Best Kotest code snippet using io.kotest.engine.concurrency.DefaultCoroutineDispatcherFactory.defaultCoroutineDispatcherFactory
SpecExecutor.kt
Source:SpecExecutor.kt
...44 *45 */46@ExperimentalKotest47class SpecExecutor(48 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,49 private val context: EngineContext,50) {51 private val logger = Logger(SpecExecutorDelegate::class)52 private val extensions = SpecExtensions(context.configuration.registry)53 private val listener = context.listener54 suspend fun execute(ref: SpecRef) {55 logger.log { Pair(ref.kclass.bestName(), "Received $ref") }56 referenceInterceptors(ref)57 }58 suspend fun execute(kclass: KClass<out Spec>) {59 execute(SpecRef.Reference(kclass))60 }61 private suspend fun referenceInterceptors(ref: SpecRef) {62 val interceptors = listOfNotNull(63 if (platform == Platform.JVM) EnabledIfSpecInterceptor(listener, context.configuration.registry) else null,64 IgnoredSpecInterceptor(listener, context.configuration.registry),65 SpecFilterInterceptor(listener, context.configuration.registry),66 SystemPropertySpecFilterInterceptor(listener, context.configuration.registry),67 TagsExcludedSpecInterceptor(listener, context.configuration),68 if (platform == Platform.JVM) RequiresTagSpecInterceptor(listener, context.configuration, context.configuration.registry) else null,69 SpecRefExtensionInterceptor(context.configuration.registry),70 SpecStartedInterceptor(listener),71 SpecFinishedInterceptor(listener),72 if (platform == Platform.JVM) ApplyExtensionsInterceptor(context.configuration.registry) else null,73 PrepareSpecInterceptor(context.configuration.registry),74 FinalizeSpecInterceptor(context.configuration.registry),75 )76 val innerExecute: suspend (SpecRef) -> Result<Map<TestCase, TestResult>> = {77 createInstance(ref).flatMap { specInterceptors(it) }78 }79 logger.log { Pair(ref.kclass.bestName(), "Executing ${interceptors.size} reference interceptors") }80 interceptors.foldRight(innerExecute) { ext: SpecRefInterceptor, fn: suspend (SpecRef) -> Result<Map<TestCase, TestResult>> ->81 { ref -> ext.intercept(ref, fn) }82 }.invoke(ref)83 }84 private suspend fun specInterceptors(spec: Spec): Result<Map<TestCase, TestResult>> {85 val interceptors = listOfNotNull(86 if (platform == Platform.JS) IgnoreNestedSpecStylesInterceptor(listener, context.configuration.registry) else null,87 ProjectContextInterceptor(context.toProjectContext()),88 SpecExtensionInterceptor(context.configuration.registry),89 ConfigurationInContextInterceptor(context.configuration),90 )91 val initial: suspend (Spec) -> Result<Map<TestCase, TestResult>> = {92 try {93 val delegate = createSpecExecutorDelegate(listener, defaultCoroutineDispatcherFactory, context.configuration)94 logger.log { Pair(spec::class.bestName(), "delegate=$delegate") }95 Result.success(delegate.execute(spec))96 } catch (t: Throwable) {97 logger.log { Pair(spec::class.bestName(), "Error executing spec $t") }98 Result.failure(t)99 }100 }101 logger.log { Pair(spec::class.bestName(), "Executing ${interceptors.size} spec interceptors") }102 return interceptors.foldRight(initial) { ext, fn ->103 { spec -> ext.intercept(spec, fn) }104 }.invoke(spec)105 }106 /**107 * Creates an instance of the given [SpecRef], notifies users of the instantiation event108 * or instantiation failure, and returns a Result with the error or spec.109 *110 * After this method is called the spec is sealed.111 */112 private suspend fun createInstance(ref: SpecRef): Result<Spec> =113 ref.instance(context.configuration.registry)114 .onFailure { extensions.specInstantiationError(ref.kclass, it) }115 .flatMap { spec -> extensions.specInstantiated(spec).map { spec } }116 .onSuccess { if (it is DslDrivenSpec) it.seal() }117}118interface SpecExecutorDelegate {119 suspend fun execute(spec: Spec): Map<TestCase, TestResult>120}121@ExperimentalKotest122internal expect fun createSpecExecutorDelegate(123 listener: TestEngineListener,124 defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,125 configuration: ProjectConfiguration,126): SpecExecutorDelegate...
SingleInstanceSpecRunner.kt
Source:SingleInstanceSpecRunner.kt
...29@ExperimentalKotest30internal class SingleInstanceSpecRunner(31 listener: TestEngineListener,32 scheduler: TestScheduler,33 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,34 private val configuration: ProjectConfiguration,35) : SpecRunner(listener, scheduler, configuration) {36 private val results = ConcurrentHashMap<TestCase, TestResult>()37 private val extensions = SpecExtensions(configuration.registry)38 private val logger = Logger(SingleInstanceSpecRunner::class)39 override suspend fun execute(spec: Spec): Result<Map<TestCase, TestResult>> {40 logger.log { Pair(spec::class.bestName(), "executing spec $spec") }41 suspend fun interceptAndRun(context: CoroutineContext) = runCatching {42 val rootTests = materializer.materialize(spec)43 logger.log { Pair(spec::class.bestName(), "Materialized root tests: ${rootTests.size}") }44 launch(spec) {45 logger.log { Pair(it.name.testName, "Executing test $it") }46 runTest(it, context, null)47 }48 }49 try {50 return coroutineScope {51 extensions.beforeSpec(spec)52 .flatMap { interceptAndRun(coroutineContext) }53 .flatMap { SpecExtensions(configuration.registry).afterSpec(spec) }54 .map { results }55 }56 } catch (e: Exception) {57 e.printStackTrace()58 throw e59 }60 }61 /**62 * A [TestScope] that runs discovered tests as soon as they are registered in the same spec instance.63 *64 * This implementation tracks fail fast if configured via TestCase config or globally.65 */66 inner class SingleInstanceTestScope(67 override val testCase: TestCase,68 override val coroutineContext: CoroutineContext,69 private val parentScope: SingleInstanceTestScope?,70 ) : TestScope {71 // set to true if we failed fast and should ignore further tests72 private var skipRemaining = false73 // in the single instance runner we execute each nested test as soon as they are registered74 override suspend fun registerTestCase(nested: NestedTest) {75 logger.log { Pair(testCase.name.testName, "Nested test case discovered '${nested}") }76 val nestedTestCase = Materializer(configuration).materialize(nested, testCase)77 if (skipRemaining) {78 logger.log { Pair(testCase.name.testName, "Skipping test due to fail fast") }79 listener.testIgnored(nestedTestCase, "Skipping test due to fail fast")80 } else {81 // if running this nested test results in an error, we won't launch anymore nested tests82 val result = runTest(nestedTestCase, coroutineContext, this@SingleInstanceTestScope)83 if (result.isErrorOrFailure) {84 if (testCase.config.failfast || configuration.projectWideFailFast) {85 logger.log { Pair(testCase.name.testName, "Test failed - setting skipRemaining = true") }86 skipRemaining = true87 parentScope?.skipRemaining = true88 }89 }90 }91 }92 }93 private suspend fun runTest(94 testCase: TestCase,95 coroutineContext: CoroutineContext,96 parentScope: SingleInstanceTestScope?,97 ): TestResult {98 val testExecutor = TestCaseExecutor(99 TestCaseExecutionListenerToTestEngineListenerAdapter(listener),100 defaultCoroutineDispatcherFactory,101 configuration,102 )103 val scope = DuplicateNameHandlingTestScope(104 configuration.duplicateTestNameMode,105 SingleInstanceTestScope(testCase, coroutineContext, parentScope)106 )107 val result = testExecutor.execute(testCase, scope)108 results[testCase] = result109 return result110 }111}...
TestCaseExecutor.kt
Source:TestCaseExecutor.kt
...38 */39@OptIn(ExperimentalKotest::class)40class TestCaseExecutor(41 private val listener: TestCaseExecutionListener,42 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory = NoopCoroutineDispatcherFactory,43 private val configuration: ProjectConfiguration,44) {45 private val logger = Logger(TestCaseExecutor::class)46 suspend fun execute(testCase: TestCase, testScope: TestScope): TestResult {47 val timeMark = TimeSource.Monotonic.markNow()48 val interceptors = listOfNotNull(49 TestPathContextInterceptor,50 TestFinishedInterceptor(listener),51 InvocationCountCheckInterceptor,52 SupervisorScopeInterceptor,53 if (platform == Platform.JVM) coroutineDispatcherFactoryInterceptor(defaultCoroutineDispatcherFactory) else null,54 if (platform == Platform.JVM) coroutineErrorCollectorInterceptor() else null,55 TestCaseExtensionInterceptor(configuration.registry),56 EnabledCheckInterceptor(configuration),57 LifecycleInterceptor(listener, timeMark, configuration.registry),58 AssertionModeInterceptor,59 SoftAssertInterceptor(),60 CoroutineLoggingInterceptor(configuration),61 if (platform == Platform.JVM) blockedThreadTimeoutInterceptor(configuration, timeMark) else null,62 TimeoutInterceptor(timeMark),63 TestInvocationInterceptor(configuration.registry, timeMark),64 InvocationTimeoutInterceptor,65 if (platform == Platform.JVM && testCase.config.testCoroutineDispatcher) TestDispatcherInterceptor() else null,66 if (platform == Platform.JVM && testCase.config.coroutineTestScope) TestCoroutineInterceptor() else null,67 CoroutineDebugProbeInterceptor,...
createSpecExecutorDelegate.kt
Source:createSpecExecutorDelegate.kt
...18import kotlin.math.max19@ExperimentalKotest20internal actual fun createSpecExecutorDelegate(21 listener: TestEngineListener,22 defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory,23 configuration: ProjectConfiguration,24): SpecExecutorDelegate = JvmSpecExecutorDelegate(listener, defaultCoroutineDispatcherFactory, configuration)25@ExperimentalKotest26class JvmSpecExecutorDelegate(27 private val listener: TestEngineListener,28 private val dispatcherFactory: CoroutineDispatcherFactory,29 private val configuration: ProjectConfiguration,30) : SpecExecutorDelegate {31 private val logger = Logger(JvmSpecExecutorDelegate::class)32 private fun Spec.resolvedIsolationMode() =33 this.isolationMode() ?: this.isolationMode ?: configuration.isolationMode34 override suspend fun execute(spec: Spec): Map<TestCase, TestResult> {35 val scheduler = when (val concurrentTests = spec.resolvedConcurrentTests(configuration.concurrentTests)) {36 ProjectConfiguration.Sequential -> SequentialTestScheduler37 else -> ConcurrentTestScheduler(max(1, concurrentTests))38 }...
ConcurrentTestSuiteScheduler.kt
Source:ConcurrentTestSuiteScheduler.kt
...3import io.kotest.core.annotation.DoNotParallelize4import io.kotest.core.annotation.Isolate5import io.kotest.core.project.TestSuite6import io.kotest.core.spec.SpecRef7import io.kotest.engine.concurrency.defaultCoroutineDispatcherFactory8import io.kotest.engine.concurrency.isIsolate9import io.kotest.engine.interceptors.EngineContext10import io.kotest.engine.listener.CollectingTestEngineListener11import io.kotest.engine.spec.SpecExecutor12import io.kotest.mpp.Logger13import io.kotest.mpp.bestName14import kotlinx.coroutines.coroutineScope15import kotlinx.coroutines.launch16import kotlinx.coroutines.sync.Semaphore17import kotlinx.coroutines.sync.withPermit18/**19 * A [TestSuiteScheduler] that schedules specs concurrently, up to a provided [maxConcurrent] value.20 * If the value is 1 then this scheduler will execute specs strictly sequentially.21 *22 * Additionally, on JVM targets, it will recognize the [Isolate] and [DoNotParallelize]23 * annotations to ensure those specs are never scheduled concurrently.24 *25 * @param maxConcurrent The maximum number of concurrent coroutines.26 */27@ExperimentalKotest28internal class ConcurrentTestSuiteScheduler(29 private val maxConcurrent: Int,30 private val context: EngineContext,31) : TestSuiteScheduler {32 private val logger = Logger(ConcurrentTestSuiteScheduler::class)33 override suspend fun schedule(suite: TestSuite): EngineResult {34 logger.log { Pair(null, "Launching ${suite.specs.size} specs") }35 val (sequential, concurrent) = suite.specs.partition { it.kclass.isIsolate() }36 logger.log { Pair(null, "Split on isIsolate: ${sequential.size} sequential ${concurrent.size} concurrent") }37 schedule(concurrent, maxConcurrent)38 logger.log { Pair(null, "Concurrent specs have completed") }39 schedule(sequential, 1)40 logger.log { Pair(null, "Sequential specs have completed") }41 return EngineResult(emptyList())42 }43 private suspend fun schedule(44 specs: List<SpecRef>,45 concurrency: Int,46 ) = coroutineScope { // we don't want this function to return until all specs are completed47 val coroutineDispatcherFactory = defaultCoroutineDispatcherFactory(context.configuration)48 val semaphore = Semaphore(concurrency)49 val collector = CollectingTestEngineListener()50 specs.forEach { ref ->51 logger.log { Pair(ref.kclass.bestName(), "Scheduling coroutine") }52 launch {53 semaphore.withPermit {54 logger.log { Pair(ref.kclass.bestName(), "Acquired permit") }55 if (context.configuration.projectWideFailFast && collector.errors) {56 context.listener.specIgnored(ref.kclass, null)57 } else {58 try {59 val executor = SpecExecutor(coroutineDispatcherFactory, context.mergeListener(collector))60 logger.log { Pair(ref.kclass.bestName(), "Executing ref") }61 executor.execute(ref)...
coroutineDispatcherFactoryInterceptor.kt
Source:coroutineDispatcherFactoryInterceptor.kt
...11import kotlinx.coroutines.test.TestDispatcher12import kotlin.coroutines.coroutineContext13@ExperimentalStdlibApi14internal actual fun coroutineDispatcherFactoryInterceptor(15 defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory16): TestExecutionInterceptor = CoroutineDispatcherFactoryInterceptor(defaultCoroutineDispatcherFactory)17/**18 * Switches execution onto a dispatcher provided by a [CoroutineDispatcherFactory].19 *20 * If the coroutine is an instance of [TestDispatcher] then the coroutine will not be changed.21 */22@ExperimentalStdlibApi23internal class CoroutineDispatcherFactoryInterceptor(24 private val defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory25) : TestExecutionInterceptor {26 private val logger = Logger(CoroutineDispatcherFactoryInterceptor::class)27 override suspend fun intercept(28 testCase: TestCase,29 scope: TestScope,30 test: suspend (TestCase, TestScope) -> TestResult31 ): TestResult {32 val currentDispatcher = coroutineContext[CoroutineDispatcher]33 // we don't override if we've set a test dispatcher on this already34 return if (currentDispatcher is TestDispatcher) {35 test(testCase, scope)36 } else {37 val userFactory = testCase.spec.coroutineDispatcherFactory ?: testCase.spec.coroutineDispatcherFactory()38 val threads = testCase.spec.threads ?: testCase.spec.threads() ?: 139 logger.log { Pair(testCase.name.testName, "userFactory=$userFactory; threads=$threads") }40 val f = when {41 userFactory != null -> userFactory42 threads > 1 -> FixedThreadCoroutineDispatcherFactory(threads, false)43 else -> defaultCoroutineDispatcherFactory44 }45 logger.log { Pair(testCase.name.testName, "Switching dispatcher using factory $f") }46 f.withDispatcher(testCase) {47 test(testCase, scope.withCoroutineContext(coroutineContext))48 }49 }50 }51}...
interceptors.kt
Source:interceptors.kt
...3import io.kotest.core.concurrency.CoroutineDispatcherFactory4import io.kotest.core.config.ProjectConfiguration5import kotlin.time.TimeMark6internal actual fun coroutineDispatcherFactoryInterceptor(7 defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory8): TestExecutionInterceptor = error("Unsupported on $platform")9internal actual fun blockedThreadTimeoutInterceptor(10 configuration: ProjectConfiguration,11 start: TimeMark,12): TestExecutionInterceptor = error("Unsupported on $platform")13internal actual fun coroutineErrorCollectorInterceptor(): TestExecutionInterceptor =14 error("Unsupported on $platform")...
DefaultCoroutineDispatcherFactory.kt
Source:DefaultCoroutineDispatcherFactory.kt
1package io.kotest.engine.concurrency2import io.kotest.core.concurrency.CoroutineDispatcherFactory3import io.kotest.core.config.ProjectConfiguration4internal actual fun defaultCoroutineDispatcherFactory(configuration: ProjectConfiguration): CoroutineDispatcherFactory =5 NoopCoroutineDispatcherFactory...
defaultCoroutineDispatcherFactory
Using AI Code Generation
1import io.kotest.core.spec.style.FunSpec2import io.kotest.matchers.shouldBe3import kotlinx.coroutines.delay4import kotlinx.coroutines.launch5import kotlinx.coroutines.runBlocking6class FunSpecTest : FunSpec({7 test("test1") {8 runBlocking {9 launch {10 delay(1000)11 println("test1")12 }13 launch {14 delay(1000)15 println("test1")16 }17 }18 }19 test("test2") {20 runBlocking {21 launch {22 delay(1000)23 println("test2")24 }25 launch {26 delay(1000)27 println("test2")28 }29 }30 }31})32import io.kotest.core.spec.style.FunSpec33import io.kotest.matchers.shouldBe34import kotlinx.coroutines.delay35import kotlinx.coroutines.launch36import kotlinx.coroutines.runBlocking37import java.util.concurrent.Executors38class FunSpecTest : FunSpec({39 test("test1") {40 runBlocking {41 launch {42 delay(1000)43 println("test1")44 }45 launch {46 delay(1000)47 println("test1")48 }49 }50 }51 test("test2") {52 runBlocking {53 launch {54 delay(1000)55 println("test2")56 }57 launch {58 delay(1000)59 println("test2")60 }61 }62 }63}, coroutineDispatcherFactory = { Executors.newFixedThreadPool(2).asCoroutineDispatcher() })64import io.kotest.core.spec.style.FunSpec65import io.kotest.matchers.shouldBe66import kotlinx.coroutines.delay67import kotlinx.coroutines.launch68import kotlinx.coroutines.runBlocking69import java.util.concurrent.Executors70class FunSpecTest : FunSpec({71 test("test1") {72 runBlocking {73 launch {74 delay(1000)75 println("test1")76 }77 launch {78 delay(1000)79 println("test1")80 }81 }82 }83 test("test2") {84 runBlocking {85 launch {86 delay(1000)87 println("test2")88 }89 launch {90 delay(1000
defaultCoroutineDispatcherFactory
Using AI Code Generation
1defaultCoroutineDispatcherFactory()2defaultCoroutineDispatcherFactory(CustomCoroutineDispatcherFactory())3defaultCoroutineDispatcherFactory { }4defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> }5defaultCoroutineDispatcherFactory { coroutineName -> }6defaultCoroutineDispatcherFactory { coroutineContext -> }7defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> coroutineContext }8defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }9defaultCoroutineDispatcherFactory { coroutineContext -> coroutineContext }10defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> Dispatchers.Default }11defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }12defaultCoroutineDispatcherFactory { coroutineContext -> coroutineContext }13defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> Dispatchers.Default }14defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }15defaultCoroutineDispatcherFactory { coroutineContext -> coroutineContext }16defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> Dispatchers.Default }17defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }18defaultCoroutineDispatcherFactory { coroutineContext -> coroutineContext }19defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> Dispatchers.Default }20defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }21defaultCoroutineDispatcherFactory { coroutineContext -> coroutineContext }22defaultCoroutineDispatcherFactory { coroutineContext, coroutineName -> Dispatchers.Default }23defaultCoroutineDispatcherFactory { coroutineName -> Dispatchers.Default }
defaultCoroutineDispatcherFactory
Using AI Code Generation
1val dispatcher = DefaultCoroutineDispatcherFactory().defaultCoroutineDispatcherFactory()2dispatcher.close()3dispatcher.close()4dispatcher.close()5val dispatcher = TestCoroutineDispatcher()6dispatcher.cleanupTestCoroutines()7dispatcher.cleanupTestCoroutines()8dispatcher.cleanupTestCoroutines()9val dispatcher = TestCoroutineDispatcher()10dispatcher.cleanupTestCoroutines()11dispatcher.cleanupTestCoroutines()12dispatcher.cleanupTestCoroutines()13val dispatcher = TestCoroutineDispatcher()14dispatcher.cleanupTestCoroutines()15dispatcher.cleanupTestCoroutines()16dispatcher.cleanupTestCoroutines()17val dispatcher = TestCoroutineDispatcher()18dispatcher.cleanupTestCoroutines()19dispatcher.cleanupTestCoroutines()20dispatcher.cleanupTestCoroutines()21val dispatcher = TestCoroutineDispatcher()22dispatcher.cleanupTestCoroutines()23dispatcher.cleanupTestCoroutines()24dispatcher.cleanupTestCoroutines()25val dispatcher = TestCoroutineDispatcher()26dispatcher.cleanupTestCoroutines()27dispatcher.cleanupTestCoroutines()28dispatcher.cleanupTestCoroutines()29val dispatcher = TestCoroutineDispatcher()30dispatcher.cleanupTestCoroutines()31dispatcher.cleanupTestCoroutines()32dispatcher.cleanupTestCoroutines()33val dispatcher = TestCoroutineDispatcher()34dispatcher.cleanupTestCoroutines()35dispatcher.cleanupTestCoroutines()36dispatcher.cleanupTestCoroutines()37val dispatcher = TestCoroutineDispatcher()38dispatcher.cleanupTestCoroutines()39dispatcher.cleanupTestCoroutines()40dispatcher.cleanupTestCoroutines()41val dispatcher = TestCoroutineDispatcher()42dispatcher.cleanupTestCoroutines()43dispatcher.cleanupTestCoroutines()44dispatcher.cleanupTestCoroutines()45val dispatcher = TestCoroutineDispatcher()46dispatcher.cleanupTestCoroutines()47dispatcher.cleanupTestCoroutines()48dispatcher.cleanupTestCoroutines()49val dispatcher = TestCoroutineDispatcher()50dispatcher.cleanupTestCoroutines()51dispatcher.cleanupTestCoroutines()52dispatcher.cleanupTestCoroutines()53val dispatcher = TestCoroutineDispatcher()
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!!