|
5 | 5 | package kotlinx.coroutines.flow
|
6 | 6 |
|
7 | 7 | import kotlinx.coroutines.*
|
| 8 | +import kotlin.coroutines.* |
8 | 9 | import kotlin.test.*
|
9 | 10 |
|
10 | 11 | class CatchTest : TestBase() {
|
@@ -86,4 +87,62 @@ class CatchTest : TestBase() {
|
86 | 87 | job.cancelAndJoin()
|
87 | 88 | finish(3)
|
88 | 89 | }
|
| 90 | + |
| 91 | + @Test |
| 92 | + fun testCatchContext() = runTest { |
| 93 | + expect(1) |
| 94 | + val flow = flow { |
| 95 | + expect(2) |
| 96 | + emit("OK") |
| 97 | + expect(3) |
| 98 | + throw TestException() |
| 99 | + } |
| 100 | + val d0 = coroutineContext[ContinuationInterceptor] as CoroutineContext |
| 101 | + val d1 = wrapperDispatcher(coroutineContext) |
| 102 | + val d2 = wrapperDispatcher(coroutineContext) |
| 103 | + flow |
| 104 | + .catch { e -> |
| 105 | + expect(4) |
| 106 | + assertTrue(e is TestException) |
| 107 | + assertEquals("A", kotlin.coroutines.coroutineContext[CoroutineName]?.name) |
| 108 | + assertSame(d1, kotlin.coroutines.coroutineContext[ContinuationInterceptor] as CoroutineContext) |
| 109 | + throw e // rethrow downstream |
| 110 | + } |
| 111 | + .flowOn(CoroutineName("A")) |
| 112 | + .catch { e -> |
| 113 | + expect(5) |
| 114 | + assertTrue(e is TestException) |
| 115 | + assertEquals("B", kotlin.coroutines.coroutineContext[CoroutineName]?.name) |
| 116 | + assertSame(d1, kotlin.coroutines.coroutineContext[ContinuationInterceptor] as CoroutineContext) |
| 117 | + throw e // rethrow downstream |
| 118 | + } |
| 119 | + .flowOn(CoroutineName("B")) |
| 120 | + .catch { e -> |
| 121 | + expect(6) |
| 122 | + assertTrue(e is TestException) |
| 123 | + assertSame(d1, kotlin.coroutines.coroutineContext[ContinuationInterceptor] as CoroutineContext) |
| 124 | + throw e // rethrow downstream |
| 125 | + } |
| 126 | + .flowOn(d1) |
| 127 | + .catch { e -> |
| 128 | + expect(7) |
| 129 | + assertTrue(e is TestException) |
| 130 | + assertSame(d2, kotlin.coroutines.coroutineContext[ContinuationInterceptor] as CoroutineContext) |
| 131 | + throw e // rethrow downstream |
| 132 | + } |
| 133 | + .flowOn(d2) |
| 134 | + // flowOn with a different dispatcher introduces asynchrony so that all exceptions in the |
| 135 | + // upstream flows are handled before they go downstream |
| 136 | + .onEach { value -> |
| 137 | + expect(8) |
| 138 | + assertEquals("OK", value) |
| 139 | + } |
| 140 | + .catch { e -> |
| 141 | + expect(9) |
| 142 | + assertTrue(e is TestException) |
| 143 | + assertSame(d0, kotlin.coroutines.coroutineContext[ContinuationInterceptor] as CoroutineContext) |
| 144 | + } |
| 145 | + .collect() |
| 146 | + finish(10) |
| 147 | + } |
89 | 148 | }
|
0 commit comments