1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.slf4j
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import org.slf4j.*
import kotlin.coroutines.*
import kotlin.test.*
class MDCContextTest : TestBase() {
@Before
fun setUp() {
MDC.clear()
}
@After
fun tearDown() {
MDC.clear()
}
@Test
fun testContextIsNotPassedByDefaultBetweenCoroutines() = runTest {
expect(1)
MDC.put("myKey", "myValue")
// Standalone launch
GlobalScope.launch {
assertEquals(null, MDC.get("myKey"))
expect(2)
}.join()
finish(3)
}
@Test
fun testContextCanBePassedBetweenCoroutines() = runTest {
expect(1)
MDC.put("myKey", "myValue")
// Scoped launch with MDCContext element
launch(MDCContext()) {
assertEquals("myValue", MDC.get("myKey"))
expect(2)
}.join()
finish(3)
}
@Test
fun testContextInheritance() = runTest {
expect(1)
MDC.put("myKey", "myValue")
withContext(MDCContext()) {
MDC.put("myKey", "myValue2")
// Scoped launch with inherited MDContext element
launch(Dispatchers.Default) {
assertEquals("myValue", MDC.get("myKey"))
expect(2)
}.join()
finish(3)
}
assertEquals("myValue", MDC.get("myKey"))
}
@Test
fun testContextPassedWhileOnMainThread() {
MDC.put("myKey", "myValue")
// No MDCContext element
runBlocking {
assertEquals("myValue", MDC.get("myKey"))
}
}
@Test
fun testContextCanBePassedWhileOnMainThread() {
MDC.put("myKey", "myValue")
runBlocking(MDCContext()) {
assertEquals("myValue", MDC.get("myKey"))
}
}
@Test
fun testContextNeededWithOtherContext() {
MDC.put("myKey", "myValue")
runBlocking(MDCContext()) {
assertEquals("myValue", MDC.get("myKey"))
}
}
@Test
fun testContextMayBeEmpty() {
runBlocking(MDCContext()) {
assertEquals(null, MDC.get("myKey"))
}
}
@Test
fun testContextWithContext() = runTest {
MDC.put("myKey", "myValue")
val mainDispatcher = kotlin.coroutines.coroutineContext[ContinuationInterceptor]!!
withContext(Dispatchers.Default + MDCContext()) {
assertEquals("myValue", MDC.get("myKey"))
withContext(mainDispatcher) {
assertEquals("myValue", MDC.get("myKey"))
}
}
}
}
|