Vsevolod Tolstopyatov | 931587a | 2018-04-16 17:51:12 +0300 | [diff] [blame] | 1 | package kotlinx.coroutines.experimental |
| 2 | |
| 3 | import kotlin.coroutines.experimental.* |
| 4 | import kotlin.test.* |
| 5 | |
| 6 | class NonCancellableTest : TestBase() { |
| 7 | |
| 8 | @Test |
| 9 | fun testNonCancellable() = runTest { |
| 10 | expect(1) |
| 11 | val job = async(coroutineContext) { |
| 12 | withContext(NonCancellable) { |
| 13 | expect(2) |
| 14 | yield() |
| 15 | expect(4) |
| 16 | } |
| 17 | |
| 18 | expect(5) |
| 19 | yield() |
| 20 | expectUnreached() |
| 21 | } |
| 22 | |
| 23 | yield() |
| 24 | job.cancel() |
| 25 | expect(3) |
| 26 | assertTrue(job.isCancelled) |
| 27 | try { |
| 28 | job.await() |
| 29 | expectUnreached() |
| 30 | } catch (e: JobCancellationException) { |
| 31 | assertNull(e.cause) |
| 32 | finish(6) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | @Test |
| 37 | fun testNonCancellableWithException() = runTest { |
| 38 | expect(1) |
| 39 | val job = async(coroutineContext) { |
| 40 | withContext(NonCancellable) { |
| 41 | expect(2) |
| 42 | yield() |
| 43 | expect(4) |
| 44 | } |
| 45 | |
| 46 | expect(5) |
| 47 | yield() |
| 48 | expectUnreached() |
| 49 | } |
| 50 | |
| 51 | yield() |
| 52 | job.cancel(NumberFormatException()) |
| 53 | expect(3) |
| 54 | assertTrue(job.isCancelled) |
| 55 | try { |
| 56 | job.await() |
| 57 | expectUnreached() |
| 58 | } catch (e: JobCancellationException) { |
| 59 | assertTrue(e.cause is NumberFormatException) |
| 60 | finish(6) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | @Test |
| 65 | fun testNonCancellableFinally() = runTest { |
| 66 | expect(1) |
| 67 | val job = async(coroutineContext) { |
| 68 | try { |
| 69 | expect(2) |
| 70 | yield() |
| 71 | expectUnreached() |
| 72 | } finally { |
| 73 | withContext(NonCancellable) { |
| 74 | expect(4) |
| 75 | yield() |
| 76 | expect(5) |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | expectUnreached() |
| 81 | } |
| 82 | |
| 83 | yield() |
| 84 | job.cancel() |
| 85 | expect(3) |
| 86 | assertTrue(job.isCancelled) |
| 87 | |
| 88 | try { |
| 89 | job.await() |
| 90 | expectUnreached() |
| 91 | } catch (e: JobCancellationException) { |
| 92 | finish(6) |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | @Test |
| 97 | fun testNonCancellableTwice() = runTest { |
| 98 | expect(1) |
| 99 | val job = async(coroutineContext) { |
| 100 | withContext(NonCancellable) { |
| 101 | expect(2) |
| 102 | yield() |
| 103 | expect(4) |
| 104 | } |
| 105 | |
| 106 | withContext(NonCancellable) { |
| 107 | expect(5) |
| 108 | yield() |
| 109 | expect(6) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | yield() |
| 114 | job.cancel() |
| 115 | expect(3) |
| 116 | assertTrue(job.isCancelled) |
| 117 | try { |
| 118 | job.await() |
| 119 | expectUnreached() |
| 120 | } catch (e: JobCancellationException) { |
| 121 | assertNull(e.cause) |
| 122 | finish(7) |
| 123 | } |
| 124 | } |
| 125 | } |