blob: 9f785924f1cb2e6f952e0baa8789d022a94142da [file] [log] [blame]
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03001/*
2 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +03005package kotlinx.coroutines.experimental
6
7import kotlin.test.*
8
9class CancellableContinuationHandlersTest : TestBase() {
10
11 @Test
12 fun testDoubleSubscription() = runTest({ it is IllegalStateException }) {
13 suspendCancellableCoroutine<Unit> { c ->
14 c.invokeOnCancellation { finish(1) }
15 c.invokeOnCancellation { expectUnreached() }
16 }
17 }
18
19 @Test
20 fun testDoubleSubscriptionAfterCompletion() = runTest {
21 suspendCancellableCoroutine<Unit> { c ->
22 c.resume(Unit)
23 // Nothing happened
24 c.invokeOnCancellation { expectUnreached() }
25 c.invokeOnCancellation { expectUnreached() }
26 }
27 }
28
29 @Test
30 fun testDoubleSubscriptionAfterCancellation() = runTest {
31 try {
32 suspendCancellableCoroutine<Unit> { c ->
33 c.cancel()
34 c.invokeOnCancellation {
Roman Elizarov6d9f40f2018-04-28 14:44:02 +030035 assertTrue(it is CancellationException)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030036 expect(1)
37 }
38 c.invokeOnCancellation {
Roman Elizarov6d9f40f2018-04-28 14:44:02 +030039 assertTrue(it is CancellationException)
Vsevolod Tolstopyatovf3a50132018-04-16 19:41:20 +030040 expect(2)
41 }
42 }
43 } catch (e: CancellationException) {
44 finish(3)
45 }
46 }
47
48 @Test
49 fun testDoubleSubscriptionAfterCancellationWithCause() = runTest {
50 try {
51 suspendCancellableCoroutine<Unit> { c ->
52 c.cancel(AssertionError())
53 c.invokeOnCancellation {
54 require(it is AssertionError)
55 expect(1)
56 }
57 c.invokeOnCancellation {
58 require(it is AssertionError)
59 expect(2)
60 }
61 }
62 } catch (e: AssertionError) {
63 finish(3)
64 }
65 }
66
67 @Test
68 fun testDoubleSubscriptionMixed() = runTest {
69 try {
70 suspendCancellableCoroutine<Unit> { c ->
71 c.invokeOnCancellation {
72 require(it is IndexOutOfBoundsException)
73 expect(1)
74 }
75
76 c.cancel(IndexOutOfBoundsException())
77 c.invokeOnCancellation {
78 require(it is IndexOutOfBoundsException)
79 expect(2)
80 }
81 }
82 } catch (e: IndexOutOfBoundsException) {
83 finish(3)
84 }
85 }
86
87 @Test
88 fun testExceptionInHandler() = runTest({it is CancellationException}, listOf({e -> e is CompletionHandlerException})) {
89 suspendCancellableCoroutine<Unit> { c ->
90 c.invokeOnCancellation { throw AssertionError() }
91 c.cancel()
92 }
93 }
94}