Best Kotest code snippet using io.kotest.core.names.TestName
UnitSpec.kt
Source:UnitSpec.kt
...3import arrow.core.Tuple44import arrow.core.Tuple55import arrow.core.test.generators.unit6import arrow.core.test.laws.Law7import io.kotest.core.names.TestName8import io.kotest.core.spec.style.StringSpec9import io.kotest.property.Arb10import io.kotest.property.Gen11import io.kotest.property.PropertyContext12import io.kotest.property.arbitrary.bind13import io.kotest.property.arbitrary.filter14import io.kotest.property.arbitrary.map15import io.kotest.property.arbitrary.list as KList16import io.kotest.property.arbitrary.map as KMap17import io.kotest.property.checkAll18import kotlin.jvm.JvmOverloads19import kotlin.math.max20/**21 * Base class for unit tests22 */23public abstract class UnitSpec(24 public val iterations: Int = 250,25 public val maxDepth: Int = 15,26 spec: UnitSpec.() -> Unit = {}27) : StringSpec() {28 public constructor(spec: UnitSpec.() -> Unit) : this(250, 15, spec)29 public fun <A> Arb.Companion.list(gen: Gen<A>, range: IntRange = 0..maxDepth): Arb<List<A>> =30 Arb.KList(gen, range)31 public fun <A> Arb.Companion.nonEmptyList(arb: Arb<A>, depth: Int = maxDepth): Arb<NonEmptyList<A>> =32 Arb.list(arb, 1..max(1, depth)).filter(List<A>::isNotEmpty).map(NonEmptyList.Companion::fromListUnsafe)33 public fun <A> Arb.Companion.sequence(arbA: Arb<A>, range: IntRange = 0..maxDepth): Arb<Sequence<A>> =34 Arb.list(arbA, range).map { it.asSequence() }35 @JvmOverloads36 public inline fun <reified A> Arb.Companion.array(gen: Arb<A>, range: IntRange = 0..maxDepth): Arb<Array<A>> =37 Arb.list(gen, range).map { it.toTypedArray() }38 public fun <K, V> Arb.Companion.map(39 keyArb: Arb<K>,40 valueArb: Arb<V>,41 minSize: Int = 1,42 maxSize: Int = 1543 ): Arb<Map<K, V>> =44 Arb.KMap(keyArb, valueArb, minSize = minSize, maxSize = maxSize)45 init {46 spec()47 }48 public fun testLaws(vararg laws: List<Law>): Unit = laws49 .flatMap { list: List<Law> -> list.asIterable() }50 .distinctBy { law: Law -> law.name }51 .forEach { law: Law ->52 registration().addTest(TestName(law.name), xdisabled = false, law.test)53 }54 public fun testLaws(prefix: String, vararg laws: List<Law>): Unit = laws55 .flatMap { list: List<Law> -> list.asIterable() }56 .distinctBy { law: Law -> law.name }57 .forEach { law: Law ->58 registration().addTest(TestName(prefix, law.name, true), xdisabled = false, law.test)59 }60 public suspend fun checkAll(property: suspend PropertyContext.() -> Unit): PropertyContext =61 checkAll(iterations, Arb.unit()) { property() }62 public suspend fun <A> checkAll(63 genA: Arb<A>,64 property: suspend PropertyContext.(A) -> Unit65 ): PropertyContext =66 checkAll(67 iterations,68 genA,69 property70 )71 public suspend fun <A, B> checkAll(72 genA: Arb<A>,...
DefaultDisplayNameFormatterTest.kt
Source:DefaultDisplayNameFormatterTest.kt
...3import io.kotest.core.Tag4import io.kotest.core.config.ProjectConfiguration5import io.kotest.core.descriptors.append6import io.kotest.core.descriptors.toDescriptor7import io.kotest.core.names.TestName8import io.kotest.core.source.sourceRef9import io.kotest.core.spec.DisplayName10import io.kotest.core.annotation.Isolate11import io.kotest.core.spec.style.FunSpec12import io.kotest.core.test.TestCase13import io.kotest.core.test.TestType14import io.kotest.core.test.config.ResolvedTestConfig15import io.kotest.engine.test.names.DefaultDisplayNameFormatter16import io.kotest.matchers.shouldBe17@Isolate18class DefaultDisplayNameFormatterTest : FunSpec() {19 init {20 test("@DisplayName should be used for spec name") {21 DefaultDisplayNameFormatter(ProjectConfiguration()).format(SpecWithDisplayName::class) shouldBe "ZZZZZ"22 }23 test("test name should use full path option") {24 val conf = ProjectConfiguration()25 conf.displayFullTestPath = true26 val tc1 = TestCase(27 SpecWithDisplayName::class.toDescriptor().append("test"),28 TestName("test"),29 SpecWithDisplayName(),30 {},31 sourceRef(),32 TestType.Test,33 )34 val tc2 = TestCase(35 SpecWithDisplayName::class.toDescriptor().append("test2"),36 TestName("test2"),37 SpecWithDisplayName(),38 {},39 sourceRef(),40 TestType.Test,41 parent = tc142 )43 DefaultDisplayNameFormatter(conf).format(tc2) shouldBe "test test2"44 }45 test("tags should be appended from config when configuration is set") {46 val c = ProjectConfiguration()47 c.testNameAppendTags = true48 val tc = TestCase(49 SpecWithDisplayName::class.toDescriptor().append("test"),50 TestName("test"),51 SpecWithDisplayName(),52 {},53 sourceRef(),54 TestType.Test,55 ResolvedTestConfig.default.copy(tags = setOf(NamedTag("Foo"), Dummy))56 )57 DefaultDisplayNameFormatter(c).format(tc) shouldBe "test[tags = Foo, Dummy]"58 }59 test("bang should not be included in test name") {60 val tc = TestCase(61 descriptor = SpecWithDisplayName::class.toDescriptor().append("!test"),62 name = TestName("!test"),63 spec = SpecWithDisplayName(),64 test = {},65 source = sourceRef(),66 type = TestType.Test,67 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))68 )69 DefaultDisplayNameFormatter(ProjectConfiguration()).format(tc) shouldBe "test"70 }71 test("focus should not be included in test name") {72 val tc = TestCase(73 descriptor = SpecWithDisplayName::class.toDescriptor().append("f:test"),74 name = TestName("f:test"),75 spec = SpecWithDisplayName(),76 test = {},77 source = sourceRef(),78 type = TestType.Test,79 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))80 )81 DefaultDisplayNameFormatter(ProjectConfiguration()).format(tc) shouldBe "test"82 }83 test("name should include prefix if affixes are included by default") {84 val tc = TestCase(85 descriptor = SpecWithDisplayName::class.toDescriptor().append("f:test"),86 name = TestName("prefix", "foo", null, true),87 spec = SpecWithDisplayName(),88 test = {},89 source = sourceRef(),90 type = TestType.Test,91 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))92 )93 DefaultDisplayNameFormatter(ProjectConfiguration()).format(tc) shouldBe "prefixfoo"94 }95 test("name should include prefix if affixes are excluded by default but enabled by config") {96 val tc = TestCase(97 descriptor = SpecWithDisplayName::class.toDescriptor().append("f:test"),98 name = TestName("prefix", "foo", null, false),99 spec = SpecWithDisplayName(),100 test = {},101 source = sourceRef(),102 type = TestType.Test,103 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))104 )105 val c = ProjectConfiguration()106 c.includeTestScopeAffixes = true107 DefaultDisplayNameFormatter(c).format(tc) shouldBe "prefixfoo"108 }109 test("name should include suffix if affixes are included by default") {110 val tc = TestCase(111 descriptor = SpecWithDisplayName::class.toDescriptor().append("f:test"),112 name = TestName(null, "foo", "suffix", true),113 spec = SpecWithDisplayName(),114 test = {},115 source = sourceRef(),116 type = TestType.Test,117 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))118 )119 DefaultDisplayNameFormatter(ProjectConfiguration()).format(tc) shouldBe "foosuffix"120 }121 test("name should include suffix if affixes are excluded by default but enabled in config") {122 val tc = TestCase(123 descriptor = SpecWithDisplayName::class.toDescriptor().append("f:test"),124 name = TestName(null, "foo", "suffix", false),125 spec = SpecWithDisplayName(),126 test = {},127 source = sourceRef(),128 type = TestType.Test,129 config = ResolvedTestConfig.default.copy(tags = setOf(Dummy, NoUse))130 )131 val c = ProjectConfiguration()132 c.includeTestScopeAffixes = true133 DefaultDisplayNameFormatter(c).format(tc) shouldBe "foosuffix"134 }135 }136}137object Dummy : Tag()138object NoUse : Tag()...
DefaultDisplayNameFormatter.kt
Source:DefaultDisplayNameFormatter.kt
...5import io.kotest.core.config.ExtensionRegistry6import io.kotest.core.config.ProjectConfiguration7import io.kotest.core.extensions.DisplayNameFormatterExtension8import io.kotest.core.names.DisplayNameFormatter9import io.kotest.core.names.TestNameCase10import io.kotest.core.spec.DisplayName11import io.kotest.core.test.TestCase12import io.kotest.mpp.annotation13import io.kotest.mpp.bestName14import kotlin.reflect.KClass15fun getDisplayNameFormatter(registry: ExtensionRegistry, configuration: ProjectConfiguration): DisplayNameFormatter {16 return registry.all()17 .filterIsInstance<DisplayNameFormatterExtension>()18 .firstOrNull()19 ?.formatter() ?: DefaultDisplayNameFormatter(configuration)20}21/**22 * A default implementation of [DisplayNameFormatter].23 * Used when there are no registered [io.kotest.core.extensions.DisplayNameFormatterExtension]s.24 */25class DefaultDisplayNameFormatter(26 private val configuration: ProjectConfiguration,27) : DisplayNameFormatter {28 constructor() : this(ProjectConfiguration())29 override fun format(testCase: TestCase): String {30 val prefix = when (configuration.includeTestScopeAffixes ?: testCase.name.defaultAffixes) {31 true -> testCase.name.prefix ?: ""32 false -> ""33 }34 val suffix = when (configuration.includeTestScopeAffixes ?: testCase.name.defaultAffixes) {35 true -> testCase.name.suffix ?: ""36 false -> ""37 }38 val displayName = if (prefix.isBlank()) {39 when (configuration.testNameCase) {40 TestNameCase.Sentence -> testCase.name.testName.capital() + suffix41 TestNameCase.InitialLowercase -> testCase.name.testName.uncapitalize() + suffix42 TestNameCase.Lowercase -> testCase.name.testName.lowercase() + suffix43 else -> testCase.name.testName + suffix44 }45 } else {46 when (configuration.testNameCase) {47 TestNameCase.Sentence -> "${prefix.capital()}${testCase.name.testName.uncapitalize()}$suffix"48 TestNameCase.InitialLowercase -> "${prefix.uncapitalize()}${testCase.name.testName.uncapitalize()}$suffix"49 TestNameCase.Lowercase -> "${prefix.lowercase()}${testCase.name.testName.lowercase()}$suffix"50 else -> "$prefix${testCase.name.testName}$suffix"51 }52 }53 val name = if (configuration.testNameAppendTags) {54 return appendTagsInDisplayName(testCase, displayName)55 } else {56 displayName57 }58 return when (val parent = testCase.parent) {59 null -> name60 else -> if (configuration.displayFullTestPath) format(parent) + " " + name else name61 }62 }63 /**...
ThingTestCases.kt
Source:ThingTestCases.kt
...13package mjs.kotest.fixtures14import io.kotest.assertions.AssertionFailedError15import io.kotest.core.descriptors.Descriptor16import io.kotest.core.descriptors.DescriptorId17import io.kotest.core.names.TestName18import io.kotest.core.source.SourceRef19import io.kotest.core.test.TestCase20import io.kotest.core.test.TestResult21import io.kotest.core.test.TestType22import kotlin.time.Duration23val specDescriptor = Descriptor.SpecDescriptor(DescriptorId(ThingTest::class.qualifiedName!!), ThingTest::class)24val thingTest = ThingTest()25const val name0 = "0. Describe the thing"26val descriptor0 = Descriptor.TestDescriptor(specDescriptor, DescriptorId(name0))27val case0 = TestCase(28 descriptor0, TestName(name0), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 8),29 TestType.Container, parent = null30)31val result0 = TestResult.Success(Duration.parse("81.112632ms"))32const val name1 = "1. I donât care"33val descriptor1 = Descriptor.TestDescriptor(descriptor0, DescriptorId(name1))34val case1 = TestCase(35 descriptor1, TestName(name1), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 9),36 TestType.Test, parent = case037)38val result1 = TestResult.Ignored("Disabled by xmethod")39const val name2 = "2. the inner thing"40val descriptor2 = Descriptor.TestDescriptor(descriptor0, DescriptorId(name2))41val case2 = TestCase(42 descriptor2, TestName(name2), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 12),43 TestType.Container, parent = case044)45val result2 = TestResult.Success(Duration.parse("34.051853ms"))46const val name2a = "2a. is thing"47val descriptor2a = Descriptor.TestDescriptor(descriptor2, DescriptorId(name2a))48val case2a = TestCase(49 descriptor2a, TestName(name2a), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 13),50 TestType.Test, parent = case251)52val result2a = TestResult.Success(Duration.parse("5.236817ms"))53const val name2b = "2b. is not thang"54val descriptor2b = Descriptor.TestDescriptor(descriptor2, DescriptorId(name2b))55val case2b = TestCase(56 descriptor2b, TestName(name2b), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 16),57 TestType.Test, parent = case258)59val result2b = TestResult.Failure(60 Duration.parse("17.143399ms"),61 AssertionFailedError("expected:<\"thang\"> but was:<\"thing\">", null, "thang", "thing"),62)63const val name3 = "3. also ignored"64val descriptor3 = Descriptor.TestDescriptor(descriptor0, DescriptorId(name3))65val case3 = TestCase(66 descriptor3, TestName(name3), thingTest, {}, SourceRef.FileSource("ThingTest.kt", 20),67 TestType.Container, parent = case068)69val result3 = TestResult.Ignored("Disabled by xmethod")70val resultsMap: Map<TestCase, TestResult> = mapOf(71 case0 to result0,72 case1 to result1,73 case2 to result2,74 case2a to result2a,75 case2b to result2b,76 case3 to result3,77)...
SpringExtensionTest.kt
Source:SpringExtensionTest.kt
1package io.kotest.extensions.spring2import io.kotest.core.descriptors.append3import io.kotest.core.descriptors.toDescriptor4import io.kotest.core.names.TestName5import io.kotest.core.source.sourceRef6import io.kotest.core.spec.style.WordSpec7import io.kotest.core.test.TestCase8import io.kotest.core.test.TestType9import io.kotest.matchers.nulls.shouldNotBeNull10import io.kotest.matchers.shouldBe11import org.springframework.beans.factory.annotation.Autowired12import org.springframework.test.context.ContextConfiguration13@ContextConfiguration(classes = [Components::class])14class SpringExtensionTest : WordSpec() {15 override fun extensions() = listOf(SpringExtension)16 @Autowired17 private lateinit var service: UserService18 init {19 "SpringExtension" should {20 "have autowired the service" {21 service.repository.findUser().name shouldBe "system_user"22 }23 "make test context available in the coroutine context"{24 testContextManager().shouldNotBeNull()25 }26 "generate applicable method name for a root test" {27 SpringExtension.methodName(28 TestCase(29 descriptor = SpringExtensionTest::class.toDescriptor()30 .append("0foo__!!55@#woo"),31 name = TestName("0foo__!!55@#woo"),32 spec = this@SpringExtensionTest,33 test = {},34 source = sourceRef(),35 type = TestType.Test36 )37 ) shouldBe "_0foo____55__woo"38 }39 "generate applicable method name for a nested test" {40 SpringExtension.methodName(41 TestCase(42 descriptor = SpringExtensionTest::class.toDescriptor()43 .append("0foo__!!55@#woo")44 .append("wibble%%wobble"),45 name = TestName("wibble%%wobble"),46 spec = this@SpringExtensionTest,47 test = {},48 source = sourceRef(),49 type = TestType.Test50 )51 ) shouldBe "_0foo____55__woo____wibble__wobble"52 }53 }54 }55}...
IOSpec.kt
Source:IOSpec.kt
1package com.github.rougsig.core2import io.kotest.core.datatest.forAll3import io.kotest.core.spec.style.FunSpec4import io.kotest.matchers.file.shouldBeADirectory5import io.kotest.matchers.file.shouldBeAFile6import io.kotest.matchers.file.shouldExist7import io.kotest.matchers.shouldBe8import kotlinx.coroutines.runBlocking9import java.io.ByteArrayInputStream10import java.io.ByteArrayOutputStream11import java.io.File12import java.io.PrintStream13import java.nio.file.Paths14abstract class IOSpec(15 private val resourcesPath: String,16 private val testFun: IOEnvironment.() -> Unit17) : FunSpec({18 val projectRoot = File(".").absoluteFile.parent19 val resourcesDir = Paths.get(projectRoot, "src/test/resources", resourcesPath).toFile()20 context("File IO tests") {21 val inputDir = File("${resourcesDir.absoluteFile}/input")22 inputDir.shouldExist()23 inputDir.shouldBeADirectory()24 val outputDir = File("${resourcesDir.absoluteFile}/output")25 outputDir.shouldExist()26 val testNames = inputDir.listFiles()27 .map { it.nameWithoutExtension.removePrefix("input") }28 forAll(testNames) { testName: String ->29 val input = File("${inputDir.absoluteFile}/input${testName}.txt")30 input.shouldExist()31 input.shouldBeAFile()32 val output = File("${outputDir.absoluteFile}/output${testName}.txt")33 output.shouldExist()34 output.shouldBeAFile()35 val baos = ByteArrayOutputStream()36 runBlocking {37 // Set the same as hackerrank timeout limit38 // https://www.hackerrank.com/environment/languages39 withTimeoutOrInterrupt(4000L) {40 IOEnvironment(ByteArrayInputStream(input.readBytes()), PrintStream(baos)).testFun()41 }42 }43 val actual = baos.toString().trim().trimIndent()44 val expected = output.readText().trim().trimIndent()45 actual.shouldBe(expected)46 }47 }48})...
DuplicateTestNameHandlerTest.kt
Source:DuplicateTestNameHandlerTest.kt
1package com.sksamuel.kotest.engine.test.names2import io.kotest.assertions.throwables.shouldThrow3import io.kotest.core.spec.style.FunSpec4import io.kotest.core.names.DuplicateTestNameMode5import io.kotest.core.names.TestName6import io.kotest.engine.test.names.DuplicateTestNameException7import io.kotest.engine.test.names.DuplicateTestNameHandler8import io.kotest.matchers.shouldBe9class DuplicateTestNameHandlerTest : FunSpec({10 test("in warn mode duplicate names should be renamed") {11 val handler = DuplicateTestNameHandler(DuplicateTestNameMode.Warn)12 handler.handle(TestName("foo")) shouldBe null13 handler.handle(TestName("foo")) shouldBe "(1) foo"14 handler.handle(TestName("foo")) shouldBe "(2) foo"15 }16 test("in silent mode duplicate names should be renamed") {17 val handler = DuplicateTestNameHandler(DuplicateTestNameMode.Silent)18 handler.handle(TestName("foo")) shouldBe null19 handler.handle(TestName("foo")) shouldBe "(1) foo"20 handler.handle(TestName("foo")) shouldBe "(2) foo"21 }22 test("in error mode duplicate names should throw DuplicateTestNameException") {23 val handler = DuplicateTestNameHandler(DuplicateTestNameMode.Error)24 handler.handle(TestName("foo")) shouldBe null25 shouldThrow<DuplicateTestNameException> {26 handler.handle(TestName("foo")) shouldBe "(1) foo"27 }28 }29})...
Law.kt
Source:Law.kt
1package io.kotest.property.arrow.laws2import io.kotest.assertions.fail3import io.kotest.core.names.TestName4import io.kotest.core.spec.style.scopes.RootScope5import io.kotest.core.spec.style.scopes.addTest6import io.kotest.core.test.TestScope7public data class Law(val name: String, val test: suspend TestScope.() -> Unit)8public fun <A> A.equalUnderTheLaw(other: A, f: (A, A) -> Boolean = { a, b -> a == b }): Boolean =9 if (f(this, other)) true else fail("Found $this but expected: $other")10public fun RootScope.testLaws(vararg laws: List<Law>): Unit =11 laws12 .flatMap { list: List<Law> -> list.asIterable() }13 .distinctBy { law: Law -> law.name }14 .forEach { law ->15 addTest(TestName(law.name), disabled = false, config = null) { law.test(this) }16 }17public fun RootScope.testLaws(prefix: String, vararg laws: List<Law>): Unit =18 laws19 .flatMap { list: List<Law> -> list.asIterable() }20 .distinctBy { law: Law -> law.name }21 .forEach { law: Law ->22 addTest(TestName(prefix, law.name, true), disabled = false, config = null) { law.test(this) }23 }...
TestName
Using AI Code Generation
1import io.kotest.core.names.TestName2import io.kotest.core.spec.style.FunSpec3import io.kotest.matchers.shouldBe4class TestNameTest : FunSpec({5 test("test name should have correct values") {6 val name = TestName("name", "a", "b", "c", "d", "e")7 }8})9import io.kotest.core.names.TestName10import io.kotest.core.spec.style.FunSpec11import io.kotest.matchers.shouldBe12class TestNameTest : FunSpec({13 test("test name should have correct values") {14 val name = TestName("name", "a", "b", "c", "d", "e")15 }16})17import io.kotest.core.names.TestName18import io.kotest.core.spec.style.FunSpec19import io.kotest.matchers.shouldBe20class TestNameTest : FunSpec({21 test("test name should have correct values") {22 val name = TestName("name", "a", "b", "c", "d", "e")23 }24})25import io.kotest.core.names.TestName26import io.kotest.core.spec.style.FunSpec27import io.kotest.matchers.shouldBe28class TestNameTest : FunSpec({29 test("test name should have correct values") {30 val name = TestName("name", "a", "b", "c", "d", "e")31 }32})33import io.kotest.core.names.TestName34import io.kotest.core.spec.style.FunSpec35import io.kotest.matchers.shouldBe36class TestNameTest : FunSpec({37 test("test name should have correct values")
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!!