Does Kotest provide a coroutine scope I should use...
# kotest
w
Does Kotest provide a coroutine scope I should use to launch a task that I want to run in the background while all tests in a Spec are being executed?
Currently, I'm launching a job in a
beforeSpec
using the
GlobalScope
, and cancelling that job in an
afterSpec
. Is there a cleaner way to do that without
GlobalScope
?
s
you can launch a corotuine directly inside a test
every test scope in kotest is a coroutine scope
w
Right, but I'm trying to launch a coroutine once before the first test to that the same background task is running for the whole spec. I don't seem to have a coroutine scope available in a
beforeSpec
block. Ideally, there would be a scope that ends after the last test ends, or after all the
afterSpec
blocks or something.
s
Ah i see what you mean
What you're doing is the right way then. There's no scope provided to those callbacks, you need to make your own.
w
OK, thanks for your advice.
o
actually, you could use
backgroundScope
(kotlinlang.org) kotest has it too via own
TestScope
impl. The only thing to be aware of is to understand the lifecycle of particular TestCope you gonna use – if you acquire
backgroundScope
from the
ContainerScope
it would have a lifecycle of the container, not a particular test, and probably this is not something you gonna want
or you could have something like this, but beware of the dispatcher (probably
UnconfinedTestDispatcherImpl
is what you want, but then you'll have to dance a bit with the single instance of
TestCoroutineScheduler
Copy code
fun Spec.SpecCancellableScope(dispatcher: CoroutineDispatcher = Dispatchers.Default) =
    CoroutineScope(Job() + dispatcher).also { scope ->
        val doCancel = { scope.cancel("Cleanup scope with test finishes") }
        when (isolationMode ?: AppKotestProjectConfig.isolationMode) {
            IsolationMode.SingleInstance -> {
                afterSpec { doCancel() }
            }

            IsolationMode.InstancePerLeaf, IsolationMode.InstancePerTest -> {
                afterTest { doCancel() }
            }
        }
    }
121 Views