Best Kotest code snippet using io.kotest.core.descriptors.SpecDescriptor.spec
EnhancedConsoleTestEngineListener.kt
Source:EnhancedConsoleTestEngineListener.kt
...22 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) {...
descriptor.kt
Source:descriptor.kt
...13 */14sealed interface Descriptor {15 val id: DescriptorId16 /**17 * A [Descriptor] for a spec class or a script file.18 */19 data class SpecDescriptor(20 override val id: DescriptorId,21 val kclass: KClass<*>,22 ) : Descriptor23 /**24 * A [Descriptor] for a test.25 */26 data class TestDescriptor(27 val parent: Descriptor,28 override val id: DescriptorId,29 ) : Descriptor30 companion object {31 const val SpecDelimiter = "/"32 const val TestDelimiter = " -- "33 }34 fun ids(): List<DescriptorId> = when (this) {35 is SpecDescriptor -> listOf(this.id)36 is TestDescriptor -> this.parent.ids() + this.id37 }38 /**39 * Returns a parseable path to the test.40 *41 * @param includeSpec if true then the spec name is included in the path.42 */43 fun path(includeSpec: Boolean = true): TestPath = when (this) {44 is SpecDescriptor -> if (includeSpec) TestPath(this.id.value) else error("Cannot call path on spec with includeSpec=false")45 is TestDescriptor -> when (this.parent) {46 is SpecDescriptor -> when (includeSpec) {47 true -> TestPath(this.parent.id.value + SpecDelimiter + this.id.value)48 false -> TestPath(this.id.value)49 }50 is TestDescriptor -> TestPath(this.parent.path(includeSpec).value + TestDelimiter + this.id.value)51 }52 }53 @KotestInternal54 fun parts(): List<String> = when (this) {55 is SpecDescriptor -> emptyList()56 is TestDescriptor -> parent.parts() + listOf(this.id.value)57 }58 /**59 * Returns true if this descriptor is for a class based test file.60 */61 fun isSpec() = this is SpecDescriptor62 /**63 * Returns true if this descriptor is for a test case.64 */65 fun isTestCase() = this is TestDescriptor66 /**67 * Returns true if this descriptor represents a root test case.68 */69 fun isRootTest() = this is TestDescriptor && this.parent.isSpec()70 /**71 * Returns the depth of this node, where the [SpecDescriptor] has depth of 0,72 * a root test has depth 1 and so on.73 */74 fun depth() = parents().size - 175 /**76 * Recursively returns any parent descriptors, with the spec being first in the list77 * and this being last.78 */79 fun parents(): List<Descriptor> = when (this) {80 is SpecDescriptor -> emptyList()81 is TestDescriptor -> parent.parents() + parent82 }83 fun chain() = parents() + this84 /**85 * Returns true if this descriptor is the immediate parent of the given [descriptor].86 */87 fun isParentOf(descriptor: Descriptor): Boolean = when (descriptor) {88 is SpecDescriptor -> false // nothing can be the parent of a spec89 is TestDescriptor -> this.id == descriptor.parent.id90 }91 /**92 * Returns true if this descriptor is ancestor (1..nth-parent) of the given [descriptor].93 */94 fun isAncestorOf(descriptor: Descriptor): Boolean = when (descriptor) {95 is SpecDescriptor -> false // nothing can be an ancestor of a spec96 is TestDescriptor -> this.id == descriptor.parent.id || isAncestorOf(descriptor.parent)97 }98 /**99 * Returns true if this descriptor is the immediate child of the given [descriptor].100 */101 fun isChildOf(descriptor: Descriptor): Boolean = descriptor.isParentOf(this)102 /**103 * Returns true if this descriptor is a child, grandchild, etc of the given [descriptor].104 */105 fun isDescendentOf(descriptor: Descriptor): Boolean = descriptor.isAncestorOf(this)106 /**107 * Returns true if this instance is on the path to the given description. That is, if this108 * instance is either an ancestor of, of the same as, the given description.109 */110 fun isOnPath(description: Descriptor): Boolean =111 this.path() == description.path() || this.isAncestorOf(description)112 /**113 * Returns the [SpecDescriptor] parent for this [Descriptor].114 * If this is already a spec descriptor, then returns itself.115 */116 fun spec(): SpecDescriptor = when (this) {117 is SpecDescriptor -> this118 is TestDescriptor -> this.parent.spec()119 }120}121data class DescriptorId(val value: String)122fun SpecDescriptor.append(name: TestName): TestDescriptor =123 TestDescriptor(this, DescriptorId(name.testName))124fun TestDescriptor.append(name: TestName): TestDescriptor =125 this.append(name.testName)126fun Descriptor.append(name: String): TestDescriptor =127 TestDescriptor(this, DescriptorId(name))128/**129 * Returns the [TestDescriptor] that is the root for this [TestDescriptor].130 * This may be the same descriptor that this method is invoked on, if that descriptor131 * is a root test.132 */133fun TestDescriptor.root(): TestDescriptor {134 return when (parent) {135 is SpecDescriptor -> this // if my parent is a spec, then I am a root136 is TestDescriptor -> parent.root()137 }138}...
ThingTestCases.kt
Source:ThingTestCases.kt
...6 http://www.apache.org/licenses/LICENSE-2.07 Unless required by applicable law or agreed to in writing, software8 distributed under the License is distributed on an "AS IS" BASIS,9 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.10 See the License for the specific language governing permissions and11 limitations under the License.12*/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))...
descriptors.kt
Source:descriptors.kt
1package io.kotest.runner.junit.platform2import io.kotest.core.descriptors.Descriptor3import org.junit.platform.engine.TestDescriptor4import org.junit.platform.engine.TestSource5import org.junit.platform.engine.UniqueId6import org.junit.platform.engine.support.descriptor.AbstractTestDescriptor7import org.junit.platform.engine.support.descriptor.ClassSource8/**9 * Creates a [TestDescriptor] from the given class, and attaches it to the engine,10 * if one does not already exist.11 *12 * The created Test Descriptor will have segment type [Segment.Spec] and will use [displayName].13 */14fun getSpecDescriptor(15 engine: TestDescriptor,16 descriptor: Descriptor.SpecDescriptor,17 displayName: String,18): TestDescriptor {19 val id = engine.uniqueId.append(Segment.Spec.value, descriptor.id.value)20 return engine.findByUniqueId(id).orElseGet { null }21 ?: createAndRegisterSpecDescription(engine, descriptor, displayName)22}23private fun createAndRegisterSpecDescription(24 engine: TestDescriptor,25 descriptor: Descriptor.SpecDescriptor,26 displayName: String,27): TestDescriptor {28 val id = engine.uniqueId.append(Segment.Spec.value, descriptor.id.value)29 val source = ClassSource.from(descriptor.kclass.java)30 val testDescriptor: TestDescriptor = object : AbstractTestDescriptor(id, displayName, source) {31 override fun getType(): TestDescriptor.Type = TestDescriptor.Type.CONTAINER32 override fun mayRegisterTests(): Boolean = true33 }34 engine.addChild(testDescriptor)35 return testDescriptor36}37/**38 * Creates a [TestDescriptor] for the given [testCase] and attaches it to the [parent].39 * The created descriptor will have segment type [Segment.Test] and will use [displayName].40 */41fun createTestDescriptor(42 id: UniqueId,43 displayName: String,44 type: TestDescriptor.Type,45 source: TestSource?,46 mayRegisterTests: Boolean,47): TestDescriptor = object : AbstractTestDescriptor(id, displayName, source) {48 // there is a bug in gradle 4.7+ whereby CONTAINER_AND_TEST breaks test reporting or hangs the build, as it is not handled49 // see https://github.com/gradle/gradle/issues/491250 // so we can't use CONTAINER_AND_TEST for our test scopes, but simply container51 // update jan 2020: Seems we can use CONTAINER_AND_TEST now in gradle 6, and CONTAINER is invisible in output52 // update sep 2021: gradle 7.1 seems we can use TEST for everything but CONTAINER_AND_TEST will not show without a contained test53 // update for 5.0.0.M2 - will just dynamically add tests after they have completed, and we can see the full tree54 // update 5.0.0.M3 - if we add dynamically afterwards then the timings are all messed up, seems gradle keeps the time itself55 override fun getType(): TestDescriptor.Type = type56 override fun mayRegisterTests(): Boolean = mayRegisterTests57}...
PostDiscoveryFilterAdapter.kt
Source:PostDiscoveryFilterAdapter.kt
...39 val source = when (descriptor) {40 is Descriptor.SpecDescriptor -> ClassSource.from(descriptor.kclass.java)41 // this isn't a method, but we can use MethodSource with the test name, so it's at least42 // somewhat compatible for top level tests.43 is Descriptor.TestDescriptor -> MethodSource.from(descriptor.spec().kclass.java.name, descriptor.path().value)44 }45 return io.kotest.runner.junit.platform.createTestDescriptor(46 id,47 displayName,48 TestDescriptor.Type.CONTAINER,49 source,50 false51 )52 }53}...
GradleClassMethodRegexTestFilter.kt
Source:GradleClassMethodRegexTestFilter.kt
...29data class GradleTestPattern(val pckage: String?, val classname: String?, val path: List<String>) {30 companion object {31 // if the regex starts with a lower case character, then we assume it is in the format package.Class.testpath32 // otherwise, we assume it is in the format Class.testpath33 // the .testpath is always optional, and at least Class or package must be specified34 fun parse(pattern: String): GradleTestPattern {35 val tokens = pattern.split('.')36 val classIndex = tokens.indexOfFirst { it.first().isUpperCase() }37 // if class is not specified, then we assume the entire string is a package38 if (classIndex == -1) return GradleTestPattern(pattern, null, emptyList())39 // if the class is the first part, then no package is specified40 val pck = if (classIndex == 0) null else tokens.take(classIndex).joinToString(".")41 val pathParts = tokens.drop(classIndex + 1)42 val path = if (pathParts.isEmpty()) emptyList() else pathParts.joinToString(".").split(Descriptor.TestDelimiter)43 return GradleTestPattern(pck, tokens[classIndex], path)44 }45 }46}...
uniqueids.kt
Source:uniqueids.kt
...13}14sealed class Segment {15 abstract val value: String16 object Spec : Segment() {17 override val value: String = "spec"18 }19 object Script : Segment() {20 override val value: String = "script"21 }22 object Test : Segment() {23 override val value: String = "test"24 }25}...
kclasses.kt
Source:kclasses.kt
1package io.kotest.core.descriptors2import io.kotest.core.descriptors.Descriptor.SpecDescriptor3import io.kotest.mpp.bestName4import kotlin.reflect.KClass5/**6 * Returns a [SpecDescriptor] for a class using the fully qualified name for the identifier.7 *8 * On platforms where the FQN is not available, this will fall back to the simple class name.9 */10fun KClass<*>.toDescriptor(): SpecDescriptor {11 return SpecDescriptor(12 DescriptorId(this.bestName()),13 this,14 )15}...
spec
Using AI Code Generation
1val spec = object : StringSpec({2"this is a test" {3}4})5val spec = object : FunSpec({6test("this is a test") {7}8})9val spec = object : BehaviorSpec({10Given("some context") {11When("some action") {12Then("some result") {13}14}15}16})17val spec = object : ExpectSpec({18context("some context") {19expect("some result") {20}21}22})23val spec = object : FeatureSpec({24feature("some feature") {25scenario("some scenario") {26}27}28})29val spec = object : FreeSpec({30"some context" - {31"some result" {32}33}34})35val spec = object : WordSpec({36"some context" should {37"some result" {38}39}40})41val spec = object : DescribeSpec({42describe("some context") {43it("some result") {44}45}46})47val spec = object : ShouldSpec({48"some context" {49"some result" {50}51}52})53val spec = object : FunSpec({54test("some result") {55}56})57val spec = object : FunSpec({58test("some result") {59}60})61val spec = object : FunSpec({62test("some result") {63}64})65val spec = object : FunSpec({66test("some result") {67}68})
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!!