@@ -5,14 +5,13 @@ import kotlin.coroutines.*
5
5
import kotlin.test.*
6
6
import kotlinx.coroutines.internal.*
7
7
8
- class CommonThreadContextElementTest : TestBase () {
8
+ class ThreadContextElementTest : TestBase () {
9
9
interface TestThreadContextElement : ThreadContextElement <Int > {
10
10
companion object Key : CoroutineContext.Key<TestThreadContextElement>
11
11
}
12
12
13
13
@Test
14
- fun updatesAndRestores () = runTest {
15
- expect(1 )
14
+ fun testUpdatesAndRestores () = runTest {
16
15
var updateCount = 0
17
16
var restoreCount = 0
18
17
val threadContextElement = object : TestThreadContextElement {
@@ -34,7 +33,6 @@ class CommonThreadContextElementTest : TestBase() {
34
33
}
35
34
assertEquals(1 , updateCount)
36
35
assertEquals(1 , restoreCount)
37
- finish(2 )
38
36
}
39
37
40
38
@Test
@@ -77,6 +75,42 @@ class CommonThreadContextElementTest : TestBase() {
77
75
job.join()
78
76
assertNull(threadContextElementThreadLocal.get())
79
77
}
78
+
79
+ @Test
80
+ fun testWithContextJobAccess () = runTest {
81
+ val captor = JobCaptor ()
82
+ val manuallyCaptured = ArrayList <Job >()
83
+ withContext(captor) {
84
+ manuallyCaptured + = coroutineContext.job
85
+ withContext(CoroutineName (" undispatched" )) {
86
+ manuallyCaptured + = coroutineContext.job
87
+ withContext(Dispatchers .Default ) {
88
+ manuallyCaptured + = coroutineContext.job
89
+ }
90
+ // Context restored, captured again
91
+ manuallyCaptured + = coroutineContext.job
92
+ }
93
+ // Context restored, captured again
94
+ manuallyCaptured + = coroutineContext.job
95
+ }
96
+ assertEquals(manuallyCaptured, captor.capturees)
97
+ }
98
+ }
99
+
100
+ private class JobCaptor () : ThreadContextElement<Unit> {
101
+
102
+ val capturees: MutableList <Job > = mutableListOf ()
103
+
104
+ companion object Key : CoroutineContext.Key<MyElement>
105
+
106
+ override val key: CoroutineContext .Key <* > get() = Key
107
+
108
+ override fun updateThreadContext (context : CoroutineContext ) {
109
+ capturees.add(context.job)
110
+ }
111
+
112
+ override fun restoreThreadContext (context : CoroutineContext , oldState : Unit ) {
113
+ }
80
114
}
81
115
82
116
internal class MyData
@@ -105,4 +139,3 @@ internal class MyElement(val data: MyData) : ThreadContextElement<MyData?> {
105
139
threadContextElementThreadLocal.set(oldState)
106
140
}
107
141
}
108
-
0 commit comments