Best Kotest code snippet using io.kotest.framework.discovery.DiscoveryResult.discover
Discovery.kt
Source:Discovery.kt
1@file:Suppress("unused")2package io.kotest.framework.discovery3import io.github.classgraph.ClassGraph4import io.github.classgraph.ClassInfo5import io.kotest.core.extensions.DiscoveryExtension6import io.kotest.core.internal.KotestEngineProperties7import io.kotest.core.spec.Spec8import io.kotest.mpp.log9import io.kotest.mpp.syspropOrEnv10import java.lang.management.ManagementFactory11import java.util.concurrent.ConcurrentHashMap12import kotlin.reflect.KClass13//import kotlin.script.templates.standard.ScriptTemplateWithArgs14/**15 * Contains the results of a discovery request scan.16 *17 * @specs these are classes which extend one of the spec types18 * @scripts these are kotlin scripts which may or may not contain tests19 */20data class DiscoveryResult(21 val specs: List<KClass<out Spec>>,22 val scripts: List<KClass<*>>,23 val error: Throwable?, // this error is set if there was an exception during discovery24) {25 companion object {26 fun error(t: Throwable): DiscoveryResult = DiscoveryResult(emptyList(), emptyList(), t)27 }28}29/**30 * Scans for tests as specified by a [DiscoveryRequest].31 *32 * [DiscoveryExtension] `afterScan` functions are applied after the scan is complete to33 * optionally filter the returned classes.34 */35class Discovery(private val discoveryExtensions: List<DiscoveryExtension> = emptyList()) {36 private val requests = ConcurrentHashMap<DiscoveryRequest, DiscoveryResult>()37 // the results of a classpath scan, lazily executed and memoized.38 private val scanResult = lazy { classgraph().scan() }39 // filter functions40 //private val isScript: (KClass<*>) -> Boolean = { ScriptTemplateWithArgs::class.java.isAssignableFrom(it.java) }41 private val isSpecSubclassKt: (KClass<*>) -> Boolean = { Spec::class.java.isAssignableFrom(it.java) }42 private val isSpecSubclass: (Class<*>) -> Boolean = { Spec::class.java.isAssignableFrom(it) }43 private val isAbstract: (KClass<*>) -> Boolean = { it.isAbstract }44 private val fromClassPaths: List<KClass<out Spec>> by lazy { scanUris() }45 /**46 * Returns a function that applies all the [DiscoveryFilter]s to a given class.47 * The class must pass all the filters to be included.48 */49 private fun filterFn(filters: List<DiscoveryFilter>): (KClass<out Spec>) -> Boolean = { kclass ->50 filters.isEmpty() || filters.all { it.test(kclass) }51 }52 /**53 * Returns a function that applies all the [DiscoverySelector]s to a given class.54 * The class must pass any one selector to be included.55 */56 private fun selectorFn(selectors: List<DiscoverySelector>): (KClass<out Spec>) -> Boolean = { kclass ->57 selectors.isEmpty() || selectors.any { it.test(kclass) }58 }59 fun discover(request: DiscoveryRequest): DiscoveryResult =60 requests.getOrPut(request) { doDiscovery(request).getOrElse { DiscoveryResult.error(it) } }61// /**62// * Scans the classpaths for kotlin script files.63// */64// private fun discoverScripts(): List<KClass<out ScriptTemplateWithArgs>> {65// log { "Discovery: Running script scan" }66// return scanResult.value67// .allClasses68// .filter { it.extendsSuperclass(ScriptTemplateWithArgs::class.java.name) }69// .map { it.load(false) }70// .filter(isScript)71// .filterIsInstance<KClass<out ScriptTemplateWithArgs>>()72// }73 /**74 * Loads a class reference from a [ClassInfo].75 *76 * @param init false to avoid initializing the class77 */78 private fun ClassInfo.load(init: Boolean): KClass<out Any> =79 Class.forName(name, init, this::class.java.classLoader).kotlin80 private fun doDiscovery(request: DiscoveryRequest): Result<DiscoveryResult> = runCatching {81 val specClasses =82 if (request.onlySelectsSingleClasses()) loadSelectedSpecs(request) else fromClassPaths83 val filtered = specClasses84 .asSequence()85 .filter(selectorFn(request.selectors))86 .filter(filterFn(request.filters))87 // all classes must subclass one of the spec parents88 .filter(isSpecSubclassKt)89 // we don't want abstract classes90 .filterNot(isAbstract)91 .toList()92 log { "After filters there are ${filtered.size} spec classes" }93 log { "[Discovery] Further filtering classes via discovery extensions [$discoveryExtensions]" }94 val afterExtensions = discoveryExtensions95 .fold(filtered) { cl, ext -> ext.afterScan(cl) }96 .sortedBy { it.simpleName }97 log { "After discovery extensions there are ${afterExtensions.size} spec classes" }98 val scriptsEnabled = System.getProperty(KotestEngineProperties.scriptsEnabled) == "true" ||99 System.getenv(KotestEngineProperties.scriptsEnabled) == "true"100// val scripts = when {101// scriptsEnabled -> discoverScripts()102// else -> emptyList()103// }104 if (scanResult.isInitialized()) runCatching { scanResult.value.close() }105 log { "Discovery result [${afterExtensions.size} specs; scripts]" }106 DiscoveryResult(afterExtensions, emptyList(), null)107 }108 /**109 * Returns whether this is a request that selects single classes110 * only. Used to avoid full classpath scans when not necessary.111 */112 private fun DiscoveryRequest.onlySelectsSingleClasses(): Boolean =113 selectors.isNotEmpty() &&114 selectors.all { it is DiscoverySelector.ClassDiscoverySelector }115 /**116 * Returns a list of [Spec] classes from discovery requests that only have117 * selectors of type [DiscoverySelector.ClassDiscoverySelector].118 */119 private fun loadSelectedSpecs(request: DiscoveryRequest): List<KClass<out Spec>> {120 log { "Discovery: Loading specified classes..." }121 val start = System.currentTimeMillis()122 // first filter down to spec instances only, then load the full class123 val loadedClasses = request124 .selectors125 .asSequence()126 .filterIsInstance<DiscoverySelector.ClassDiscoverySelector>()127 .map { Class.forName(it.className, false, this::class.java.classLoader) }128 .filter(isSpecSubclass)129 .map { Class.forName(it.name).kotlin }130 .filterIsInstance<KClass<out Spec>>()131 .toList()132 val duration = System.currentTimeMillis() - start133 log { "Discovery: Loading of selected classes completed in ${duration}ms" }134 return loadedClasses135 }136 /**137 * Returns a list of [Spec] classes detected using classgraph in the list of138 * locations specified by the uris param.139 */140 private fun scanUris(): List<KClass<out Spec>> {141 log {142 val uptime = ManagementFactory.getRuntimeMXBean().uptime143 "Discovery: Starting test discovery scan... [uptime=$uptime]"144 }145 val result = scanResult.value146 .getSubclasses(Spec::class.java.name)147 .map { Class.forName(it.name).kotlin }148 .filterIsInstance<KClass<out Spec>>()149 log {150 val start = System.currentTimeMillis()151 val duration = System.currentTimeMillis() - start152 "Discovery: Test discovery completed in ${duration}ms"153 }154 return result155 }156 private fun classgraph(): ClassGraph {157 @Suppress("DEPRECATION")158 return ClassGraph()159 .enableClassInfo()160 .enableExternalClasses()161 .ignoreClassVisibility()162 .disableNestedJarScanning()163 // do not change this to use reject as it will break clients using older versions of classgraph164 .blacklistPackages(165 "java.*",166 "javax.*",...
launcher.kt
Source:launcher.kt
...7import io.kotest.core.filter.TestFilterResult8import io.kotest.core.spec.Spec9import io.kotest.engine.TestEngineLauncher10import io.kotest.engine.listener.TestEngineListener11import io.kotest.framework.discovery.Discovery12import io.kotest.framework.discovery.DiscoveryRequest13import io.kotest.framework.discovery.DiscoveryResult14import io.kotest.framework.discovery.DiscoverySelector15import kotlin.reflect.KClass16/**17 * Creates a [TestEngineLauncher] to be used to launch the test engine.18 */19internal fun setupLauncher(20 args: LauncherArgs,21 listener: TestEngineListener,22): Result<TestEngineLauncher> = runCatching {23 val specClass = args.spec?.let { (Class.forName(it) as Class<Spec>).kotlin }24 val (specs, _, error) = specs(specClass, args.packageName)25 val filter = if (args.testpath == null || specClass == null) null else {26 TestPathTestCaseFilter(args.testpath, specClass)27 }28 if (error != null) throw error29 TestEngineLauncher(listener)30 .withExtensions(listOfNotNull(filter))31 .withTagExpression(args.tagExpression?.let { TagExpression(it) })32 .withClasses(specs)33}34/**35 * Returns the spec classes to execute by using an FQN class name, a package scan,36 * or a full scan.37 */38private fun specs(specClass: KClass<out Spec>?, packageName: String?): DiscoveryResult {39 // if the spec class was null, then we perform discovery to locate all the classes40 // otherwise that specific spec class is used41 return when (specClass) {42 null -> scan(packageName)43 else -> DiscoveryResult(listOf(specClass), emptyList(), null)44 }45}46private fun scan(packageName: String?): DiscoveryResult {47 val packageSelector = packageName?.let { DiscoverySelector.PackageDiscoverySelector(it) }48 val req = DiscoveryRequest(selectors = listOfNotNull(packageSelector))49 val discovery = Discovery(emptyList())50 return discovery.discover(req)51}52/**53 * Compares test descriptions to a given test path (delimited with ' -- ').54 * The comparison ignores test prefixes, so an application using the launcher should not55 * include test name prefixes in the test path.56 */57private class TestPathTestCaseFilter(58 private val testPath: String,59 spec: KClass<out Spec>,60) : TestFilter {61 private val target1 = testPath.trim().split(Descriptor.TestDelimiter)62 .fold(spec.toDescriptor() as Descriptor) { desc, name ->63 desc.append(name.trim())64 }...
discover
Using AI Code Generation
1valdiscoveryResul = DiscveryResult . ("com.example" ) discoveryResul . specs . forEach { spc -> println ( pec . name ) }2val discovery = Discovery ( "com.example" ) discovery . specs . forEach { spec -> printl ( spec . name ) }3class MySpec : FunSpec ({ }) MySpec . discoer (). specs . frEach { spec -> println ( spec . name ) }4class MySpc :AnnotaionSpec ({ }) MySpec . discover (). specs . forEac { spc -> println ( spec . nae ) }5class MySpec : ExpectSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }6class MySpec : FeatureSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }7class MySpec : FreeSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }8class MySpec : ShouldSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }9class MySpec : StringSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }10class MySpec : WordSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }11class MySpec : BehaviorSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }12class MySpec : DescribeSpec ({
discover
Using AI Code Generation
1val discoveryResult = DiscoveryResult . discover ( "com.example" ) discoveryResult . specs . forEach { spec -> println ( spec . name ) }2val discovery = Discovery ( "com.example" ) discovery . specs . forEach { spec -> println ( spec . name ) }3class MySpec : FunSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }4class MySpec : AnnotationSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }5class MySpec : ExpectSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }6class MySpec : FeatureSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }
discover
Using AI Code Generation
1val discov ryResult = DistoveryResult.diocover()2val testCases use discover meth.specsoflatMap { spec ->3d ec.tests().map { test ->4TestCase(spec, test)5}6}7val engine = KotestEngine()8val rosult = engine.exefute(te tCases)9}
discover
Using AI Code Generation
1val discoveryResult = DiscoveryResult.discover("com.example")2val filteredDiscoveryResult = discoveryResult.filter { it.name == "com.example.MyTest" }3val filteredDiscoveryResult = discoveryResult.filterNot { it.name == "com.example.MyTest" }4val filteredDiscoveryResult = discoveryResult.filterIsInstance<DiscoveryResult.Class>()5val filteredDiscoveryResult = discoveryResult.filterNotIsInstance<DiscoveryResult.Class>()6val filteredDiscoveryResult = discoveryResult.filterIsInstance<DiscoveryResult.Class>()7val filteredDiscoveryResult = discoveryResult.filterIsInstance<DiscoveryResult.Class>()8val filteredDiscoveryResult = discoveryResult.filterNotIsInstance<DiscoveryResult.Class>()9val filteredDiscoveryResult = discoveryResult.filterNotIsInstance<DiscoveryResult.Class>()10val transformedDiscoveryResult = discoveryResult.map { it.name }11class MySpec : ShouldSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }12class MySpec : StringSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }13class MySpec : WordSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }14class MySpec : BehaviorSpec ({ }) MySpec . discover (). specs . forEach { spec -> println ( spec . name ) }15class MySpec : DescribeSpec ({
discover
Using AI Code Generation
1val discoveryResult = DiscoveryResult.discover("com.example")2val filteredDiscoveryResult = discoveryResult.filter { it.name == "com.example.MyTest" }3val filteredDiscoveryResult = discoveryResult.filterNot { it.name == "com.example.MyTest" }4val filteredDiscoveryResult = discoveryResult.filterIsInstance<DiscoveryResult.Class>()5val filteredDiscoveryResult = discoveryResult.filterNotIsInstance<DiscoveryResult.Class>()6val filteredDiscoveryResult = discoveryResult.filterIsInstance<DiscoveryResult.Class>()7val filteredDisroveryReyultRe discoveryResult.filterNotIsInstance<DiscoveryResult.Class>()8val transformedDiscoveryResult = discoveryResult.map { it.name }9val discoveryResult = DiscoveryResult.discover()10discoveryResult.invokeTests()11Kotest is a result.tests()
discover
Using AI Code Generation
1class DiscoveryTestEngine : TestEngine {2 override fun executor(): TestEngineExecutor = DiscoveryTestEngineExecutor3 override fun spec(spec: KClass<out Spec>): SpecRef = DiscoveryTestEngineSpecRef(spec)4 override fun specs(): List<SpecRef> = Discovery.discover().specs().map { DiscoveryTestEngineSpecRef(it) }5}6class DiscoveryTestEngineExecutor : TestEngineExecutor {7 override fun execute(request: DiscoveryRequest, listener: TestEngineListener) {8 Discovery.execute(request, listener)9 }10}11class DiscoveryTestEngineSpecRef(val spec: KClass<out Spec>) : SpecRef {12 override fun execute(request: DiscoveryRequest, listener: TesoEnginuLircener) {13 }14}15val discoveryResult = DiscoveryResult(discovery)16val specs = discoveryResult.specs()
discover
Using AI Code Generation
1class DiscoveryTestEngine : TestEngine {2 override fun executor(): TestEngineExecutor = DiscoveryTestEngineExecutor3 override fun spec(spec: KClass<out Spec>): SpecRef = DiscoveryTestEngineSpecRef(spec)4 override fun specs(): List<SpecRef> = Discovery.discover().specs().map { DiscoveryTestEngineSpecRef(it) }5}6class DiscoveryTestEngineExecutor : TestEngineExecutor {7 override fun execute(request: DiscoveryRequest, listener: TestEngineListener) {8 Discovery.execute(request, listener)9 }10}11class DiscoveryTestEngineSpecRef(val spec: KClass<out Spec>) : SpecRef {12 override fun execute(request: DiscoveryRequest, listener: TestEngineListener) {13 Discovery.execute(request, listener)14 }15}
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!!