Best Kotest code snippet using io.kotest.engine.tags.runtime
Kotest.kt
Source:Kotest.kt
...112 override fun executeTests() {113 //val testResultsDir = project.buildDir.resolve("test-results")114 val sourceset = project.javaTestSourceSet() ?: return115 val result = try {116 val exec = exec(sourceset.runtimeClasspath)117 if (isIntellij()) rerouteTeamCityListener(exec)118 exec.execute()119 } catch (e: Exception) {120 println(e)121 e.printStackTrace()122 throw GradleException("Test process failed", e)123 }124 if (result.exitValue != 0) {125 throw GradleException("There were test failures")126 }127 }128}...
build.gradle.kts
Source:build.gradle.kts
...11repositories {12 jcenter()13}14dependencies {15 implementation(gradleApi()) // Implementation: available at compile and runtime, non transitive16 testImplementation(gradleTestKit()) // Test implementation: available for testing compile and runtime17 testImplementation("io.kotest:kotest-runner-junit5:4.2.5") // for kotest framework18 testImplementation("io.kotest:kotest-assertions-core:4.2.5") // for kotest core assertions19 testImplementation("io.kotest:kotest-assertions-core-jvm:4.2.5") // for kotest core jvm assertions20}21tasks.withType<Test> {22 useJUnitPlatform() // Use JUnit 5 engine23 testLogging.showStandardStreams = true24 testLogging {25 showCauses = true26 showStackTraces = true27 showStandardStreams = true28 events(*org.gradle.api.tasks.testing.logging.TestLogEvent.values())29 exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL30 }31}32// This task creates a file with a classpath descriptor, to be used in tests33val createClasspathManifest by tasks.registering {34 val outputDir = file("$buildDir/$name")35 inputs.files(sourceSets.main.get().runtimeClasspath)36 outputs.dir(outputDir)37 doLast {38 outputDir.mkdirs()39 file("$outputDir/plugin-classpath.txt").writeText(sourceSets.main.get().runtimeClasspath.joinToString("\n"))40 }41}42// Add the classpath file to the test runtime classpath43dependencies {44 // This way "createClasspathManifest" is always executed before the tests!45 // Gradle auto-resolves dependencies if there are dependencies on inputs/outputs46 testRuntimeOnly(files(createClasspathManifest))47}48pluginBundle { // These settings are set for the whole plugin bundle49 website = "https://danysk.github.io/Course-Laboratory-of-Software-Systems/"50 vcsUrl = "https://github.com/DanySK/Course-Laboratory-of-Software-Systems"51 tags = listOf("example", "greetings", "lss", "unibo")52}53gradlePlugin {54 plugins {55 create("GradleLatex") { // One entry per plugin56 id = "${project.group}.${project.name}"...
TestEngine.kt
Source:TestEngine.kt
...8import io.kotest.core.project.TestSuite9import io.kotest.engine.interceptors.EngineContext10import io.kotest.engine.interceptors.EngineInterceptor11import io.kotest.engine.listener.TestEngineListener12import io.kotest.engine.tags.runtimeTags13import io.kotest.mpp.Logger14data class EngineResult(val errors: List<Throwable>) {15 companion object {16 val empty = EngineResult(emptyList())17 }18 fun addError(t: Throwable): EngineResult {19 return EngineResult(errors + t)20 }21}22@KotestInternal23data class TestEngineConfig(24 val listener: TestEngineListener,25 val interceptors: List<EngineInterceptor>,26 val configuration: ProjectConfiguration,27 val explicitTags: TagExpression?,28)29/**30 * Multiplatform Kotest Test Engine.31 */32@KotestInternal33class TestEngine(private val config: TestEngineConfig) {34 private val logger = Logger(this::class)35 /**36 * Starts execution of the given [TestSuite], intercepting calls via [EngineInterceptor]s.37 *38 * It is recommended that this method is not invoked, but instead the engine39 * is launched via the [TestEngineLauncher].40 */41 @OptIn(KotestInternal::class, ExperimentalKotest::class)42 internal suspend fun execute(suite: TestSuite): EngineResult {43 logger.log { Pair(null, "Executing test suite with ${suite.specs.size} specs") }44 val innerExecute: suspend (EngineContext) -> EngineResult = { context ->45 val scheduler = when (platform) {46 Platform.JVM -> ConcurrentTestSuiteScheduler(47 config.configuration.concurrentSpecs ?: config.configuration.parallelism,48 context,49 )50 Platform.JS -> SequentialTestSuiteScheduler(context)51 Platform.Native -> SequentialTestSuiteScheduler(context)52 }53 scheduler.schedule(context.suite)54 }55 logger.log { Pair(null, "${config.interceptors.size} engine interceptors") }56 val execute = config.interceptors.foldRight(innerExecute) { extension, next ->57 { context -> extension.intercept(context, next) }58 }59 val tags = config.configuration.runtimeTags()60 logger.log { Pair(null, "TestEngine: Active tags: ${tags.expression}") }61 return execute(EngineContext(suite, config.listener, tags, config.configuration))62 }63}...
RequiresTagSpecInterceptor.kt
Source:RequiresTagSpecInterceptor.kt
...12import io.kotest.engine.listener.TestEngineListener13import io.kotest.engine.spec.SpecExtensions14import io.kotest.engine.tags.isActive15import io.kotest.engine.tags.parse16import io.kotest.engine.tags.runtimeTags17import io.kotest.mpp.annotation18/**19 * A [SpecFilter] which will ignore specs if they are annotated with @[RequiresTag]20 * and those tags are not present in the runtime tags.21 */22internal class RequiresTagSpecInterceptor(23 private val listener: TestEngineListener,24 private val configuration: ProjectConfiguration,25 private val registry: ExtensionRegistry,26) : SpecRefInterceptor {27 override suspend fun intercept(28 ref: SpecRef,29 fn: suspend (SpecRef) -> Result<Map<TestCase, TestResult>>30 ): Result<Map<TestCase, TestResult>> {31 return when (val annotation = ref.kclass.annotation<RequiresTag>()) {32 null -> fn(ref)33 else -> {34 val requiredTags = annotation.wrapper.map { NamedTag(it) }.toSet()35 val expr = configuration.runtimeTags().parse()36 if (requiredTags.isEmpty() || expr.isActive(requiredTags)) {37 fn(ref)38 } else {39 runCatching { listener.specIgnored(ref.kclass, "Disabled by @RequiresTag") }40 .flatMap { SpecExtensions(registry).ignored(ref.kclass, "Disabled by @RequiresTag") }41 .map { emptyMap() }42 }43 }44 }45 }46}...
RuntimeTagExtensionTest.kt
Source:RuntimeTagExtensionTest.kt
...33 }34}35private class TestWithTag : FunSpec() {36 init {37 test("Test marked with a runtime excluded tag").config(tags = setOf(MyRuntimeExcludedTag)) {38 fail("boom")39 }40 }41}...
TagsExcludedDiscoveryExtension.kt
Source:TagsExcludedDiscoveryExtension.kt
...9import io.kotest.engine.listener.TestEngineListener10import io.kotest.engine.spec.SpecExtensions11import io.kotest.engine.tags.isPotentiallyActive12import io.kotest.engine.tags.parse13import io.kotest.engine.tags.runtimeTags14/**15 * Filters any [Spec] that can be eagerly excluded based on the @[TagExpression] annotation at the class level.16 */17class TagsExcludedSpecInterceptor(18 private val listener: TestEngineListener,19 private val conf: ProjectConfiguration,20) : SpecRefInterceptor {21 private val extensions = SpecExtensions(conf.registry)22 override suspend fun intercept(23 ref: SpecRef,24 fn: suspend (SpecRef) -> Result<Map<TestCase, TestResult>>25 ): Result<Map<TestCase, TestResult>> {26 val potentiallyActive = conf.runtimeTags().parse().isPotentiallyActive(ref.kclass)27 return if (potentiallyActive) {28 fn(ref)29 } else {30 runCatching { listener.specIgnored(ref.kclass, null) }31 .flatMap { extensions.ignored(ref.kclass, "Skipped by tags") }32 .map { emptyMap() }33 }34 }35}
runtime
Using AI Code Generation
1 val runtimeClass = Class.forName("io.kotest.engine.tags.TagExpression")2 val instance = runtimeClass.getConstructor(String::class.java).newInstance("abc")3 println(instance)4 val runtimeClass = Class.forName("io.kotest.core.spec.style.scopes.RootContext")5 val instance = runtimeClass.getConstructor().newInstance()6 println(instance)7 val runtimeClass = Class.forName("io.kotest.core.spec.style.scopes.RootContext")8 val instance = runtimeClass.getConstructor().newInstance()9 println(instance)10}11 at java.net.URLClassLoader.findClass(URLClassLoader.java:382)12 at java.lang.ClassLoader.loadClass(ClassLoader.java:418)13 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:355)14 at java.lang.ClassLoader.loadClass(ClassLoader.java:351)15 at java.lang.Class.forName0(Native Method)16 at java.lang.Class.forName(Class.java:348)17 at com.example.MainKt.main(Main.kt:9)18 at com.example.MainKt.main(Main.kt)
runtime
Using AI Code Generation
1 val tags = TestTag::class.sealedSubclasses.map { it.objectInstance as TestTag }2 val styles = SpecStyle::class.sealedSubclasses.map { it.objectInstance as SpecStyle }3 val configs = TestCaseConfig::class.sealedSubclasses.map { it.objectInstance as TestCaseConfig }4 val levels = TestCaseSeverityLevel::class.sealedSubclasses.map { it.objectInstance as TestCaseSeverityLevel }5 val orders = TestCaseOrder::class.sealedSubclasses.map { it.objectInstance as TestCaseOrder }6 val configs = TestCaseConfig::class.sealedSubclasses.map { it.objectInstance as TestCaseConfig }7 val levels = TestCaseSeverityLevel::class.sealedSubclasses.map { it.objectInstance as TestCaseSeverityLevel }8 val orders = TestCaseOrder::class.sealedSubclasses.map { it.objectInstance as TestCaseOrder }9 val configs = TestCaseConfig::class.sealedSubclasses.map { it.objectInstance as TestCaseConfig }10 val levels = TestCaseSeverityLevel::class.sealedSubclasses.map { it.objectInstance as TestCaseSeverityLevel }11 val orders = TestCaseOrder::class.sealedSubclasses.map { it.objectInstance as TestCaseOrder }12 val configs = TestCaseConfig::class.sealedSubclasses.map { it.objectInstance as TestCaseConfig }13 val levels = TestCaseSeverityLevel::class.sealedSubclasses.map { it.objectInstance as TestCase
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!!