aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/common/test/EnsureActiveTest.kt
blob: 716be629e8cae12b38f2b276ecc5f2c2898a5ffe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
 * 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.test.*

class EnsureActiveTest : 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<JobCancellationException> { job.ensureActive() }
        assertFailsWith<JobCancellationException> { scope.ensureActive() }
        assertFailsWith<JobCancellationException> { 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)
    }

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