All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commonTest.JobExtensionsTest.kt Maven / Gradle / Ivy

There is a newer version: 1.9.0
Show newest version
/*
 * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
 */

package kotlinx.coroutines

import kotlin.coroutines.*
import kotlin.test.*

class JobExtensionsTest : TestBase() {

    private val job = Job()
    private val scope = CoroutineScope(job + CoroutineExceptionHandler { _, _ ->  })

    @Test
    fun testIsActive() = runTest {
        expect(1)
        scope.launch(Dispatchers.Unconfined) {
            ensureActive()
            coroutineContext.ensureActive()
            coroutineContext[Job]!!.ensureActive()
            expect(2)
            delay(Long.MAX_VALUE)
        }

        expect(3)
        job.ensureActive()
        scope.ensureActive()
        scope.coroutineContext.ensureActive()
        job.cancelAndJoin()
        finish(4)
    }

    @Test
    fun testIsCompleted() = runTest {
        expect(1)
        scope.launch(Dispatchers.Unconfined) {
            ensureActive()
            coroutineContext.ensureActive()
            coroutineContext[Job]!!.ensureActive()
            expect(2)
        }

        expect(3)
        job.complete()
        job.join()
        assertFailsWith { job.ensureActive() }
        assertFailsWith { scope.ensureActive() }
        assertFailsWith { scope.coroutineContext.ensureActive() }
        finish(4)
    }


    @Test
    fun testIsCancelled() = runTest {
        expect(1)
        scope.launch(Dispatchers.Unconfined) {
            ensureActive()
            coroutineContext.ensureActive()
            coroutineContext[Job]!!.ensureActive()
            expect(2)
            throw TestException()
        }

        expect(3)
        checkException { job.ensureActive() }
        checkException { scope.ensureActive() }
        checkException { scope.coroutineContext.ensureActive() }
        finish(4)
    }

    @Test
    fun testEnsureActiveWithEmptyContext() = runTest {
        withEmptyContext {
            ensureActive() // should not do anything
        }
    }

    private inline fun checkException(block: () -> Unit) {
        val result = runCatching(block)
        val exception = result.exceptionOrNull() ?: fail()
        assertTrue(exception is JobCancellationException)
        assertTrue(exception.cause is TestException)
    }

    @Test
    fun testJobExtension() = runTest {
        assertSame(coroutineContext[Job]!!, coroutineContext.job)
        assertSame(NonCancellable, NonCancellable.job)
        assertSame(job, job.job)
        assertFailsWith { EmptyCoroutineContext.job }
        assertFailsWith { Dispatchers.Default.job }
        assertFailsWith { (Dispatchers.Default + CoroutineName("")).job }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy