Best Kotest code snippet using io.kotest.core.spec.listeners
S3StorageServiceSpec.kt
Source:S3StorageServiceSpec.kt
1package network.as2.persistence.s32import com.amazonaws.services.s3.AmazonS33import com.fasterxml.jackson.databind.ObjectMapper4import com.freighttrust.testing.generators.textDataHandlerGenerator5import com.freighttrust.testing.listeners.FlywayTestListener6import com.freighttrust.testing.listeners.PostgresTestListener7import com.freighttrust.testing.listeners.S3TestListener8import com.github.javafaker.Faker9import io.kotest.core.listeners.TestListener10import io.kotest.core.spec.Spec11import io.kotest.core.spec.style.BehaviorSpec12import io.kotest.koin.KoinLifecycleMode13import io.kotest.koin.KoinListener14import io.kotest.matchers.shouldBe15import io.kotest.matchers.shouldNotBe16import io.kotest.property.RandomSource17import kotlinx.coroutines.Dispatchers18import kotlinx.coroutines.withContext19import network.as2.common.AppConfigModule20import network.as2.jooq.enums.FileProvider21import network.as2.persistence.extensions.metadataForS322import network.as2.persistence.postgres.PostgresPersistenceModule23import network.as2.serialisation.JsonModule24import org.koin.core.context.stopKoin25import org.koin.test.KoinTest26import org.koin.test.inject27import kotlin.random.asJavaRandom28@Suppress("BlockingMethodInNonBlockingContext")29class S3StorageServiceSpec : BehaviorSpec(), KoinTest {30 private val bucket = "s3-file-service-spec"31 override fun listeners(): List<TestListener> =32 listOf(33 listOf(34 S3TestListener(bucket)35 .apply { listener(this) }36 ),37 PostgresTestListener()38 .let { postgresListener ->39 listOf(40 postgresListener,41 FlywayTestListener(postgresListener.container)42 )43 },44 listOf(45 KoinListener(...
LocalStorageServiceSpec.kt
Source:LocalStorageServiceSpec.kt
1package network.as2.persistence.local2import com.fasterxml.jackson.databind.ObjectMapper3import com.freighttrust.testing.generators.textDataHandlerGenerator4import com.freighttrust.testing.listeners.FlywayTestListener5import com.freighttrust.testing.listeners.PostgresTestListener6import com.github.javafaker.Faker7import io.kotest.core.listeners.TestListener8import io.kotest.core.spec.Spec9import io.kotest.core.spec.style.BehaviorSpec10import io.kotest.koin.KoinLifecycleMode11import io.kotest.koin.KoinListener12import io.kotest.matchers.shouldBe13import io.kotest.matchers.shouldNotBe14import io.kotest.property.RandomSource15import kotlinx.coroutines.Dispatchers16import kotlinx.coroutines.withContext17import network.as2.common.AppConfigModule18import network.as2.jooq.enums.FileProvider19import network.as2.persistence.extensions.metadataForLocal20import network.as2.persistence.postgres.PostgresPersistenceModule21import network.as2.serialisation.JsonModule22import org.koin.core.context.stopKoin23import org.koin.test.KoinTest24import org.koin.test.inject25import java.io.BufferedInputStream26import java.io.FileInputStream27import kotlin.random.asJavaRandom28@Suppress("BlockingMethodInNonBlockingContext")29class LocalStorageServiceSpec : BehaviorSpec(), KoinTest {30 override fun listeners(): List<TestListener> =31 listOf(32 PostgresTestListener()33 .let { postgresListener ->34 listOf(35 postgresListener,36 FlywayTestListener(postgresListener.container)37 )38 },39 listOf(40 KoinListener(41 modules = listOf(42 AppConfigModule,43 JsonModule,44 LocalPersistenceModule,...
KotestStringSpecTest.kt
Source:KotestStringSpecTest.kt
1package com.example.kotest2import com.example.logger3import io.kotest.assertions.fail4import io.kotest.core.extensions.Extension5import io.kotest.core.listeners.TestListener6import io.kotest.core.spec.Spec7import io.kotest.core.spec.style.StringSpec8import io.kotest.core.test.TestCase9import io.kotest.core.test.TestResult10import kotlin.reflect.KClass11class KotestStringSpecTest : StringSpec({12 val logger = logger<KotestStringSpecTest>()13 val list = mutableListOf<String>()14 fun add(item: String) {15 list.add(item)16 }17 add("init-1")18 logger.info("init 1, list: {}", list)19 "foo" {20 add("foo")21 logger.info("foo, list: {}", list)22 }23 add("init-2")24 logger.info("init 2, list: {}", list)25 "fail" {26 add("fail")27 logger.info("fail, list: {}", list)28 fail("fail, list: $list")29 }30 "bar" {31 add("bar")32 logger.info("bar, list: {}", list)33 }34})35class KotestStringSpecTest2: StringSpec() {36 private val logger = logger<KotestStringSpecTest2>()37 init {38 val list = mutableListOf<String>()39 fun add(item: String) {40 list.add(item)41 }42 add("init-1")43 logger.info("init 1, list: {}", list)44 "foo" {45 add("foo")46 logger.info("foo, list: {}", list)47 }48 add("init-2")49 logger.info("init 2, list: {}", list)50 "fail" {51 add("fail")52 logger.info("fail, list: {}", list)53 fail("fail, list: $list")54 }55 "bar" {56 add("bar")57 logger.info("bar, list: {}", list)58 }59 }60 override fun afterSpec(spec: Spec) {61 logger.info("afterSpec")62 }63 override fun afterTest(testCase: TestCase, result: TestResult) {64 logger.info("afterTest")65 }66 override fun beforeSpec(spec: Spec) {67 logger.info("beforeSpec")68 }69 override fun beforeTest(testCase: TestCase) {70 logger.info("beforeTest")71 }72 override fun extensions(): List<Extension> {73 logger.info("extensions")74 return listOf(object : Extension {})75 }76 override fun listeners(): List<TestListener> {77 logger.info("listeners")78 return listOf(ExampleListener)79 }80}81object ExampleListener: TestListener {82 private val logger = logger<ExampleListener>()83 override suspend fun afterInvocation(testCase: TestCase, iteration: Int) {84 logger.info("afterInvocation ${testCase.displayName}")85 }86 override suspend fun afterSpec(spec: Spec) {87 val names = spec.rootTests().map { it.testCase.displayName }88 logger.info("afterSpec $names")89 }90 override suspend fun afterTest(testCase: TestCase, result: TestResult) {91 logger.info("afterTest ${testCase.displayName}, ${result.status} ${result.reason} ${result.error}")...
TestContainerExtension.kt
Source:TestContainerExtension.kt
1package io.kotest.extensions.testcontainers2import io.kotest.core.extensions.MountableExtension3import io.kotest.core.listeners.AfterSpecListener4import io.kotest.core.listeners.TestListener5import io.kotest.core.spec.Spec6import io.kotest.core.test.TestCase7import io.kotest.core.test.TestResult8import io.kotest.core.test.TestType9import io.kotest.core.test.isRootTest10import kotlinx.coroutines.Dispatchers11import kotlinx.coroutines.withContext12import org.testcontainers.containers.GenericContainer13import org.testcontainers.lifecycle.TestLifecycleAware14import java.util.Optional15class TestContainerExtension<T : GenericContainer<out T>>(16 private val container: GenericContainer<out T>,17 private val lifecycleMode: LifecycleMode = LifecycleMode.Spec,18) : MountableExtension<T, T>, TestListener, AfterSpecListener {...
TestListener.kt
Source:TestListener.kt
1package fixutre23import io.kotest.core.config.AbstractProjectConfig4import io.kotest.core.listeners.*5import io.kotest.core.listeners.ProjectListener6import io.kotest.core.spec.AutoScan7import io.kotest.core.spec.Spec8import io.kotest.core.spec.style.FunSpec9import io.kotest.core.test.TestCase10import io.kotest.core.test.TestResult11import io.kotest.matchers.shouldBe12import kotlin.reflect.KClass1314object SpecLevelListener : TestListener {15 override val name:String = "SpecLevelListener"1617 override suspend fun prepareSpec(kclass: KClass<out Spec>) {18 println("PrepareSpec(in SpecLevelListener): ${kclass.qualifiedName}")19 }2021 override suspend fun beforeSpec(spec: Spec) {22 println("BeforeSpec: ${spec.materializeRootTests().joinToString { it.testCase.displayName }}")23 }2425 override suspend fun beforeTest(testCase: TestCase) {26 println("BeforeTest: ${testCase.displayName}")27 }2829 override suspend fun afterTest(testCase: TestCase, result: TestResult) {30 println("AfterTest: ${testCase.displayName}")31 }3233 override suspend fun afterSpec(spec: Spec) {34 println("AfterSpec: ${spec.materializeRootTests().joinToString { it.testCase.displayName }}")35 }3637 override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {38 println("FinalizeSpec(in SpecLevelListener): ${kclass.qualifiedName}")39 }40}4142class NumbersTestWithFixture1 : FunSpec() {43 init {44 context("Addition") {45 test("2 + 2") {46 2 + 2 shouldBe 447 }48 test("4 * 4") {49 4 + 4 shouldBe 850 }51 }52 }5354 override fun listeners() = listOf(SpecLevelListener)55}5657class NumbersTestWithFixture2 : FunSpec() {58 init {59 context("Multiplication") {60 test("2 * 2") {61 2 * 2 shouldBe 462 }63 test("4 * 4") {64 4 * 4 shouldBe 1665 }66 }67 }6869 override fun listeners() = listOf(SpecLevelListener)70}7172object MyProjectListener : ProjectListener, TestListener {73 override val name: String = "MyProjectListener"7475 override suspend fun beforeProject() { println("Before project") }7677 override suspend fun afterProject() { println("After project") }7879 override suspend fun prepareSpec(kclass: KClass<out Spec>) {80 println("PrepareSpec: ${kclass.qualifiedName}")81 }8283 override suspend fun finalizeSpec(kclass: KClass<out Spec>, results: Map<TestCase, TestResult>) {84 println("FinalizeSpec: ${kclass.qualifiedName}")85 }86}8788object ProjectConfig: AbstractProjectConfig() {89 override fun listeners() = listOf(MyProjectListener)
...
BFunSpec.kt
Source:BFunSpec.kt
1package com.painkillergis.ktor_starter2import io.kotest.core.listeners.ProjectListener3import io.kotest.core.spec.AutoScan4import io.kotest.core.spec.style.FunSpec5import io.kotest.core.test.TestCase6import io.ktor.client.*7import io.ktor.client.features.*8import io.ktor.client.features.json.*9import io.ktor.client.request.*10import io.ktor.client.statement.*11import io.ktor.http.*12import io.ktor.server.engine.*13import io.ktor.server.netty.*14import kotlinx.coroutines.delay15import kotlinx.coroutines.withTimeout16import com.cruftbusters.ktor_baseurl_util.setBaseUrl17abstract class BFunSpec(val body: FunSpec.(HttpClient) -> Unit) : FunSpec({18 register(ServerStart)19 body(this, httpClient)20}) {21 companion object {22 private const val embeddedServerBaseUrl = "http://localhost:8080"23 private val baseUrl = System.getProperty("baseUrl").ifBlank { embeddedServerBaseUrl }24 private var started = false25 private val server = embeddedServer(Netty, port = 8080) { module() }26 val httpClient = HttpClient {27 defaultRequest {28 setBaseUrl(baseUrl)29 }30 install(JsonFeature)31 }32 object ServerStart : io.kotest.core.listeners.TestListener {33 override suspend fun beforeTest(testCase: TestCase) {34 if (started || baseUrl != embeddedServerBaseUrl) return35 server.start()36 started = true37 withTimeout(4000) {38 while (!isRunning()) {39 delay(250)40 }41 }42 }43 private suspend fun isRunning() =44 try {45 httpClient.get<HttpResponse>("/version").status == HttpStatusCode.OK46 } catch (exception: Exception) {...
VaultTestListener.kt
Source:VaultTestListener.kt
1package com.freighttrust.testing.listeners2import io.kotest.core.listeners.TestListener3import io.kotest.core.spec.Spec4import io.kotest.matchers.shouldBe5import kotlinx.coroutines.Dispatchers6import kotlinx.coroutines.withContext7import org.testcontainers.containers.BindMode8import org.testcontainers.containers.wait.strategy.Wait9import org.testcontainers.vault.VaultContainer10import java.nio.charset.Charset11class VaultTestListener : TestListener {12 private val container = VaultContainer<Nothing>("vault:1.4.3")13 .apply {14 withVaultToken("root")15 withClasspathResourceMapping(16 "/kotest/listeners/vault/init.sh",17 "/opt/init.sh",18 BindMode.READ_ONLY19 )20 }21 @Suppress("BlockingMethodInNonBlockingContext")22 override suspend fun beforeSpec(spec: Spec) {23 with(container) {24 start()25 // wait for vault to start26 waitingFor(Wait.forHealthcheck())27 // execute init script28 val result = withContext(Dispatchers.IO) {29 execInContainer(Charset.defaultCharset(), "sh", "/opt/init.sh")30 }...
KotestConfig.kt
Source:KotestConfig.kt
...5class KotestConfig: AbstractProjectConfig() {6 // Modificamos esta configuración para que se creen nuevos objetos para cada `it`.7 override val isolationMode = IsolationMode.InstancePerLeaf8 // Reporta el resultado de los tests como XML, lo cual usamos para que se muestren en el pull request cuando fallan.9 override fun listeners() = listOf(JunitXmlReporter())10}...
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!!