aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/common/test/AbstractCoroutineTest.kt
blob: ce20837e251a44506bcae403d56e09aedd08519d (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * Copyright 2016-2018 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.*

@Suppress("DEPRECATION") // cancel(cause)
class AbstractCoroutineTest : TestBase() {
    @Test
    fun testNotifications() = runTest {
        expect(1)
        val coroutineContext = coroutineContext // workaround for KT-22984
        val coroutine = object : AbstractCoroutine<String>(coroutineContext, false) {
            override fun onStart() {
                expect(3)
            }

            override fun onCancelling(cause: Throwable?) {
                assertNull(cause)
                expect(5)
            }

            override fun onCompleted(value: String) {
                assertEquals("OK", value)
                expect(6)
            }

            override fun onCancelled(cause: Throwable, handled: Boolean) {
                expectUnreached()
            }
        }

        coroutine.invokeOnCompletion(onCancelling = true) {
            assertNull(it)
            expect(7)
        }

        coroutine.invokeOnCompletion {
            assertNull(it)
            expect(8)
        }
        expect(2)
        coroutine.start()
        expect(4)
        coroutine.resume("OK")
        finish(9)
    }

    @Test
    fun testNotificationsWithException() = runTest {
        expect(1)
        val coroutineContext = coroutineContext // workaround for KT-22984
        val coroutine = object : AbstractCoroutine<String>(coroutineContext + NonCancellable, false) {
            override fun onStart() {
                expect(3)
            }

            override fun onCancelling(cause: Throwable?) {
                assertTrue(cause is TestException1)
                expect(5)
            }

            override fun onCompleted(value: String) {
                expectUnreached()
            }

            override fun onCancelled(cause: Throwable, handled: Boolean) {
                assertTrue(cause is TestException1)
                expect(8)
            }
        }

        coroutine.invokeOnCompletion(onCancelling = true) {
            assertTrue(it is TestException1)
            expect(6)
        }

        coroutine.invokeOnCompletion {
            assertTrue(it is TestException1)
            expect(9)
        }

        expect(2)
        coroutine.start()
        expect(4)
        coroutine.cancelCoroutine(TestException1())
        expect(7)
        coroutine.resumeWithException(TestException2())
        finish(10)
    }
}