Best Kotest code snippet using io.kotest.core.TestConfiguration
TransferGeneratorTest.kt
Source:TransferGeneratorTest.kt
...12import org.iban4j.IbanUtil13import org.springframework.beans.factory.annotation.Autowired14import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer15import org.springframework.boot.test.context.SpringBootTest16import org.springframework.boot.test.context.TestConfiguration17import org.springframework.test.context.ActiveProfiles18import org.springframework.test.context.ContextConfiguration19import java.util.concurrent.ThreadLocalRandom20class ProjectConfig : AbstractProjectConfig() {21 override fun extensions(): List<Extension> = listOf(SpringAutowireConstructorExtension)22}23fun hasProperLetter() = object : Matcher<String> {24 private val NIF_CHARACTERS = "TRWAGMYFPDXBNJZSQVHLCKE"25 fun isAValidNIF(nif: String): Boolean {26 val number = nif.substring(0, nif.length - 1).toLongOrNull()27 return when {28 number == null -> false29 nif.length != 9 -> false30 else -> nif[nif.length - 1] == NIF_CHARACTERS[(number % 23).toInt()]31 }32 }33 override fun test(value: String) =34 MatcherResult(35 isAValidNIF(value),36 "String $value should has proper letter",37 "String $value should not has a proper letter"38 )39}40@SpringBootTest41@ActiveProfiles("test")42@ContextConfiguration(43 initializers = [ConfigFileApplicationContextInitializer::class],44 classes = [TestConfiguration::class, TransferConfiguration::class, NIFGenerator::class]45)46class NIFCustomerGeneratorTest(private val generator: NIFGenerator, private val configuration: TransferConfiguration) :47 FunSpec() {48 override fun listeners(): List<TestListener> {49 return listOf(SpringListener)50 }51 init {52 test("Well formatted NIF should have 8 digits and one character").config(invocations = 10) {53 val randomPosition = ThreadLocalRandom.current().nextInt(0, configuration.people)54 generator.generateWell(randomPosition) shouldMatch "([a-z]|[A-Z]|[0-9])[0-9]{7}([a-z]|[A-Z]|[0-9])"55 }56 test("Well formatted NIF should have the proper last character").config(invocations = 10) {57 val randomPosition = ThreadLocalRandom.current().nextInt(0, configuration.people)58 generator.generateWell(randomPosition) should hasProperLetter()59 }60 test("Wrong formatted NIF should have 8 digits and one character").config(invocations = 10) {61 generator.generateWrong() shouldMatch "([a-z]|[A-Z]|[0-9])[0-9]{7}([a-z]|[A-Z]|[0-9])"62 }63 test("Wrong formatted NIF should not have the proper last character").config(invocations = 10) {64 generator.generateWrong() shouldNot hasProperLetter()65 }66 }67}68fun isAProperIban() = object : Matcher<String> {69 fun isValid(value: String): Boolean {70 return try {71 IbanUtil.validate(value)72 true73 } catch (ex: Exception) {74 false75 }76 }77 override fun test(value: String) =78 MatcherResult(79 isValid(value),80 "String $value should be proper iban",81 "String $value should not be proper iban"82 )83}84@SpringBootTest85@ActiveProfiles("test")86@ContextConfiguration(87 initializers = [ConfigFileApplicationContextInitializer::class],88 classes = [TestConfiguration::class, TransferConfiguration::class, IbanGenerator::class]89)90class IbanCustomerGeneratorTest(91 private val configuration: TransferConfiguration, private val generator: IbanGenerator92) : FunSpec() {93 override fun listeners(): List<TestListener> {94 return listOf(SpringListener)95 }96 init {97 test("Well formatted IBAN").config(invocations = 50) {98 val randomPosition = ThreadLocalRandom.current().nextInt(0, configuration.people)99 generator.generateWell(randomPosition) should isAProperIban()100 }101 test("Wrong formatted IBAN").config(invocations = 50) {102 generator.generateWrong() shouldNot isAProperIban()103 }104 }105}106fun isAValidCurrencyName(configuration: TransferConfiguration) = object : Matcher<String> {107 private val validCurrencies = configuration.currencies108 override fun test(value: String) =109 MatcherResult(110 validCurrencies.contains(value),111 "String $value is not a valid currency",112 "String $value should not be a valid currency"113 )114}115fun isAInvalidCurrencyName() = object : Matcher<String> {116 private val badCurrencyNames = arrayOf("SDU", "RUE", "GB", "CFH", "BUR", "KK", "KES")117 override fun test(value: String) =118 MatcherResult(119 badCurrencyNames.contains(value),120 "String $value is a valid currency",121 "String $value should be a valid currency"122 )123}124@SpringBootTest125@ActiveProfiles("test")126@ContextConfiguration(127 initializers = [ConfigFileApplicationContextInitializer::class],128 classes = [TestConfiguration::class, ConfigFileApplicationContextInitializer::class, CurrencyNameCustomGenerator::class, TransferConfiguration::class]129)130class CurrencyNameCustomerGeneratorTest(131 private val configuration: TransferConfiguration,132 private val generator: CurrencyNameCustomGenerator133) : FunSpec() {134 override fun listeners(): List<TestListener> {135 return listOf(SpringListener)136 }137 init {138 test("Valid currencies") {139 generator.checkCurrencies()140 }141 test("Valid currency").config(invocations = 50) {142 generator.generateWell() should isAValidCurrencyName(configuration)143 }144 test("Wrong valid currency").config(invocations = 50) {145 generator.generateWrong() should isAInvalidCurrencyName()146 }147 }148}149@SpringBootTest150@ActiveProfiles("test")151@ContextConfiguration(152 initializers = [ConfigFileApplicationContextInitializer::class],153 classes = [TestConfiguration::class, ConfigFileApplicationContextInitializer::class, CurrencyAmountCustomGenerator::class, TransferConfiguration::class]154)155class CurrencyAmountCustomerGeneratorTest(156 private val configuration: TransferConfiguration,157 private val generator: CurrencyAmountCustomGenerator158) : FunSpec() {159 override fun listeners(): List<TestListener> {160 return listOf(SpringListener)161 }162 init {163 test("Valid currency").config(invocations = 1000) {164 generator.generateWell().toDouble() shouldBeLessThan configuration.maxAmount165 }166 test("Wrong valid currency") {167 generator.generateWrong() shouldBe "N/A"168 }169 }170}171@SpringBootTest172@ActiveProfiles("test")173@ContextConfiguration(174 initializers = [ConfigFileApplicationContextInitializer::class],175 classes = [TestConfiguration::class,176 ConfigFileApplicationContextInitializer::class,177 TransferConfiguration::class,178 IbanGenerator::class,179 NIFGenerator::class,180 PersonFieldCustomGenerator::class]181)182class PersonFieldCustomerGeneratorTest(private val generator: PersonFieldCustomGenerator) : FunSpec() {183 override fun listeners(): List<TestListener> {184 return listOf(SpringListener)185 }186 init {187 test("Valid Person Field").config(invocations = 50) {188 val badGeneratedPersonField = generator.generateWell()189 val splitPersonField = badGeneratedPersonField.split("\t");190 splitPersonField.size shouldBe 2191 splitPersonField[0] should isAProperIban()192 splitPersonField[1] should hasProperLetter()193 }194 test("Wrong Person Field").config(invocations = 50) {195 val badGeneratedPersonField = generator.generateWrong()196 val splitPersonField = badGeneratedPersonField.split("\t");197 splitPersonField.size shouldBe 2198 splitPersonField[0] shouldNot isAProperIban()199 splitPersonField[1] shouldNot hasProperLetter()200 }201 }202}203fun isAValidTransfer() = object : Matcher<String> {204 private fun isValidTransfer(value: String): Boolean {205 return value == TransferGenerator.MALFORMED_LINE ||206 value.isBlank() ||207 value.split("\t").size >= 2208 }209 override fun test(value: String) =210 MatcherResult(211 isValidTransfer(value),212 "String \"$value\" is not a valid transfer line",213 "String \"$value\" should not be a valid transfer line"214 )215}216@SpringBootTest217@ActiveProfiles("test")218@ContextConfiguration(219 initializers = [ConfigFileApplicationContextInitializer::class],220 classes = [TestConfiguration::class,221 ConfigFileApplicationContextInitializer::class,222 TransferConfiguration::class,223 IbanGenerator::class,224 NIFGenerator::class,225 PersonFieldCustomGenerator::class,226 CurrencyNameCustomGenerator::class,227 CurrencyAmountCustomGenerator::class,228 TransferGenerator::class]229)230class TransferGeneratorTest(private val generator: TransferGenerator) : FunSpec() {231 override fun listeners(): List<TestListener> {232 return listOf(SpringListener)233 }234 init {...
resource.kt
Source:resource.kt
...12import arrow.fx.coroutines.Resource13import arrow.fx.coroutines.bracketCase14import io.kotest.assertions.fail15import io.kotest.common.runBlocking16import io.kotest.core.TestConfiguration17import io.kotest.core.listeners.TestListener18import io.kotest.core.spec.Spec19fun <A> TestConfiguration.resource(resource: Resource<A>): A = runBlocking {20 TestResource(resource).also(this::listener).value()21}22private class TestResource<A>(private val resource: Resource<A>) : TestListener {23 private val finalizers: AtomicRef<List<suspend (ExitCase) -> Unit>> = AtomicRef(emptyList())24 suspend fun value(): A = resource.bind()25 // Remove once resource computation block is available26 private suspend fun <B> Resource<B>.bind(): B =27 when (this) {28 is Resource.Bind<*, *> -> {29 val any = source.bind()30 @Suppress("UNCHECKED_CAST") val ff = f as ((Any?) -> Resource<B>)31 ff(any).bind()32 }33 is Resource.Allocate ->...
FileGeneratorTest.kt
Source:FileGeneratorTest.kt
...7import io.kotest.matchers.should8import io.kotest.spring.SpringListener9import org.springframework.boot.test.context.ConfigFileApplicationContextInitializer10import org.springframework.boot.test.context.SpringBootTest11import org.springframework.boot.test.context.TestConfiguration12import org.springframework.test.context.ActiveProfiles13import org.springframework.test.context.ContextConfiguration14import java.io.File15fun checkFile(fileConfiguration: FileConfiguration) = object : Matcher<String> {16 private fun checkFile(value: String): Boolean {17 var lines: Long = 018 val file = File(value)19 if (!file.exists())20 return false21 file.forEachLine { ++lines }22 return lines < fileConfiguration.transferAmountLines23 }24 override fun test(value: String) =25 MatcherResult(26 checkFile(value),27 "String $value is not a valid transfer line",28 "String $value should not be a valid transfer line"29 )30}31@SpringBootTest32@ActiveProfiles("test")33@ContextConfiguration(34 initializers = [ConfigFileApplicationContextInitializer::class],35 classes = [TestConfiguration::class,36 ConfigFileApplicationContextInitializer::class,37 TransferConfiguration::class,38 IbanGenerator::class,39 NIFGenerator::class,40 PersonFieldCustomGenerator::class,41 CurrencyNameCustomGenerator::class,42 CurrencyAmountCustomGenerator::class,43 TransferGenerator::class]44)45class FileGeneratorTest(private val transferGenerator: TransferGenerator): FunSpec() {46 override fun listeners(): List<TestListener> {47 return listOf(SpringListener)48 }49 private val fileConfiguration = FileConfiguration()...
setup.kt
Source:setup.kt
1package com.tylerkindy.betrayal.db2import io.kotest.core.TestConfiguration3import io.kotest.core.listeners.ProjectListener4import io.kotest.core.spec.AutoScan5import org.jetbrains.exposed.sql.Database6import org.jetbrains.exposed.sql.Schema7import org.jetbrains.exposed.sql.SchemaUtils8import org.jetbrains.exposed.sql.transactions.TransactionManager9import org.jetbrains.exposed.sql.transactions.transaction10import org.jetbrains.exposed.sql.vendors.PostgreSQLDialect11import java.io.File12@AutoScan13object SetupDatabaseProjectListener : ProjectListener {14 override suspend fun beforeProject() {15 Database.registerJdbcDriver(16 "jdbc:tc:postgresql",17 "org.postgresql.Driver",18 PostgreSQLDialect.dialectName19 )20 Database.connect(21 "jdbc:tc:postgresql:12:///betrayal-test?TC_DAEMON=true"22 )23 }24}25val migrationsSql: List<String> = File(26 SetupDatabaseProjectListener.javaClass.getResource(27 "/migrations.sql"28 )!!.toURI()29).readText().split("\n\n")30fun TestConfiguration.useDatabase() {31 beforeEach {32 transaction {33 SchemaUtils.createSchema(Schema("public"))34 migrationsSql.forEach { TransactionManager.current().exec(it) }35 }36 }37 afterEach {38 transaction {39 SchemaUtils.dropSchema(Schema("public"), cascade = true)40 }41 }42}...
util.kt
Source:util.kt
1package io.github.hWorblehat.gradlecumber.testutil2import io.kotest.core.TestConfiguration3import org.apache.commons.io.file.PathUtils4import org.gradle.api.Project5import org.gradle.testfixtures.ProjectBuilder6import java.io.File7import java.io.IOException8import java.nio.file.Files9import java.nio.file.Path10val ANSI_SEQUENCE_REGEX = Regex("(?:\\x1B\\x5B|\\x9B)[\\x30-\\x3f]*[\\x20-\\x2F]*[\\x30-\\x7E]")11fun String.removeANSISequences(): String = replace(ANSI_SEQUENCE_REGEX, "")12fun String.escapeWindowsFileSeparators() = replace("\\", "\\\\")13fun TestConfiguration.cleanupAfter(dir: Path): Path {14 afterSpec {15 try {16 PathUtils.delete(dir)17 } catch(e: IOException) {/* ignore */}18 }19 return dir20}21fun TestConfiguration.tempdir(prefix: String? = null): File = cleanupAfter(Files.createTempDirectory(prefix)).toFile()22fun TestConfiguration.cleanupAfter(project: Project): Project {23 cleanupAfter(project.projectDir.toPath())24 return project25}26fun TestConfiguration.testProject(): Project = cleanupAfter(ProjectBuilder.builder().build())...
DslDockerTutorialPageTest.kt
Source:DslDockerTutorialPageTest.kt
2import io.kotest.core.spec.style.StringSpec3import io.kotest.matchers.nulls.shouldNotBeNull4import io.kotest.matchers.shouldBe5import io.kotest.matchers.string.shouldContain6import org.brewcode.qa.pages.cfg.TestConfiguration7import org.brewcode.qa.pages.page.modal.ModalDockerTutorialPage8open class DslDockerTutorialPageTest : StringSpec() {9 private val pages = TestConfiguration.pages10 init {11 "Scenario: base page dsl" {12 var throwError = true13 pages.page<ModalDockerTutorialPage>()14 .open()15 .verify()16 .whenDoWithRetry({ throwError = false }) {17 if (throwError) throw IllegalStateException("Should be ignored")18 link.click()19 }.thenOpen<CommandDockerTutorialPage> {20 body.shouldNotBeNull()21 }.thenOpen(CommandDockerTutorialPage::class) {22 title() shouldContain "Getting Started"23 }...
Extensions.kt
Source:Extensions.kt
1package io.kotest.extensions.testcontainers2import io.kotest.core.TestConfiguration3import org.testcontainers.lifecycle.Startable4fun <T : Startable> T.perTest(): StartablePerTestListener<T> = StartablePerTestListener<T>(this)5fun <T : Startable> T.perSpec(): StartablePerSpecListener<T> = StartablePerSpecListener<T>(this)6fun <T : Startable> T.perProject(containerName: String): StartablePerProjectListener<T> = StartablePerProjectListener<T>(this, containerName)7fun <T : Startable> TestConfiguration.configurePerTest(startable: T): T {8 listener(StartablePerTestListener(startable))9 return startable10}11fun <T : Startable> TestConfiguration.configurePerSpec(startable: T): T {12 listener(StartablePerSpecListener(startable))13 return startable14}15fun <T : Startable> TestConfiguration.configurePerProject(startable: T, containerName: String): T {16 listener(StartablePerProjectListener(startable, containerName))17 return startable18}...
TestFilesUtil.kt
Source:TestFilesUtil.kt
1package konnekt.gradle2import io.kotest.core.TestConfiguration3import io.kotest.core.test.TestStatus4import java.io.File5import java.nio.file.Files6fun TestConfiguration.tempdir(prefix: String? = null, suffix: String? = ".tmp"): File {7 val file = Files.createTempDirectory(prefix).toFile()8 afterTest { (_, result) ->9 if (result.status == TestStatus.Success) {10 file.walkBottomUp().filter { it != file }.fold(true) { res, it -> (it.delete() || !it.exists()) && res }11 }12 }13 afterSpec {14 file.deleteRecursively()15 }16 return file17}18val TestConfiguration.newFile: File.(String) -> File19 get() = {20 val file = File(this, it)21 beforeTest {22 file.createNewFile()23 }24 file25}...
TestConfiguration
Using AI Code Generation
1import io.kotest.core.spec.style.FunSpec2class TestConfigurationTest : FunSpec({3testConfiguration(4println("After test")5}6test("test1") {7println("Test 1")8}9test("test2") {10println("Test 2")11}12})13In the above example, we are using testConfiguration() function to apply test configuration to all tests in the spec. The test configuration will be applied to each test in the spec. The test configuration is applied to each test in the spec and not to the spec itself. We can specify the following parameters in the test configuration:14import io.kotest.core.spec.style.FunSpec15class TestConfigurationTest : FunSpec({16testConfiguration(17println("After test")18}19context("test context") {20testConfiguration(21println("After test in test context")22}23test("test1") {24println("Test 1")25}26test("test2") {27println("Test 2")28}29}30})31In the above example, we are using testConfiguration() function to apply test configuration to all tests in the
TestConfiguration
Using AI Code Generation
1val config = TestConfiguration (2testCase = TestCase ( name = "test" , spec = this , test = { } ) ,3project = Project ( name = "Kotest" ) ,4sharedTest = { } ,5tags = emptySet ( ) ,6afters = emptyList ( ) ,7befores = emptyList ( ) ,8defaultTestCaseConfig = TestCaseConfig ( )
TestConfiguration
Using AI Code Generation
1val config = TestConfiguration (2timeout = Duration . ofSeconds ( 10 )3testConfiguration ( config )4test ( "Test case with timeout" ) {5Thread . sleep ( 10000 )6}7}
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!!