Skip to content

Commit a563608

Browse files
elizarovqwwdfsad
authored andcommitted
Added a test that ensures proper context in catch/flowOn combinations
Amazingly, it works like a charm, but a test is needed to make sure it will not get broken in the future.
1 parent bb97ffb commit a563608

File tree

1 file changed

+59
-0
lines changed
  • kotlinx-coroutines-core/common/test/flow/operators

1 file changed

+59
-0
lines changed

kotlinx-coroutines-core/common/test/flow/operators/CatchTest.kt

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
package kotlinx.coroutines.flow
66

77
import kotlinx.coroutines.*
8+
import kotlin.coroutines.*
89
import kotlin.test.*
910

1011
class CatchTest : TestBase() {
@@ -86,4 +87,62 @@ class CatchTest : TestBase() {
8687
job.cancelAndJoin()
8788
finish(3)
8889
}
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+
}
89148
}

0 commit comments

Comments
 (0)