From bcb2569148e4878aa34e31113c935809d3fb3039 Mon Sep 17 00:00:00 2001 From: Saeed Rezaee Date: Mon, 19 Feb 2024 12:10:46 +0100 Subject: [PATCH] Add abstraction classes for tests This commit introduces the AbstractTest class for general tests. It also adds the AbstractHaraMessageTest to be used for tests dependent on the Hara client messages. Signed-off-by: Saeed Rezaee --- dependencies.gradle | 2 +- .../integrationtest/AbstractDeploymentTest.kt | 68 +---- .../AbstractHaraMessageTest.kt | 131 ++++++++++ .../ddiclient/integrationtest/AbstractTest.kt | 144 +++++++++++ .../DdiClientHttpRequestsTest.kt | 238 +++++------------- .../HawkbitDownloadOnlyDeploymentTest.kt | 9 +- .../integrationtest/HawkbitTimeForcedTest.kt | 11 +- .../utils/KotlinExFunctions.kt | 9 + 8 files changed, 358 insertions(+), 254 deletions(-) create mode 100644 src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractHaraMessageTest.kt create mode 100644 src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractTest.kt diff --git a/dependencies.gradle b/dependencies.gradle index eda8488..8bad331 100644 --- a/dependencies.gradle +++ b/dependencies.gradle @@ -26,6 +26,6 @@ ext { joda:'joda-time:joda-time:2.10.13' ] test_dependencies = [ - testng: 'org.testng:testng:7.5' + testng: 'org.testng:testng:7.9.0' ] } diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractDeploymentTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractDeploymentTest.kt index 9eae683..6e77f83 100644 --- a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractDeploymentTest.kt +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractDeploymentTest.kt @@ -17,7 +17,6 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch -import kotlinx.coroutines.runBlocking import okhttp3.OkHttpClient import org.eclipse.hara.ddiclient.api.ConfigDataProvider import org.eclipse.hara.ddiclient.api.DeploymentPermitProvider @@ -30,35 +29,20 @@ import org.eclipse.hara.ddiclient.api.MessageListener import org.eclipse.hara.ddiclient.api.Updater import org.eclipse.hara.ddiclient.integrationtest.api.management.Action import org.eclipse.hara.ddiclient.integrationtest.api.management.ActionStatus -import org.eclipse.hara.ddiclient.integrationtest.api.management.HawkbitAssignDistributionBody -import org.eclipse.hara.ddiclient.integrationtest.api.management.HawkbitTargetInfo -import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementApi -import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementClient -import org.eclipse.hara.ddiclient.integrationtest.api.management.ServerSystemConfig import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils import org.eclipse.hara.ddiclient.integrationtest.utils.addOkhttpLogger import org.eclipse.hara.ddiclient.integrationtest.utils.internalLog -import org.testng.Assert -import org.testng.annotations.AfterTest -import org.testng.annotations.BeforeTest +import org.eclipse.hara.ddiclient.integrationtest.utils.safeStopClient import java.io.File -import java.lang.Exception import kotlin.coroutines.cancellation.CancellationException import kotlin.time.Duration.Companion.seconds -abstract class AbstractDeploymentTest { - - protected lateinit var managementApi: ManagementApi - abstract val targetId: String - protected var actionId: Int = 0 +abstract class AbstractDeploymentTest: AbstractTest() { private var assertServerActionsScope = CoroutineScope(Dispatchers.IO) private var assertServerActionsOnCompleteJob: Deferred? = null private var testScope = CoroutineScope(Dispatchers.Default) - private val throwableScope = CoroutineScope(Dispatchers.Default) - private var throwableJob: Deferred? = null - private val eventListener = object : MessageListener { override fun onMessage(message: MessageListener.Message) { "Message received: $message".internalLog() @@ -80,18 +64,6 @@ abstract class AbstractDeploymentTest { } } - @BeforeTest - open fun beforeTest() { - managementApi = ManagementClient.newInstance(TestUtils.hawkbitUrl) - } - - @AfterTest - open fun afterTest() { - } - - protected fun setPollingTime(time: String) = runBlocking { - managementApi.setPollingTime(TestUtils.basic, ServerSystemConfig(time)) - } protected fun defaultClientFromTargetId( directoryDataProvider: DirectoryForArtifactsProvider = TestUtils.directoryDataProvider, @@ -139,26 +111,6 @@ abstract class AbstractDeploymentTest { deploymentPermitProvider = deploymentBehavior).invoke(targetId) } - protected suspend fun reCreateTestTargetOnServer() { - runCatching { - managementApi.deleteTarget(TestUtils.basic, targetId) - } - runCatching { - managementApi.createTarget( - TestUtils.basic, listOf(HawkbitTargetInfo(targetId))) - } - } - - protected suspend fun assignDistributionToTheTarget( - distribution: HawkbitAssignDistributionBody) { - val response = - managementApi.assignDistributionToTarget(TestUtils.basic, - targetId, distribution) - if (response.assignedActions.isNotEmpty()) { - actionId = response.assignedActions.first().id - } - } - protected suspend fun startTheTestAndWaitForResult(client: HaraClient, deployment: TestUtils.TargetDeployments) { client.startAsync() @@ -202,20 +154,4 @@ abstract class AbstractDeploymentTest { TestUtils.firstActionWithAssignmentEntry )) - private suspend fun assertEquals(actual: Any?, expected: Any?) { - throwableJob = throwableScope.async { - Assert.assertEquals(actual, expected) - } - try { - throwableJob?.await() - } catch (ignored: CancellationException) { - } - } - - private fun HaraClient.safeStopClient() { - try { - stop() - } catch (ignored: Exception) { - } - } } \ No newline at end of file diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractHaraMessageTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractHaraMessageTest.kt new file mode 100644 index 0000000..b6ba566 --- /dev/null +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractHaraMessageTest.kt @@ -0,0 +1,131 @@ +/* + * + * * Copyright © 2017-2024 Kynetics LLC + * * + * * This program and the accompanying materials are made + * * available under the terms of the Eclipse Public License 2.0 + * * which is available at https://www.eclipse.org/legal/epl-2.0/ + * * + * * SPDX-License-Identifier: EPL-2.0 + * + */ + +package org.eclipse.hara.ddiclient.integrationtest + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.channels.BufferOverflow +import kotlinx.coroutines.channels.Channel +import kotlinx.coroutines.launch +import okhttp3.OkHttpClient +import org.eclipse.hara.ddiclient.api.ConfigDataProvider +import org.eclipse.hara.ddiclient.api.DeploymentPermitProvider +import org.eclipse.hara.ddiclient.api.DirectoryForArtifactsProvider +import org.eclipse.hara.ddiclient.api.DownloadBehavior +import org.eclipse.hara.ddiclient.api.HaraClient +import org.eclipse.hara.ddiclient.api.MessageListener +import org.eclipse.hara.ddiclient.api.Updater +import org.eclipse.hara.ddiclient.integrationtest.utils.internalLog +import kotlin.coroutines.cancellation.CancellationException + +abstract class AbstractHaraMessageTest : AbstractTest() { + + private var expectedHaraMessages = mutableListOf() + open val expectedMessagesAssertionListener: + List Unit> = listOf() + + private val expectedMessageChannel = + Channel(5, BufferOverflow.DROP_OLDEST) + + private val checkMessagesScope = CoroutineScope(Dispatchers.IO) + private var checkExpectedMessagesJob: Deferred? = null + + open val expectedMessagesList: MutableList> = + mutableListOf(expectedHaraMessages) + + open fun filterHaraMessages(message: MessageListener.Message): Boolean = true + + protected fun sendExpectedMessage(message: ExpectedMessage) { + checkMessagesScope.launch { + expectedMessageChannel.send(message) + } + } + + protected suspend fun startWatchingExpectedMessages(lastTest: Boolean = false) { + checkExpectedMessagesJob = getExpectedMessagesCheckingJob(lastTest) + try { + checkExpectedMessagesJob?.await() + } catch (ignored: CancellationException) { + } + } + + open val messageListener: MessageListener + get() = object : MessageListener { + override fun onMessage(message: MessageListener.Message) { + "Received message: $message".internalLog() + if (filterHaraMessages(message)) { + sendExpectedMessage(ExpectedMessage.HaraMessage(message)) + } + } + } + + private suspend fun getExpectedMessagesCheckingJob(lastTest: Boolean): Deferred { + return checkMessagesScope.async { + for (msg in expectedMessageChannel) { + when (msg) { + is ExpectedMessage.HaraMessage -> { + if (expectedHaraMessages.isNotEmpty()) { + assertEquals(msg, expectedHaraMessages.removeFirst()) + } + } + + else -> { + expectedMessagesAssertionListener.forEach { + it.invoke(msg) + } + } + } + val finished = expectedMessagesList.map { + it.isEmpty() + } + if (finished.all { it }) { + "All expected messages received".internalLog() + checkExpectedMessagesJob?.cancel() + if (lastTest) { + safeStopClient() + } + } + } + } + } + + override fun clientFromTargetId( + directoryDataProvider: DirectoryForArtifactsProvider, + configDataProvider: ConfigDataProvider, updater: Updater, + messageListeners: List, + deploymentPermitProvider: DeploymentPermitProvider, + downloadBehavior: DownloadBehavior, + okHttpClientBuilder: OkHttpClient.Builder, + targetToken: String?, + gatewayToken: String?): (String) -> HaraClient { + return super.clientFromTargetId( + directoryDataProvider, configDataProvider, updater, + listOf(messageListener), + deploymentPermitProvider, + downloadBehavior, okHttpClientBuilder, + targetToken, gatewayToken) + } + + protected fun expectMessages(vararg messages: MessageListener.Message) { + expectedHaraMessages.clear() + expectedHaraMessages.addAll(messages.map { ExpectedMessage.HaraMessage(it) }) + } + + + sealed class ExpectedMessage { + + data class HaraMessage(val message: MessageListener.Message) : ExpectedMessage() + } +} \ No newline at end of file diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractTest.kt new file mode 100644 index 0000000..aa524cc --- /dev/null +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/AbstractTest.kt @@ -0,0 +1,144 @@ +/* + * + * * Copyright © 2017-2024 Kynetics LLC + * * + * * This program and the accompanying materials are made + * * available under the terms of the Eclipse Public License 2.0 + * * which is available at https://www.eclipse.org/legal/epl-2.0/ + * * + * * SPDX-License-Identifier: EPL-2.0 + * + */ + +package org.eclipse.hara.ddiclient.integrationtest + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.async +import kotlinx.coroutines.runBlocking +import okhttp3.OkHttpClient +import org.eclipse.hara.ddiclient.api.ConfigDataProvider +import org.eclipse.hara.ddiclient.api.DeploymentPermitProvider +import org.eclipse.hara.ddiclient.api.DirectoryForArtifactsProvider +import org.eclipse.hara.ddiclient.api.DownloadBehavior +import org.eclipse.hara.ddiclient.api.HaraClient +import org.eclipse.hara.ddiclient.api.HaraClientData +import org.eclipse.hara.ddiclient.api.HaraClientDefaultImpl +import org.eclipse.hara.ddiclient.api.MessageListener +import org.eclipse.hara.ddiclient.api.Updater +import org.eclipse.hara.ddiclient.integrationtest.api.management.HawkbitAssignDistributionBody +import org.eclipse.hara.ddiclient.integrationtest.api.management.HawkbitTargetInfo +import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementApi +import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementClient +import org.eclipse.hara.ddiclient.integrationtest.api.management.ServerSystemConfig +import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils +import org.eclipse.hara.ddiclient.integrationtest.utils.addOkhttpLogger +import org.testng.Assert +import org.testng.annotations.AfterClass +import org.testng.annotations.BeforeClass +import java.lang.Exception +import kotlin.coroutines.cancellation.CancellationException + +abstract class AbstractTest { + + protected lateinit var managementApi: ManagementApi + abstract val targetId: String + + private val throwableScope = CoroutineScope(Dispatchers.Default) + + private var throwableJob: Deferred? = null + + protected var client: HaraClient? = null + set(value) { + safeStopClient() + field = value + } + + + @BeforeClass + open fun beforeTest() { + managementApi = ManagementClient.newInstance(TestUtils.hawkbitUrl) + } + + @AfterClass + open fun afterTest() { + } + + + protected fun setPollingTime(time: String) = runBlocking { + managementApi.setPollingTime(TestUtils.basic, ServerSystemConfig(time)) + } + + protected suspend fun reCreateTestTargetOnServer() { + runCatching { + managementApi.deleteTarget(TestUtils.basic, targetId) + } + runCatching { + managementApi.createTarget( + TestUtils.basic, listOf(HawkbitTargetInfo(targetId))) + } + } + + protected suspend fun assignDistributionToTheTarget( + distribution: HawkbitAssignDistributionBody): Int { + val response = + managementApi.assignDistributionToTarget(TestUtils.basic, + targetId, distribution) + if (response.assignedActions.isNotEmpty()) { + return response.assignedActions.first().id + } + return -1 + } + + protected fun safeStopClient() { + try { + client?.stop() + } catch (ignored: Exception) { + } + } + + protected suspend fun assertEquals(actual: Any?, expected: Any?) { + throwableJob = throwableScope.async { + Assert.assertEquals(actual, expected) + } + try { + throwableJob?.await() + } catch (ignored: CancellationException) { + } + } + + open fun clientFromTargetId( + directoryDataProvider: DirectoryForArtifactsProvider = TestUtils.directoryDataProvider, + configDataProvider: ConfigDataProvider = TestUtils.configDataProvider, + updater: Updater = TestUtils.updater, + messageListeners: List = listOf(), + deploymentPermitProvider: DeploymentPermitProvider = object : + DeploymentPermitProvider {}, + downloadBehavior: DownloadBehavior = TestUtils.downloadBehavior, + okHttpClientBuilder: OkHttpClient.Builder = OkHttpClient.Builder().addOkhttpLogger(), + targetToken: String? = "", + gatewayToken: String? = TestUtils.gatewayToken): (String) -> HaraClient = + { targetId -> + val clientData = HaraClientData( + TestUtils.tenantName, + targetId, + TestUtils.hawkbitUrl, + gatewayToken, targetToken) + + val client = HaraClientDefaultImpl() + + client.init( + clientData, + directoryDataProvider, + configDataProvider, + deploymentPermitProvider, + listOf(*messageListeners.toTypedArray()), + listOf(updater), + downloadBehavior, + httpBuilder = okHttpClientBuilder + ) + + client + } +} \ No newline at end of file diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/DdiClientHttpRequestsTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/DdiClientHttpRequestsTest.kt index 1263634..4949611 100644 --- a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/DdiClientHttpRequestsTest.kt +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/DdiClientHttpRequestsTest.kt @@ -9,155 +9,99 @@ */ package org.eclipse.hara.ddiclient.integrationtest -import kotlinx.coroutines.CancellationException -import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.Deferred -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.async -import kotlinx.coroutines.channels.BufferOverflow -import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.delay -import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import okhttp3.Interceptor import okhttp3.OkHttpClient import org.eclipse.hara.ddi.security.Authentication -import org.eclipse.hara.ddiclient.api.ConfigDataProvider -import org.eclipse.hara.ddiclient.api.DeploymentPermitProvider -import org.eclipse.hara.ddiclient.api.DirectoryForArtifactsProvider -import org.eclipse.hara.ddiclient.api.DownloadBehavior import org.eclipse.hara.ddiclient.api.HaraClient -import org.eclipse.hara.ddiclient.api.HaraClientData -import org.eclipse.hara.ddiclient.api.HaraClientDefaultImpl import org.eclipse.hara.ddiclient.api.MessageListener import org.eclipse.hara.ddiclient.api.MessageListener.Message.Event.Polling import org.eclipse.hara.ddiclient.api.MessageListener.Message.State.Idle -import org.eclipse.hara.ddiclient.api.Updater -import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementApi -import org.eclipse.hara.ddiclient.integrationtest.api.management.ManagementClient import org.eclipse.hara.ddiclient.integrationtest.api.management.ServerSystemConfig import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.basic import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.gatewayToken import org.eclipse.hara.ddiclient.integrationtest.utils.addOkhttpLogger -import org.eclipse.hara.ddiclient.integrationtest.utils.internalLog import org.eclipse.hara.ddiclient.integrationtest.utils.logCurrentFunctionName -import org.testng.Assert -import org.testng.annotations.AfterTest -import org.testng.annotations.BeforeTest +import org.testng.annotations.AfterClass +import org.testng.annotations.BeforeClass import org.testng.annotations.Test -import java.lang.Exception import java.net.HttpURLConnection import kotlin.time.Duration.Companion.seconds -class DdiClientHttpRequestsTest { +class DdiClientHttpRequestsTest : AbstractHaraMessageTest() { - private lateinit var managementApi: ManagementApi + override val targetId: String = "DoubleToken" + private var expectedServerResponses = mutableListOf() - private var expectedMessages = mutableListOf() - private var expectedServerResponses = mutableListOf() - private val expectedMessageChannel = - Channel(5, BufferOverflow.DROP_OLDEST) + override val expectedMessagesList: MutableList> by lazy { + super.expectedMessagesList.apply { + add(expectedServerResponses) + } + } - private val checkMessagesScope = CoroutineScope(Dispatchers.IO) - private val throwableScope = CoroutineScope(Dispatchers.Default) + override val expectedMessagesAssertionListener = + listOf(checkOkHttpExpectedMessages()) - private var checkExpectedMessagesJob: Deferred? = null - private var throwableJob: Deferred? = null - private var client: HaraClient?= null - set(value) { - safeStopClient() - field = value + private fun checkOkHttpExpectedMessages(): suspend (ExpectedMessage) -> Unit = { msg -> + if (expectedServerResponses.isNotEmpty()) { + assertEquals(msg, expectedServerResponses.removeFirst()) } + } companion object { - const val TEST_TARGET_ID = "DoubleToken" const val TEST_TARGET_SECURITY_TOKEN = "r2m3ixxc86a2v4q81wntpyhr78zy08we" } - private val messageListener: MessageListener - get() = object : MessageListener { - override fun onMessage(message: MessageListener.Message) { - "Received message: $message".internalLog() - if (message is Polling || message is Idle) { - checkMessagesScope.launch { - expectedMessageChannel.send(ExpectedMessage.HaraMessage(message)) - } - } - } + override fun filterHaraMessages(message: MessageListener.Message): Boolean { + return message is Polling || message is Idle } - @BeforeTest - fun beforeTest() { - managementApi = ManagementClient.newInstance(TestUtils.hawkbitUrl) - runBlocking { - managementApi.setPollingTime(basic, ServerSystemConfig("00:00:05")) - } + @BeforeClass + override fun beforeTest() { + super.beforeTest() + setPollingTime("00:00:05") } - @AfterTest - fun afterTest() { + @AfterClass + override fun afterTest() { + setPollingTime("00:00:30") runBlocking { - managementApi.setPollingTime(basic, ServerSystemConfig("00:00:30")) enableTargetTokenInServer(true) enableGatewayTokenInServer(true) } } - private fun clientFromTargetId( - directoryDataProvider: DirectoryForArtifactsProvider = TestUtils.directoryDataProvider, - configDataProvider: ConfigDataProvider = TestUtils.configDataProvider, - updater: Updater = TestUtils.updater, - deploymentPermitProvider: DeploymentPermitProvider = object : - DeploymentPermitProvider {}, - downloadBehavior: DownloadBehavior = TestUtils.downloadBehavior, + private fun createClient( targetToken: String? = TEST_TARGET_SECURITY_TOKEN, - gatewayToken: String? = TestUtils.gatewayToken): (String) -> HaraClient = - { targetId -> - val clientData = HaraClientData( - TestUtils.tenantName, - targetId, - TestUtils.hawkbitUrl, - gatewayToken, targetToken) - - val client = HaraClientDefaultImpl() - - val okHttpClient = OkHttpClient.Builder().apply { - addInterceptor(Interceptor { chain -> - val request = chain.request() - val response = chain.proceed(request) - - val actualServerResponse = ExpectedMessage.OkHttpMessage( - response.code, request.header("Authorization")) - - checkMessagesScope.launch { - expectedMessageChannel.send(actualServerResponse) - } - response - }) - addOkhttpLogger() - } - client.init( - clientData, - directoryDataProvider, - configDataProvider, - deploymentPermitProvider, - listOf(messageListener), - listOf(updater), - downloadBehavior, - httpBuilder = okHttpClient - ) - - client + gatewayToken: String? = TestUtils.gatewayToken): HaraClient { + + val okHttpClient = OkHttpClient.Builder().apply { + addInterceptor(Interceptor { chain -> + val request = chain.request() + val response = chain.proceed(request) + + val actualServerResponse = OkHttpMessage( + response.code, request.header("Authorization")) + + sendExpectedMessage(actualServerResponse) + response + }) + addOkhttpLogger() } + return clientFromTargetId( + okHttpClientBuilder = okHttpClient, + targetToken = targetToken, + gatewayToken = gatewayToken).invoke(targetId) + } + @Suppress("UNUSED_VARIABLE") @Test(enabled = true, priority = 1) fun useEmptyTokensTest() = runBlocking { try { - val client = clientFromTargetId(targetToken = "", gatewayToken = "").also { - it.invoke(TEST_TARGET_ID) - } + val client = createClient(targetToken = "", gatewayToken = "") } catch (e: Throwable) { assertEquals(e.message, "gatewayToken and targetToken cannot both be empty") } @@ -166,7 +110,7 @@ class DdiClientHttpRequestsTest { @Test(enabled = true, timeOut = 60_000, priority = 2) fun useOnlyGatewayTokenTest() { runBlocking { - client = clientFromTargetId(targetToken = "").invoke(TEST_TARGET_ID) + client = createClient(targetToken = "") enableTargetTokenInServer(false) enableGatewayTokenInServer(false) @@ -200,8 +144,7 @@ class DdiClientHttpRequestsTest { enableGatewayTokenInServer() val invalidGatewayToken = "InValidToken" - client = clientFromTargetId(targetToken = "", - gatewayToken = invalidGatewayToken).invoke(TEST_TARGET_ID) + client = createClient(targetToken = "", gatewayToken = invalidGatewayToken) expectPollingOnlyMessage() expectedServerResponses.apply { add(gatewayTokenMessage(HttpURLConnection.HTTP_UNAUTHORIZED, invalidGatewayToken)) @@ -212,7 +155,7 @@ class DdiClientHttpRequestsTest { @Test(enabled = true, timeOut = 60_000, priority = 3) fun useOnlyTargetTokenTest() { runBlocking { - client = clientFromTargetId(gatewayToken = "").invoke(TEST_TARGET_ID) + client = createClient(gatewayToken = "") enableTargetTokenInServer(false) enableGatewayTokenInServer(false) @@ -246,8 +189,7 @@ class DdiClientHttpRequestsTest { enableTargetTokenInServer() val invalidTargetToken = "InValidToken" - client = clientFromTargetId(targetToken = invalidTargetToken, - gatewayToken = "").invoke(TEST_TARGET_ID) + client = createClient(targetToken = invalidTargetToken, gatewayToken = "") expectPollingOnlyMessage() expectedServerResponses.apply { add(targetTokenMessage(HttpURLConnection.HTTP_UNAUTHORIZED, invalidTargetToken)) @@ -259,7 +201,7 @@ class DdiClientHttpRequestsTest { @Test(enabled = true, timeOut = 60_000, priority = 4) fun usingEmptyTargetTokenRequestShouldOnlyUseGatewayTokenTest() { runBlocking { - client = clientFromTargetId(targetToken = "").invoke(TEST_TARGET_ID) + client = createClient(targetToken = "") enableTargetTokenInServer(false) enableGatewayTokenInServer(true) @@ -282,7 +224,7 @@ class DdiClientHttpRequestsTest { runBlocking { enableTargetTokenInServer(true) enableGatewayTokenInServer(false) - client = clientFromTargetId(gatewayToken = "").invoke(TEST_TARGET_ID) + client = createClient(gatewayToken = "") `test #4-1= request should succeed with target token, when gateway token is empty`() } @@ -300,7 +242,7 @@ class DdiClientHttpRequestsTest { @Test(enabled = true, timeOut = 200_000, priority = 6) fun providingBothTokensTest() { runBlocking { - client = clientFromTargetId().invoke(TEST_TARGET_ID) + client = createClient() enableTargetTokenInServer(false) enableGatewayTokenInServer(false) @@ -381,27 +323,12 @@ class DdiClientHttpRequestsTest { startWatchingExpectedMessages(lastTest) } - private suspend fun startWatchingExpectedMessages(lastTest: Boolean = false) { - checkExpectedMessagesJob = getExpectedMessagesCheckingJob(lastTest) - try { - checkExpectedMessagesJob?.await() - } catch (ignored: CancellationException) { - } - } - private fun expectPollingAndIdleMessages() { - expectedMessages.clear() - expectedMessages.apply { - add(ExpectedMessage.HaraMessage(Polling)) - add(ExpectedMessage.HaraMessage(Idle)) - } + expectMessages(Polling, Idle) } private fun expectPollingOnlyMessage() { - expectedMessages.clear() - expectedMessages.apply { - add(ExpectedMessage.HaraMessage(Polling)) - } + expectMessages(Polling) } private suspend fun enableGatewayTokenInServer(enabled: Boolean = true) { @@ -416,7 +343,7 @@ class DdiClientHttpRequestsTest { private fun targetTokenMessage(responseCode: Int = HttpURLConnection.HTTP_OK, token: String = TEST_TARGET_SECURITY_TOKEN) = - ExpectedMessage.OkHttpMessage( + OkHttpMessage( responseCode, Authentication.newInstance( Authentication.AuthenticationType.TARGET_TOKEN_AUTHENTICATION, @@ -426,7 +353,7 @@ class DdiClientHttpRequestsTest { private fun gatewayTokenMessage(responseCode: Int = HttpURLConnection.HTTP_OK, token: String = gatewayToken) = - ExpectedMessage.OkHttpMessage( + OkHttpMessage( responseCode, Authentication.newInstance( Authentication.AuthenticationType.GATEWAY_TOKEN_AUTHENTICATION, @@ -434,52 +361,7 @@ class DdiClientHttpRequestsTest { ).headerValue ) - private suspend fun assertEquals(actual: Any?, expected: Any?) { - throwableJob = throwableScope.async { - Assert.assertEquals(actual, expected) - } - try { - throwableJob?.await() - } catch (ignored: CancellationException) { - } - } - - private suspend fun getExpectedMessagesCheckingJob(lastTest: Boolean): Deferred { - return checkMessagesScope.async { - for (msg in expectedMessageChannel) { - when (msg) { - is ExpectedMessage.HaraMessage -> { - if (expectedMessages.isNotEmpty()) { - assertEquals(msg, expectedMessages.removeFirst()) - } - } - - is ExpectedMessage.OkHttpMessage -> { - if (expectedServerResponses.isNotEmpty()) { - assertEquals(msg, expectedServerResponses.removeFirst()) - } - } - } - if (expectedMessages.isEmpty() && expectedServerResponses.isEmpty()) { - "All expected messages received".internalLog() - checkExpectedMessagesJob?.cancel() - if (lastTest) { - safeStopClient() - } - } - } - } - } + data class OkHttpMessage(val code: Int, val authHeader: String?) : + ExpectedMessage() - private fun safeStopClient() { - try { - client?.stop() - } catch (ignored: Exception) { - } - } - - sealed class ExpectedMessage { - data class HaraMessage(val message: MessageListener.Message) : ExpectedMessage() - data class OkHttpMessage(val code: Int, val authHeader: String?) : ExpectedMessage() - } } diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitDownloadOnlyDeploymentTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitDownloadOnlyDeploymentTest.kt index e667f80..80e1610 100644 --- a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitDownloadOnlyDeploymentTest.kt +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitDownloadOnlyDeploymentTest.kt @@ -18,24 +18,25 @@ import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.endMessagesOnS import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.messagesOnSoftUpdateAuthorization import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.messagesOnSuccessfullyDownloadDistribution import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.targetRetrievedUpdateAction -import org.testng.annotations.BeforeTest +import org.testng.annotations.BeforeClass import org.testng.annotations.Test class HawkbitDownloadOnlyDeploymentTest : AbstractDeploymentTest() { + private var actionId: Int = 0 override val targetId: String = "DownloadOnlyTest" companion object { const val DISTRIBUTION_ID = 3 } - @BeforeTest + @BeforeClass override fun beforeTest() { super.beforeTest() setPollingTime("00:00:05") } - @Test(enabled = true, timeOut = 60_000) + @Test(enabled = true, timeOut = 60_000, priority = 3) fun testDownloadOnlyWhileWaitingForUpdateAuthorization() = runBlocking { reCreateTestTargetOnServer() @@ -52,7 +53,7 @@ class HawkbitDownloadOnlyDeploymentTest : AbstractDeploymentTest() { private suspend fun assignDownloadOnlyDistribution() { val distribution = HawkbitAssignDistributionBody(DISTRIBUTION_ID, AssignDistributionType.DOWNLOAD_ONLY, 0) - assignDistributionToTheTarget(distribution) + actionId = assignDistributionToTheTarget(distribution) } private fun createTargetTestDeployment( diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitTimeForcedTest.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitTimeForcedTest.kt index 8fae696..8b84b33 100644 --- a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitTimeForcedTest.kt +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/HawkbitTimeForcedTest.kt @@ -19,25 +19,26 @@ import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.firstActionWit import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.messagesOnSoftDownloadAuthorization import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.waitingForDownloadAuthorizationMessage import org.eclipse.hara.ddiclient.integrationtest.utils.TestUtils.waitingForUpdateAuthorizationMessage -import org.testng.annotations.BeforeTest +import org.testng.annotations.BeforeClass import org.testng.annotations.Test import kotlin.time.Duration.Companion.seconds class HawkbitTimeForcedTest : AbstractDeploymentTest() { + private var actionId: Int = 0 override val targetId: String = "TimeForceTest" companion object { const val DISTRIBUTION_ID = 3 } - @BeforeTest + @BeforeClass override fun beforeTest() { super.beforeTest() setPollingTime("00:00:10") } - @Test(enabled = true, timeOut = 150_000) + @Test(enabled = true, timeOut = 150_000, priority = 1) fun testTimeForcedUpdateWhileWaitingForDownloadAuthorization() = runBlocking { reCreateTestTargetOnServer() @@ -52,7 +53,7 @@ class HawkbitTimeForcedTest : AbstractDeploymentTest() { } - @Test(enabled = true, timeOut = 150_000) + @Test(enabled = true, timeOut = 150_000, priority = 2) fun testTimeForcedUpdateWhileWaitingForUpdateAuthorization() = runBlocking { reCreateTestTargetOnServer() @@ -116,6 +117,6 @@ class HawkbitTimeForcedTest : AbstractDeploymentTest() { val distribution = HawkbitAssignDistributionBody( DISTRIBUTION_ID, AssignDistributionType.TIME_FORCED, System.currentTimeMillis() + timeForcedTime) - assignDistributionToTheTarget(distribution) + actionId = assignDistributionToTheTarget(distribution) } } \ No newline at end of file diff --git a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/utils/KotlinExFunctions.kt b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/utils/KotlinExFunctions.kt index 22de11f..96b3541 100644 --- a/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/utils/KotlinExFunctions.kt +++ b/src/test/kotlin/org/eclipse/hara/ddiclient/integrationtest/utils/KotlinExFunctions.kt @@ -10,6 +10,8 @@ package org.eclipse.hara.ddiclient.integrationtest.utils +import org.eclipse.hara.ddiclient.api.HaraClient +import java.lang.Exception import java.text.SimpleDateFormat import java.util.Date @@ -28,4 +30,11 @@ fun String.internalLog() { @Suppress("NOTHING_TO_INLINE") inline fun logCurrentFunctionName() { "Running Test: ${Thread.currentThread().stackTrace[1].methodName}".log() +} + +fun HaraClient.safeStopClient() { + try { + stop() + } catch (ignored: Exception) { + } } \ No newline at end of file