Best Kotest code snippet using io.kotest.engine.tags.tags
DatexIntegrationTests.kt
Source:DatexIntegrationTests.kt
1package no.vegvesen.saga.modules.datex.inttest2import arrow.core.Either3import io.kotest.assertions.arrow.core.shouldBeRight4import io.kotest.core.annotation.Tags5import io.kotest.core.spec.style.FunSpec6import io.kotest.core.spec.style.funSpec7import io.kotest.matchers.collections.shouldContain8import io.kotest.matchers.collections.shouldHaveSize9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.shouldBe11import io.kotest.matchers.shouldNotBe12import io.kotest.matchers.string.shouldEndWith13import io.ktor.client.HttpClient14import io.ktor.client.engine.mock.MockEngine15import io.ktor.client.engine.mock.respond16import no.vegvesen.saga.modules.datex.DatexClient17import no.vegvesen.saga.modules.datex.DatexIngestProcessor18import no.vegvesen.saga.modules.datex.DatexPoller19import no.vegvesen.saga.modules.datex.DatexSettings20import no.vegvesen.saga.modules.datex.DatexStorageRepository21import no.vegvesen.saga.modules.datex.DatexValidator22import no.vegvesen.saga.modules.ktor.createApacheHttpClient23import no.vegvesen.saga.modules.shared.ContentType24import no.vegvesen.saga.modules.shared.blobstorage.FileMetadata25import no.vegvesen.saga.modules.shared.blobstorage.InMemoryBlobStorage26import no.vegvesen.saga.modules.shared.blobstorage.StoragePath27import no.vegvesen.saga.modules.shared.envOrThrow28import no.vegvesen.saga.modules.shared.functions.SimpleFunctionError29import no.vegvesen.saga.modules.shared.kvstore.InMemoryKVStore30import no.vegvesen.saga.modules.shared.services.DeadLetterStorage31import no.vegvesen.saga.modules.testing.ExternalTest32import no.vegvesen.saga.modules.testing.shouldBeLeftOfType33import no.vegvesen.saga.modules.testing.shouldBeRightAnd34@Tags(ExternalTest)35class DatexIntegrationTests : FunSpec({36 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/trafikk/2/GetSituation")37 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/trafikk/3/GetSituation")38 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/reisetid/2/GetTravelTimeData")39 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/reisetid/3/GetTravelTimeData")40 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/reisetid/2/GetPredefinedTravelTimeLocations")41 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/reisetid/3/GetPredefinedTravelTimeLocations")42 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/vaer/2/GetMeasuredWeatherData")43 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/vaer/3/GetMeasuredWeatherData")44 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/vaer/2/GetMeasurementWeatherSiteTable")45 testDatexEndpoint("https://www.vegvesen.no/ws/no/vegvesen/veg/trafikkpublikasjon/vaer/3/GetMeasurementWeatherSiteTable")46})47private fun FunSpec.testDatexEndpoint(datexEndpoint: String) {48 include(49 funSpec {50 val datexSettings = DatexSettings(datexEndpoint, envOrThrow("DATEX_USERNAME"), envOrThrow("DATEX_PASSWORD"))51 val ingestBucket = "ingest"52 val deadLetterBucket = "deadletter"53 var kvStore = InMemoryKVStore()54 val blobStorage = InMemoryBlobStorage()55 fun createDatexClient(): DatexClient = DatexClient(56 createApacheHttpClient(), datexSettings, DatexValidator()57 )58 fun createProcessor(datexClient: DatexClient, gzipped: Boolean = true): DatexIngestProcessor =59 DatexIngestProcessor(60 DatexPoller(61 datexClient,62 DatexStorageRepository(63 ingestBucket, "datasource", kvStore, blobStorage64 )65 ),66 DeadLetterStorage(blobStorage, deadLetterBucket), gzipped = gzipped67 )68 beforeEach {69 kvStore = InMemoryKVStore()70 blobStorage.clearFiles()71 }72 context(datexSettings.datexUrl) {73 test("can retrieve and save the latest publication in gzipped XML format") {74 val result = createProcessor(createDatexClient()).process()75 result.shouldBeRight()76 blobStorage.listFiles(ingestBucket).shouldBeRightAnd { files ->77 files.shouldHaveSize(1)78 val file = files[0]79 file.contentType shouldBe ContentType.Xml80 file.contentEncoding shouldBe "gzip"81 file.customTime.shouldNotBeNull()82 val storagePath = StoragePath(ingestBucket, file.fileName)83 blobStorage.loadFileAsString(storagePath) shouldBeRightAnd { xml ->84 // Optimization to avoid OutOfMemoryError85 xml.substring(0, 20).replace(Regex("ns\\d+:"), "").substring(0, 15).let<String, Unit> {86 listOf("<d2LogicalModel", "<messageContain").shouldContain(it)87 }88 }89 }90 }91 test("erronous document from Datex is stored in deadletter") {92 val mockHttpClient = HttpClient(MockEngine) {93 engine {94 addHandler {95 respond("aResponse")96 }97 }98 }99 val datexClient = DatexClient(100 mockHttpClient, datexSettings, DatexValidator()101 )102 val result = createProcessor(datexClient).process()103 val file = result.shouldBeStoredInDeadletter(blobStorage, ingestBucket, deadLetterBucket)104 file.contentEncoding shouldBe "gzip"105 }106 test("when processor is created with gzipped=false, deadletter files are not gzipped") {107 val mockHttpClient = HttpClient(MockEngine) {108 engine {109 addHandler {110 respond("aResponse")111 }112 }113 }114 val datexClient = DatexClient(115 mockHttpClient, datexSettings, DatexValidator()116 )117 val result = createProcessor(datexClient, gzipped = false).process()118 val file = result.shouldBeStoredInDeadletter(blobStorage, ingestBucket, deadLetterBucket)119 file.contentEncoding shouldNotBe "gzip"120 }121 }122 }123 )124}125private suspend fun Either<SimpleFunctionError, Unit>.shouldBeStoredInDeadletter(126 storage: InMemoryBlobStorage,127 ingestBucket: String,128 deadLetterBucket: String129): FileMetadata {130 shouldBeLeftOfType<SimpleFunctionError.UnexpectedError>()131 storage.listFiles(ingestBucket).shouldBeRightAnd { it shouldHaveSize 0 }132 val files = storage.listFiles(deadLetterBucket).shouldBeRightAnd { deadLetterFiles ->133 deadLetterFiles shouldHaveSize 1134 val file = deadLetterFiles.single()135 file.fileName shouldEndWith ".xml"136 storage.loadFile(StoragePath(deadLetterBucket, file.fileName))137 .shouldBeRightAnd { String(it) shouldBe "aResponse" }138 }139 return files.single()140}...
build.gradle.kts
Source:build.gradle.kts
...83 image = "openjdk:11-jre-slim"84 }85 to {86 image = "demo-app"87 tags = setOf("latest", "${project.name}-${project.version}")88 }89 container {90 mainClass = "com.demo.DemoApplicationKt"91 ports = listOf("8080")92 volumes = listOf("/tmp")93 user = "nobody:nogroup"94 creationTime = "USE_CURRENT_TIMESTAMP"95 }96}97tasks.jacocoTestReport {98 reports {99 // turn off/on reports100 html.required.set(true)101 xml.required.set(true)...
Kotest.kt
Source:Kotest.kt
...28 companion object {29 private const val IntellijTestListenerClassName = "IJTestEventLogger"30 private const val ReporterArg = "--reporter"31 private const val TermArg = "--termcolor"32 private const val TagsArg = "--tags"33 private const val TeamCityReporter = "teamcity"34 private const val TaycanReporter = "io.kotest.engine.reporter.TaycanConsoleReporter"35 private const val PlainColours = "ansi16"36 private const val TrueColours = "ansi256"37 }38 private val listeners = mutableListOf<TestListener>()39 private val outputListeners = mutableListOf<TestOutputListener>()40 private var tags: String? = null41 // gradle will call this if --tags was specified on the command line42 @Option(option = "tags", description = "Set tag expression to include or exclude tests")43 fun setTags(tags: String) {44 this.tags = tags45 }46 // intellij will call this to register its listeners for the test event run window47 override fun addTestListener(listener: TestListener) {48 listeners.add(listener)49 }50 override fun addTestOutputListener(listener: TestOutputListener) {51 outputListeners.add(listener)52 }53 /**54 * Returns args to be used for the tag expression.55 *56 * If --tags was passed as a command line arg, then that takes precedence over the value57 * set in the gradle build.58 *59 * Returns empty list if no tag expression was specified.60 */61 private fun tagArgs(): List<String> {62 tags?.let { return listOf(TagsArg, it) }63 project.kotest()?.tags?.orNull?.let { return listOf(TagsArg, it) }64 return emptyList()65 }66 // -- reporter was added in 4.2.167 private fun args() = when {68 isIntellij() -> listOf(ReporterArg, TeamCityReporter, TermArg, PlainColours) + tagArgs()69 else -> listOf(ReporterArg, TaycanReporter, TermArg, TrueColours) + tagArgs()70 }71 private fun exec(classpath: FileCollection): JavaExecAction {72 val exec =73 DefaultExecActionFactory.of(fileResolver, fileCollectionFactory, executorFactory, null).newJavaExecAction()74 copyTo(exec)75 exec.main = "io.kotest.engine.launcher.MainKt"76 exec.classpath = classpath77 exec.jvmArgs = allJvmArgs...
KotestEngineLauncher.kt
Source:KotestEngineLauncher.kt
...20 private val listeners: List<TestEngineListener>,21 private val specs: List<KClass<out Spec>>,22 private val testFilters: List<TestFilter>,23 private val specFilters: List<SpecFilter>,24 private val tags: TagExpression?,25 private val scripts: List<KClass<*>>,26) {27 companion object {28 fun default(29 listeners: List<TestEngineListener>,30 specs: List<KClass<out Spec>>,31 tags: TagExpression?32 ): KotestEngineLauncher {33 return KotestEngineLauncher(34 listeners = listeners,35 specs = specs,36 scripts = emptyList(),37 testFilters = emptyList(),38 specFilters = emptyList(),39 tags = tags,40 )41 }42 }43 constructor() : this(emptyList(), emptyList(), emptyList(), emptyList(), null, emptyList())44 @Deprecated("This class is deprecated since 5.0")45 fun launch(): EngineResult {46 if (listeners.isEmpty())47 error("Cannot launch a KotestEngine without at least one TestEngineListener")48 val launcher = TestEngineLauncher(49 ThreadSafeTestEngineListener(50 PinnedSpecTestEngineListener(51 CompositeTestEngineListener(listeners)52 )53 )54 ).withExtensions(testFilters)55 .withExtensions(specFilters)56 .withTagExpression(tags)57 .withClasses(specs)58 return launcher.launch()59 }60 @Deprecated("This class is deprecated since 5.0")61 fun withFilter(filter: TestFilter) = withFilters(listOf(filter))62 @Deprecated("This class is deprecated since 5.0")63 fun withListener(listener: TestEngineListener) = KotestEngineLauncher(64 listeners = this.listeners + listener,65 specs = specs,66 testFilters = testFilters,67 specFilters = specFilters,68 tags = tags,69 scripts = scripts,70 )71 @Deprecated("This class is deprecated since 5.0")72 fun withDumpConfig(dump: Boolean) = KotestEngineLauncher(73 listeners = listeners,74 specs = specs,75 testFilters = testFilters,76 specFilters = specFilters,77 tags = tags,78 scripts = scripts,79 )80 @Deprecated("This class is deprecated since 5.0")81 fun withSpecFilters(filters: List<SpecFilter>): KotestEngineLauncher {82 return KotestEngineLauncher(83 listeners = listeners,84 specs = specs,85 testFilters = testFilters,86 specFilters = specFilters + filters,87 tags = tags,88 scripts = scripts,89 )90 }91 @Deprecated("This class is deprecated since 5.0")92 fun withTestFilters(filters: List<TestFilter>): KotestEngineLauncher {93 return KotestEngineLauncher(94 listeners = listeners,95 specs = specs,96 testFilters = testFilters + filters,97 specFilters = specFilters,98 tags = tags,99 scripts = scripts,100 )101 }102 @Deprecated("This class is deprecated since 5.0")103 fun withFilters(filters: List<TestFilter>): KotestEngineLauncher = withTestFilters(filters)104 @Deprecated("This class is deprecated since 5.0")105 fun withScripts(scripts: List<KClass<*>>): KotestEngineLauncher {106 return KotestEngineLauncher(107 listeners = listeners,108 specs = specs,109 testFilters = testFilters,110 specFilters = specFilters,111 tags = tags,112 scripts = scripts,113 )114 }115 @Deprecated("This class is deprecated since 5.0")116 fun withSpec(klass: KClass<out Spec>) = withSpecs(listOf(klass))117 @Deprecated("This class is deprecated since 5.0")118 fun withSpecs(vararg specs: KClass<out Spec>) = withSpecs(specs.toList())119 @Deprecated("This class is deprecated since 5.0")120 fun withSpecs(specs: List<KClass<out Spec>>): KotestEngineLauncher {121 return KotestEngineLauncher(122 listeners = listeners,123 specs = specs,124 testFilters = testFilters,125 specFilters = specFilters,126 tags = tags,127 scripts = scripts,128 )129 }130 @Deprecated("This class is deprecated since 5.0")131 fun withTags(tags: TagExpression?): KotestEngineLauncher {132 return KotestEngineLauncher(133 listeners = listeners,134 specs = specs,135 testFilters = testFilters,136 specFilters = specFilters,137 tags = tags,138 scripts = scripts,139 )140 }141}...
TagsExcludedDiscoveryExtensionTest.kt
Source:TagsExcludedDiscoveryExtensionTest.kt
...14@ExperimentalKotest15class TagsExcludedDiscoveryExtensionTest : FunSpec() {16 init {17 test("TagsExcludedSpecInterceptor should support include & exclude") {18 val tags = TagExpression.Empty.include(NamedTag("SpecIncluded")).exclude(NamedTag("SpecExcluded"))19 val conf = ProjectConfiguration()20 conf.registry.add(SpecifiedTagsTagExtension(tags))21 // will be excluded explicitly22 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)23 .intercept(SpecRef.Reference(ExcludedSpec::class)) { error("foo") }24 // will be included as includes are ignored at the class level25 var executed = false26 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)27 .intercept(SpecRef.Reference(IncludedSpec::class)) {28 executed = true29 Result.success(emptyMap())30 }31 executed.shouldBeTrue()32 // will be included as we can must check the spec itself later to see if the test themselves have the include or exclude33 executed = false34 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)35 .intercept(SpecRef.Reference(UntaggedSpec::class)) {36 executed = true37 Result.success(emptyMap())38 }39 executed.shouldBeTrue()40 }41 test("TagsExcludedSpecInterceptor should ignore include only") {42 val tags = TagExpression.Empty.include(NamedTag("SpecIncluded"))43 val conf = ProjectConfiguration()44 conf.registry.add(SpecifiedTagsTagExtension(tags))45 var executed = false46 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)47 .intercept(SpecRef.Reference(ExcludedSpec::class)) {48 executed = true49 Result.success(emptyMap())50 }51 executed.shouldBeTrue()52 executed = false53 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)54 .intercept(SpecRef.Reference(IncludedSpec::class)) {55 executed = true56 Result.success(emptyMap())57 }58 executed.shouldBeTrue()59 executed = false60 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)61 .intercept(SpecRef.Reference(UntaggedSpec::class)) {62 executed = true63 Result.success(emptyMap())64 }65 executed.shouldBeTrue()66 }67 test("TagsExcludedSpecInterceptor should support exclude only") {68 val tags = TagExpression.Empty.exclude(NamedTag("SpecExcluded"))69 val conf = ProjectConfiguration()70 conf.registry.add(SpecifiedTagsTagExtension(tags))71 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)72 .intercept(SpecRef.Reference(ExcludedSpec::class)) {73 error("foo")74 }75 var executed = false76 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)77 .intercept(SpecRef.Reference(IncludedSpec::class)) {78 executed = true79 Result.success(emptyMap())80 }81 executed.shouldBeTrue()82 executed = false83 TagsExcludedSpecInterceptor(NoopTestEngineListener, conf)84 .intercept(SpecRef.Reference(UntaggedSpec::class)) {...
LoaderTest.kt
Source:LoaderTest.kt
...15 loader.getSources().first().contents.bufferedReader().readText() shouldBe text16 loader.loadSources() shouldHaveSize 117 loader.loadSources().first().bufferedReader().readText() shouldBe text18 }19 "!load from file in linux".config(tags = setOf(Tags.Linux)) {20 val file = tempfile(testCase.descriptor.id.value, ".kd")21 val loader = FileLoader {22 path = Path("/tmp")23 }24 val text = "Hello world!"25 file.writeText(text)26 assertSoftly {27 loader.getSources() shouldHaveSize 128 loader.loadSources().first().bufferedReader().readText() shouldBe text29 }30 }31 "load any temp file".config(tags = setOf(Tags.Linux)) {32 tempfile(testCase.descriptor.id.value, ".any")33 val loader = FileLoader {34 path = Path("/tmp")35 anySourceExtension = true36 }37 assertSoftly {38 loader.getSources() shouldBeLargerThan sequenceOf(1)39 }40 }41})...
ApiSpec.kt
Source:ApiSpec.kt
...11@OptIn(ExperimentalKotest::class)12class ApiSpec : KoinTest, FunSpec({13 val logger = KotlinLogging.logger {}14 val ktorEngine = SingleKtorTestApplicationEngine.instance15 tags(NamedTag("api"))16 context("api_user").config(tags = setOf(NamedTag("api_user"))) {17 logger.info { "========== User API Test Begin ==========" }18 ktorEngine.userApiTest(this)19 logger.info { "========== User API Test End ==========" }20 }21 context("api_login").config(tags = setOf(NamedTag("api_login"))) {22 logger.info { "========== Login API Test Begin ==========" }23 ktorEngine.loginApiTest(this)24 logger.info { "========== Login API Test End ==========" }25 }26 context("api_notification").config(tags = setOf(NamedTag("api_notification"))) {27 logger.info { "========== Notification API Test Begin ==========" }28 ktorEngine.notificationApiTest(this)29 logger.info { "========== Notification API Test End ==========" }30 }31})
SystemPropertyTagExtension.kt
Source:SystemPropertyTagExtension.kt
...5import io.kotest.core.extensions.TagExtension6import io.kotest.core.internal.KotestEngineProperties7import io.kotest.mpp.syspropOrEnv8/**9 * This [TagExtension] includes and excludes tags using the system properties:10 * [KotestEngineProperties.tagExpression], [KotestEngineProperties.includeTags]11 * and [KotestEngineProperties.excludeTags].12 *13 * Note: If [KotestEngineProperties.tagExpression] is used then the other two properties will be ignored.14 *15 * On non-JVM targets this extension will have no effect.16 */17object SystemPropertyTagExtension : TagExtension {18 override fun tags(): TagExpression {19 fun readTagsProperty(name: String): List<Tag> =20 (syspropOrEnv(name) ?: "").split(',').filter { it.isNotBlank() }.map { NamedTag(it.trim()) }21 val includedTags = readTagsProperty(KotestEngineProperties.includeTags)22 val excludedTags = readTagsProperty(KotestEngineProperties.excludeTags)23 val expression = syspropOrEnv(KotestEngineProperties.tagExpression)24 return if (expression == null) TagExpression(includedTags.toSet(), excludedTags.toSet()) else TagExpression(expression)25 }26}...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!