1
+ package kotlinx.coroutines
2
+
3
+ import kotlinx.coroutines.flow.*
4
+ import kotlinx.coroutines.internal.intellij.*
5
+ import kotlinx.coroutines.testing.*
6
+ import org.junit.Assert.*
7
+ import org.junit.Test
8
+ import kotlin.coroutines.*
9
+
10
+ class ExposedThreadContextTest : TestBase () {
11
+ @Test
12
+ fun runBlocking () = runBlocking {
13
+ assertContextEqualUnderResumption()
14
+ }
15
+
16
+ class C : AbstractCoroutineContextElement (C ) {
17
+ companion object Key : CoroutineContext.Key<C>
18
+ }
19
+
20
+ @Test
21
+ fun withContext () = runBlocking {
22
+ val element = C ()
23
+ withContext(element) {
24
+ // the context changed
25
+ assertContextEqualUnderResumption()
26
+ withContext(element) {
27
+ // checking fast path -- the context effectively does not change
28
+ assertContextEqualUnderResumption()
29
+ }
30
+ }
31
+ }
32
+
33
+ @Test
34
+ fun launch () = runBlocking {
35
+ for (i in 0 .. 10 ) {
36
+ launch {
37
+ assertContextEqualUnderResumption()
38
+ }
39
+ }
40
+ }
41
+
42
+ @Test
43
+ fun coroutineScope () = runBlocking {
44
+ coroutineScope {
45
+ assertContextEqualUnderResumption()
46
+ coroutineScope {
47
+ assertContextEqualUnderResumption()
48
+ }
49
+ }
50
+ }
51
+
52
+ @Test
53
+ fun supervisorScope () = runBlocking {
54
+ supervisorScope {
55
+ assertContextEqualUnderResumption()
56
+ supervisorScope {
57
+ assertContextEqualUnderResumption()
58
+ }
59
+ }
60
+ }
61
+
62
+ @Test
63
+ fun testFlow () = runBlocking {
64
+ coroutineScope {
65
+ val flowVar = flow {
66
+ repeat(10 ) {
67
+ // Flow has encapsulated context
68
+ assertContextEqualUnderResumption()
69
+ emit(it)
70
+ }
71
+ }.flowOn(C ())
72
+ flowVar.collect {
73
+ assertContextEqualUnderResumption()
74
+ }
75
+ }
76
+ }
77
+
78
+ private suspend fun assertContextEqualUnderResumption () {
79
+ // thread context should survive dispatches
80
+ assertContextsEqual()
81
+ yield ()
82
+ assertContextsEqual()
83
+ }
84
+
85
+
86
+ private suspend fun assertContextsEqual () {
87
+ val coroutineContext = currentCoroutineContext()
88
+ val threadContext = IntellijCoroutines .currentThreadCoroutineContext()
89
+ assertEquals(coroutineContext, threadContext)
90
+ }
91
+ }
0 commit comments