Best Kotest code snippet using io.kotest.engine.test.names.DefaultDisplayNameFormatter.format
TeamCityTestEngineListener.kt
Source:TeamCityTestEngineListener.kt
...21class TeamCityTestEngineListener(22 private val prefix: String = TeamCityMessageBuilder.TeamCityPrefix,23 private val details: Boolean = true,24) : TestEngineListener {25 private var formatter: DisplayNameFormatter = DefaultDisplayNameFormatter(ProjectConfiguration())26 // once a spec has completed, we want to be able to check whether any given test is27 // a container or a leaf test, and so this map contains all test that have children28 private val children = mutableMapOf<Descriptor, MutableList<TestCase>>()29 private val results = mutableMapOf<Descriptor, TestResult>()30 private val started = mutableSetOf<Descriptor.TestDescriptor>()31 // intellij has no method for failed suites, so if a container or spec fails we must insert32 // a dummy "test" in order to tag the error against that33 private fun insertPlaceholder(t: Throwable, parent: Descriptor) {34 val (name, cause) = ExtensionExceptionExtractor.resolve(t)35 val msg1 = TeamCityMessageBuilder36 .testStarted(prefix, name)37 .id(name)38 .parent(parent.path().value)39 .build()40 println(msg1)41 // we must print out the stack trace in between the dummy, so it appears when you click on the test name42 //t?.printStackTrace()43 val msg2 = TeamCityMessageBuilder44 .testFailed(prefix, name)45 .id(name)46 .parent(parent.path().value)47 .withException(cause, details)48 .build()49 println(msg2)50 val msg3 = TeamCityMessageBuilder51 .testFinished(prefix, name)52 .id(name)53 .parent(parent.path().value)54 .build()55 println(msg3)56 }57 override suspend fun engineStarted() {}58 override suspend fun engineInitialized(context: EngineContext) {59 formatter = getDisplayNameFormatter(context.configuration.registry, context.configuration)60 }61 override suspend fun engineFinished(t: List<Throwable>) {62 if (t.isNotEmpty()) {63 t.withIndex().forEach { (index, error) ->64 val testName = if (t.size == 1) "Engine exception" else "Engine exception ${index + 1}"65 println(TeamCityMessageBuilder.testStarted(prefix, testName).build())66 val message = error.message ?: t::class.bestName()67 println(TeamCityMessageBuilder.testFailed(prefix, testName).message(message).build())68 println(TeamCityMessageBuilder.testFinished(prefix, testName).build())69 }70 }71 }72 override suspend fun specStarted(kclass: KClass<*>) {73 val msg = TeamCityMessageBuilder74 .testSuiteStarted(prefix, formatter.format(kclass))75 .id(kclass.toDescriptor().path().value)76 .locationHint(Locations.location(kclass))77 .build()78 println(msg)79 }80 // ignored specs are completely hidden from output in team city81 override suspend fun specIgnored(kclass: KClass<*>, reason: String?) {}82 override suspend fun specFinished(kclass: KClass<*>, result: TestResult) {83 // if the spec itself has an error, we must insert a placeholder test84 when (val t = result.errorOrNull) {85 null -> Unit86 is MultipleExceptions -> t.causes.forEach { insertPlaceholder(it, kclass.toDescriptor()) }87 else -> insertPlaceholder(t, kclass.toDescriptor())88 }89 finishSpec(kclass)90 results.clear()91 children.clear()92 }93 private fun finishSpec(kclass: KClass<*>) {94 val msg = TeamCityMessageBuilder95 .testSuiteFinished(prefix, formatter.format(kclass))96 .id(kclass.toDescriptor().path().value)97 .locationHint(Locations.location(kclass))98 .build()99 println(msg)100 }101 override suspend fun testStarted(testCase: TestCase) {102 if (testCase.parent != null) addChild(testCase)103 when (testCase.type) {104 TestType.Container -> startTestSuite(testCase)105 TestType.Test -> startTest(testCase)106 TestType.Dynamic -> Unit107 }108 }109 override suspend fun testIgnored(testCase: TestCase, reason: String?) {110 ignoreTest(testCase, TestResult.Ignored(reason))111 }112 private fun addChild(testCase: TestCase) {113 children.getOrPut(testCase.descriptor.parent) { mutableListOf() }.add(testCase)114 }115 override suspend fun testFinished(testCase: TestCase, result: TestResult) {116 results[testCase.descriptor] = result117 when (testCase.type) {118 TestType.Container -> {119 failTestSuiteIfError(testCase, result)120 finishTestSuite(testCase, result)121 }122 TestType.Test -> {123 if (!started.contains(testCase.descriptor)) startTest(testCase)124 if (result.isErrorOrFailure) failTest(testCase, result)125 finishTest(testCase, result)126 }127 TestType.Dynamic -> {128 if (isParent(testCase)) {129 startTestSuite(testCase)130 failTestSuiteIfError(testCase, result)131 finishTestSuite(testCase, result)132 } else {133 startTest(testCase)134 if (result.isErrorOrFailure) failTest(testCase, result)135 finishTest(testCase, result)136 }137 }138 }139 }140 private fun failTestSuiteIfError(testCase: TestCase, result: TestResult) {141 // test suites cannot be in a failed state, so we must insert a placeholder to hold any error142 when (val t = result.errorOrNull) {143 null -> Unit144 is MultipleExceptions -> t.causes.forEach { insertPlaceholder(it, testCase.descriptor) }145 else -> insertPlaceholder(t, testCase.descriptor)146 }147 }148 // returns true if this test case is a parent149 private fun isParent(testCase: TestCase) = children.getOrElse(testCase.descriptor) { mutableListOf() }.isNotEmpty()150 /**151 * For a given [TestCase] will output the "test ignored" message.152 */153 private fun ignoreTest(testCase: TestCase, result: TestResult.Ignored) {154 val msg = TeamCityMessageBuilder155 .testIgnored(prefix, formatter.format(testCase))156 .id(testCase.descriptor.path().value)157 .parent(testCase.descriptor.parent.path().value)158 .locationHint(Locations.location(testCase.source))159 .message(result.reason)160 .result(result)161 .build()162 println(msg)163 }164 /**165 * For a [TestCase] will output the "test started" message.166 */167 private fun startTest(testCase: TestCase) {168 val msg = TeamCityMessageBuilder169 .testStarted(prefix, formatter.format(testCase))170 .id(testCase.descriptor.path().value)171 .parent(testCase.descriptor.parent.path().value)172 .locationHint(Locations.location(testCase.source))173 .build()174 println(msg)175 started.add(testCase.descriptor)176 }177 /**178 * For a given [TestCase] will output the "test failed" message.179 */180 private fun failTest(testCase: TestCase, result: TestResult) {181 val msg = TeamCityMessageBuilder182 .testFailed(prefix, formatter.format(testCase))183 .id(testCase.descriptor.path().value)184 .parent(testCase.descriptor.parent.path().value)185 .duration(result.duration)186 .locationHint(Locations.location(testCase.source))187 .withException(result.errorOrNull, details)188 .result(result)189 .build()190 println(msg)191 }192 /**193 * For a given [TestCase] will output the "test finished" message.194 */195 private fun finishTest(testCase: TestCase, result: TestResult) {196 val msg = TeamCityMessageBuilder197 .testFinished(prefix, formatter.format(testCase))198 .id(testCase.descriptor.path().value)199 .parent(testCase.descriptor.parent.path().value)200 .duration(result.duration)201 .locationHint(Locations.location(testCase.source))202 .result(result)203 .build()204 println(msg)205 }206 /**207 * For a given [TestCase] will output the "test suite started" message.208 */209 private fun startTestSuite(testCase: TestCase) {210 val msg = TeamCityMessageBuilder211 .testSuiteStarted(prefix, formatter.format(testCase))212 .id(testCase.descriptor.path().value)213 .parent(testCase.descriptor.parent.path().value)214 .locationHint(Locations.location(testCase.source))215 .build()216 println(msg)217 started.add(testCase.descriptor)218 }219 /**220 * For a given [TestCase] will output the "test suite finished" message.221 */222 private fun finishTestSuite(testCase: TestCase, result: TestResult) {223 val msg = TeamCityMessageBuilder224 .testSuiteFinished(prefix, formatter.format(testCase))225 .id(testCase.descriptor.path().value)226 .parent(testCase.descriptor.parent.path().value)227 .duration(result.duration)228 .locationHint(Locations.location(testCase.source))229 .result(result)230 .build()231 println(msg)232 }233}...
EnhancedConsoleTestEngineListener.kt
Source:EnhancedConsoleTestEngineListener.kt
...8import io.kotest.core.test.TestResult9import io.kotest.core.test.TestType10import io.kotest.engine.interceptors.EngineContext11import io.kotest.engine.test.names.DefaultDisplayNameFormatter12import io.kotest.engine.test.names.formatTestPath13import io.kotest.engine.test.names.getDisplayNameFormatter14import kotlin.reflect.KClass15import kotlin.time.Duration16/**17 * Generates test output to the console in an enhanced, formatted, coloured, way.18 * For a more basic output, see [BasicConsoleTestEngineListener]19 */20class EnhancedConsoleTestEngineListener(private val term: TermColors) : AbstractTestEngineListener() {21 private var errors = 022 private var start = System.currentTimeMillis()23 private var testsFailed = emptyList<Pair<TestCase, TestResult>>()24 private var testsIgnored = 025 private var testsPassed = 026 private var specsFailed = emptyList<Descriptor.SpecDescriptor>()27 private var specsSeen = emptyList<Descriptor>()28 private var slow = Duration.milliseconds(500)29 private var verySlow = Duration.milliseconds(5000)30 private var formatter:DisplayNameFormatter = DefaultDisplayNameFormatter(ProjectConfiguration())31 private fun green(str: String) = term.green(str)32 private fun greenBold(str: String) = term.green.plus(term.bold).invoke(str)33 private fun red(str: String) = term.red(str)34 private fun brightRed(str: String) = term.brightRed(str)35 private fun brightRedBold(str: String) = term.brightRed.plus(term.bold).invoke(str)36 private fun redBold(str: String) = term.red.plus(term.bold).invoke(str)37 private fun yellow(str: String) = term.yellow(str)38 private fun brightYellow(str: String) = term.brightYellow(str)39 private fun brightYellowBold(str: String) = term.brightYellow.plus(term.bold).invoke(str)40 private fun yellowBold(str: String) = term.yellow.plus(term.bold).invoke(str)41 private fun bold(str: String) = term.bold(str)42 private val intros = listOf(43 "Feeding the kotest engine with freshly harvested tests",44 "Engaging kotest engine at warp factor 9",45 "Harvesting the test fields",46 "Preparing to sacrifice your code to the demi-god of test",47 "Hamsters are turning the wheels of kotest",48 "Battle commanders are ready to declare war on bugs",49 "Be afraid - be very afraid - of failing tests",50 "The point is, ladies and gentlemen, that green is good",51 "Lock test-foils in attack position",52 "Fasten your seatbelts. It's going to be a bumpy test-run",53 "Lets crack open this test suite",54 "Lets get testing, I'm on the clock here",55 "Test time is the best time",56 "Open the test suite doors, HAL",57 "Mama always said testing was like a box of chocolates. You don't know which ones are gonna fail",58 "A test suite. Shaken, not stirred",59 "I'm going to make him a test he can't refuse",60 "You testing me? I don't see any other tests here, so you must be testing me",61 "I love the smell of tests in the morning",62 "Do you feel lucky punk? Do you think your tests will pass? Well, do ya?",63 "Mirab, with tests unfurled",64 "Dolly works 9 to 5. I test 24/7",65 "A test suite's gotta do what a test suite's gotta do",66 "I test code and chew bubblegum, and I'm all out of bubblegum"67 )68 override suspend fun engineInitialized(context: EngineContext) {69 formatter = getDisplayNameFormatter(context.configuration.registry, context.configuration)70 println(bold(">> Kotest"))71 println("- " + intros.shuffled().first())72 print("- Test plan has ")73 print(greenBold(context.suite.specs.size.toString()))74 println(" specs")75 println()76 }77 override suspend fun engineFinished(t: List<Throwable>) {78 if (specsSeen.isEmpty()) return79 if (t.isNotEmpty()) {80 errors += t.size81 t.forEach {82 printThrowable(it, 0)83 }84 }85 val duration = System.currentTimeMillis() - start86 val seconds = duration / 100087 if (errors == 0) {88 println(bold(">> All tests passed"))89 } else {90 println(redBold(">> There were test failures"))91 println()92 specsFailed.distinct().forEach { spec ->93 println(brightRedBold(" ${formatter.format(spec.kclass)}"))94 testsFailed.filter { it.first.spec::class.toDescriptor() == spec }.forEach { (testCase, _) ->95 println(brightRed(" - ${formatter.formatTestPath(testCase, " -- ")}"))96 }97 }98 }99 println()100 printSpecCounts()101 printTestsCounts()102 print("Time: ")103 println(bold("${seconds}s"))104 }105 private fun printThrowable(error: Throwable?, padding: Int) {106 if (error != null) {107 val message = error.message108 if (message != null) {109 println(brightRed(message.padStart(padding, ' ')))110 }111 error.stackTrace?.forEach {112 println(red("".padStart(padding + 2, ' ') + it))113 }114 }115 }116 private fun printSpecCounts() {117 val specsSeenSize = specsSeen.distinct().size118 val specsPassedSize = specsSeen.distinct().minus(specsFailed).size119 val specsFailedSize = specsFailed.distinct().size120 print("Specs: ")121 print(greenBold("$specsPassedSize passed"))122 print(", ")123 if (specsFailed.isEmpty()) {124 print(bold("$specsFailedSize failed"))125 print(bold(", "))126 } else {127 print(redBold("$specsFailedSize failed"))128 print(bold(", "))129 }130 println("$specsSeenSize total")131 }132 private fun printTestsCounts() {133 print("Tests: ")134 print(greenBold("$testsPassed passed"))135 print(", ")136 if (testsFailed.isEmpty()) {137 print(bold("${testsFailed.size} failed"))138 print(", ")139 } else {140 print(redBold("${testsFailed.size} failed"))141 print(", ")142 }143 if (testsIgnored > 0) {144 print(yellowBold("$testsIgnored ignored"))145 print(", ")146 } else {147 print(bold("$testsIgnored ignored"))148 print(", ")149 }150 println("${testsPassed + testsFailed.size + testsIgnored} total")151 }152 override suspend fun specStarted(kclass: KClass<*>) {153 specsSeen = specsSeen + kclass.toDescriptor()154 val specCount = specsSeen.size155 print(bold("$specCount. ".padEnd(4, ' ')))156 println(bold(formatter.format(kclass)))157 }158 override suspend fun specFinished(kclass: KClass<*>, result: TestResult) {159 if (result.isErrorOrFailure) {160 errors++161 specsFailed = specsFailed + kclass.toDescriptor()162 printThrowable(result.errorOrNull, 4)163 }164 println()165 }166 override suspend fun testIgnored(testCase: TestCase, reason: String?) {167 testsIgnored++168 print("".padEnd(testCase.descriptor.depth() * 4, ' '))169 print("- " + formatter.format(testCase))170 println(brightYellowBold(" IGNORED"))171 }172 private fun durationString(duration: Duration): String {173 return when {174 duration in slow..verySlow -> term.brightYellow("(${duration.inWholeMilliseconds}ms)")175 duration > verySlow -> term.brightRed("(${duration.inWholeMilliseconds}ms)")176 else -> ""177 }178 }179 override suspend fun testFinished(testCase: TestCase, result: TestResult) {180 // only leaf tests or failed containers contribute to the counts181 when (result) {182 is TestResult.Success -> if (testCase.type == TestType.Test) testsPassed++183 is TestResult.Failure, is TestResult.Error -> {184 errors++185 testsFailed = testsFailed + Pair(testCase, result)186 specsFailed = specsFailed + testCase.descriptor.spec()187 }188 else -> Unit189 }190 // we only print the name and status for leafs, as containers are printed in advance191 if (testCase.type == TestType.Test) {192 print("".padEnd(testCase.descriptor.depth() * 4, ' '))193 print("- " + formatter.format(testCase))194 when (result) {195 is TestResult.Success -> print(greenBold(" OK"))196 is TestResult.Error -> print(brightRed(" ERROR"))197 is TestResult.Failure -> print(brightRed(" FAILED"))198 is TestResult.Ignored -> print(brightYellow(" IGNORED"))199 }200 if (result.duration > slow) {201 print(" ${durationString(result.duration)}")202 }203 println()204 }205 if (result.errorOrNull != null) {206 println()207 printThrowable(result.errorOrNull, testCase.descriptor.depth() * 4)208 println()209 }210 }211 override suspend fun testStarted(testCase: TestCase) {212 // containers we display straight away without pass / fail message213 if (testCase.type == TestType.Container) {214 print("".padEnd(testCase.descriptor.depth() * 4, ' '))215 println("+ " + formatter.format(testCase))216 }217 }218}...
DefaultDisplayNameFormatterTest.kt
Source:DefaultDisplayNameFormatterTest.kt
...17@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()139@DisplayName("ZZZZZ")140private class SpecWithDisplayName : FunSpec({141 test("a") { }142})...
DefaultDisplayNameFormatter.kt
Source:DefaultDisplayNameFormatter.kt
...15fun 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 /**64 * Returns a formatted display name for this spec class.65 *66 * If the spec has been annotated with [DisplayName] (on supported platforms), then that will be used,67 * otherwise the default is to use the fully qualified class name.68 *69 * Note: This name must be globally unique. Two specs, even in different packages,70 * cannot share the same names, so if [DisplayName] is used, developers must ensure it does not71 * clash with another spec.72 */73 override fun format(kclass: KClass<*>): String {74 return when (platform) {75 Platform.JVM -> kclass.annotation<DisplayName>()?.wrapper ?: kclass.bestName()76 Platform.JS -> kclass.bestName()77 Platform.Native -> kclass.bestName()78 }79 }80}81fun appendTagsInDisplayName(testCase: TestCase, displayName: String): String {82 val tagNames = testCase.config.tags.joinToString(", ")83 return if (tagNames.isBlank()) {84 displayName85 } else {86 "${displayName}[tags = $tagNames]"87 }...
KotestTestRunner.kt
Source:KotestTestRunner.kt
...12import org.junit.runner.notification.RunNotifier13class KotestTestRunner(14 private val kclass: Class<out Spec>15) : Runner() {16 private val formatter = DefaultDisplayNameFormatter(ProjectConfiguration())17 override fun run(notifier: RunNotifier) {18 runBlocking {19 val listener = JUnitTestEngineListener(notifier)20 TestEngineLauncher(listener).withClasses(kclass.kotlin).launch()21 }22 }23 override fun getDescription(): Description {24 val spec = runBlocking { createAndInitializeSpec(kclass.kotlin, EmptyExtensionRegistry).getOrThrow() }25 val desc = Description.createSuiteDescription(spec::class.java)26 Materializer(ProjectConfiguration()).materialize(spec).forEach { rootTest ->27 desc.addChild(28 describeTestCase(29 rootTest,30 formatter.format(rootTest)31 )32 )33 }34 return desc35 }36}...
JUnitTestEngineListener.kt
Source:JUnitTestEngineListener.kt
...9import org.junit.runner.notification.RunNotifier10class JUnitTestEngineListener(11 private val notifier: RunNotifier,12) : AbstractTestEngineListener() {13 private val formatter = DefaultDisplayNameFormatter(ProjectConfiguration())14 override suspend fun testStarted(testCase: TestCase) {15 notifier.fireTestStarted(describeTestCase(testCase, formatter.format(testCase)))16 }17 override suspend fun testFinished(testCase: TestCase, result: TestResult) {18 val desc = describeTestCase(testCase, formatter.format(testCase))19 when (result) {20 is TestResult.Success -> notifier.fireTestFinished(desc)21 is TestResult.Error -> notifyFailure(desc, result)22 is TestResult.Ignored -> notifier.fireTestIgnored(desc)23 is TestResult.Failure -> notifyFailure(desc, result)24 }25 }26 private fun notifyFailure(desc: Description, result: TestResult) {27 notifier.fireTestFailure(Failure(desc, result.errorOrNull))28 notifier.fireTestFinished(desc)29 }30}...
format
Using AI Code Generation
1val displayNameFormatter = DefaultDisplayNameFormatter()2val displayName = displayNameFormatter.format(testCase)3println(displayName)4val testNameFormatter = DefaultTestNameFormatter()5val testName = testNameFormatter.format(testCase)6println(testName)7val testPathFormatter = DefaultTestPathFormatter()8val testPath = testPathFormatter.format(testCase)9println(testPath)10val testPathFormatter = DefaultTestPathFormatter()11val testPath = testPathFormatter.format(testCase)12println(testPath)13val testPathFormatter = DefaultTestPathFormatter()14val testPath = testPathFormatter.format(testCase)15println(testPath)16val testPathFormatter = DefaultTestPathFormatter()17val testPath = testPathFormatter.format(testCase)18println(testPath)19val testPathFormatter = DefaultTestPathFormatter()20val testPath = testPathFormatter.format(testCase)21println(testPath)22val testPathFormatter = DefaultTestPathFormatter()23val testPath = testPathFormatter.format(testCase)24println(testPath)25val testPathFormatter = DefaultTestPathFormatter()26val testPath = testPathFormatter.format(testCase)27println(testPath)28val testPathFormatter = DefaultTestPathFormatter()29val testPath = testPathFormatter.format(testCase)30println(testPath)31val testPathFormatter = DefaultTestPathFormatter()32val testPath = testPathFormatter.format(testCase)33println(testPath)34val testPathFormatter = DefaultTestPathFormatter()
format
Using AI Code Generation
1val displayNameFormatter = DefaultDisplayNameFormatter()2val displayName = displayNameFormatter.format(testCase)3val testCaseNameFormatter = DefaultTestCaseNameFormatter()4val testCaseName = testCaseNameFormatter.format(testCase)5val testPathFormatter = DefaultTestPathFormatter()6val testPath = testPathFormatter.format(testCase)7val testPathNameFormatter = DefaultTestPathNameFormatter()8val testPathName = testPathNameFormatter.format(testCase)9val testPathNameFormatter = DefaultTestPathNameFormatter()10val testPathName = testPathNameFormatter.format(testCase)11val testPathNameFormatter = DefaultTestPathNameFormatter()12val testPathName = testPathNameFormatter.format(testCase)13val testPathNameFormatter = DefaultTestPathNameFormatter()14val testPathName = testPathNameFormatter.format(testCase)15val testPathNameFormatter = DefaultTestPathNameFormatter()16val testPathName = testPathNameFormatter.format(testCase)17val testPathNameFormatter = DefaultTestPathNameFormatter()18val testPathName = testPathNameFormatter.format(testCase)19val testPathNameFormatter = DefaultTestPathNameFormatter()20val testPathName = testPathNameFormatter.format(testCase)21val testPathNameFormatter = DefaultTestPathNameFormatter()22val testPathName = testPathNameFormatter.format(testCase)
format
Using AI Code Generation
1val displayNameFormatter = DefaultDisplayNameFormatter()2println(displayNameFormatter.format("test name"))3println(duplicateTestNameMode.format("test name", 2))4println(duplicateTestNameMode.format("test name", 2))5println(duplicateTestNameMode.format("test name", 2))6println(duplicateTestNameMode.format("test name", 2))7println(duplicateTestNameMode.format("test name", 2))8println(duplicateTestNameMode.format("test name", 2))9println(duplicateTestNameMode.format("test name", 2))10println(duplicateTestNameMode.format("test name", 2))
format
Using AI Code Generation
1val formatter = DefaultDisplayNameFormatter()2println(formatter.format(TestName("MyTest", "my test")))3val formatter = DefaultDisplayNameFormatter()4println(formatter.format(TestName("MyTest", "my test")))5val formatter = DefaultDisplayNameFormatter()6println(formatter.format(TestName("MyTest", "my test")))7val formatter = DefaultDisplayNameFormatter()8println(formatter.format(TestName("MyTest", "my test")))9val formatter = DefaultDisplayNameFormatter()10println(formatter.format(TestName("MyTest", "my test")))11val formatter = DefaultDisplayNameFormatter()12println(formatter.format(TestName("MyTest", "my test")))13val formatter = DefaultDisplayNameFormatter()14println(formatter.format(TestName("MyTest", "my test")))15val formatter = DefaultDisplayNameFormatter()16println(formatter.format(TestName("MyTest", "my test")))17val formatter = DefaultDisplayNameFormatter()18println(formatter.format(TestName("MyTest", "my test")))19val formatter = DefaultDisplayNameFormatter()20println(formatter.format(TestName("MyTest", "my test")))21val formatter = DefaultDisplayNameFormatter()
format
Using AI Code Generation
1val displayNameFormatter = DefaultDisplayNameFormatter() 2val displayName = displayNameFormatter.format(name) 3println(displayName)4val displayNameFormatter = DisplayNameFormatter { it } 5val displayName = displayNameFormatter.format(name) 6println(displayName)7import io.kotest.core.names.DisplayNameFormatter8class DefaultDisplayNameFormatter(private val useSpaces: Boolean = false) : DisplayNameFormatter {9override fun format(name: String): String = 10if (useSpaces) name.replace("_", " ") else name11}12typealias DisplayNameFormatter = (String) -> String13interface DisplayNameFormatter {14fun format(name: String): String15}16class NoopDisplayNameFormatter : DisplayNameFormatter {17override fun format(name: String): String = name18}
format
Using AI Code Generation
1val formatter = DefaultDisplayNameFormatter()2val displayName = formatter.format("My test case")3println(displayName)4val displayName = duplicateNameMode.format("My test case")5println(displayName)6My test case (1)7val displayName = duplicateNameMode.format("My test case")8println(displayName)9val displayName = duplicateNameMode.format("My test case")10println(displayName)11val displayName = duplicateNameMode.format("My test case")12println(displayName)13My test case (1)14val displayName = duplicateNameMode.format("My test case")15println(displayName)16val displayName = duplicateNameMode.format("My test case")17println(displayName)18val displayName = duplicateNameMode.format("My test case")19println(displayName)20My test case (1)21val displayName = duplicateNameMode.format("My test case")22println(displayName)
format
Using AI Code Generation
1val formatter = DefaultDisplayNameFormatter()2val displayName = formatter.format("ClassName", "testName")3println(displayName)4val formatter = object : DisplayNameFormatter {5override fun format(className: String, testName: String): String {6}7}8val displayName = formatter.format("ClassName", "testName")9println(displayName)10val listener = object : KotestEngineListener {11override fun testStarted(testCase: TestCase) {12println("Test Started : $testCase")13}14override fun testFinished(testCase: TestCase, result: TestResult) {15println("Test Finished : $testCase")16}17override fun testIgnored(testCase: TestCase, reason: String?) {18println("Test Ignored : $testCase")19}20override fun testFailed(testCase: TestCase, error: Throwable) {21println("Test Failed : $testCase")22}23}24KotestEngineLauncher()25.registerListener(listener)26KotestEngineLauncher()27.registerListener(listener)28.launch()29val listener = object : KotestEngineListener {30override fun testStarted(testCase: TestCase) {31println("Test Started : $testCase")32}33override fun testFinished(testCase: TestCase, result: TestResult) {34println("Test Finished : $testCase")35}
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!!