forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestDispatchersTest.kt
71 lines (58 loc) · 1.89 KB
/
TestDispatchersTest.kt
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
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
import kotlinx.atomicfu.*
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.coroutines.*
import kotlin.test.*
class TestDispatchersTest {
private val actionIndex = atomic(0)
private val finished = atomic(false)
private fun expect(index: Int) {
val wasIndex = actionIndex.incrementAndGet()
check(index == wasIndex) { "Expecting action index $index but it is actually $wasIndex" }
}
private fun finish(index: Int) {
expect(index)
check(!finished.getAndSet(true)) { "Should call 'finish(...)' at most once" }
}
@BeforeTest
fun setUp() {
Dispatchers.resetMain()
}
@Test
fun testSelfSet() {
assertFailsWith<IllegalArgumentException> { Dispatchers.setMain(Dispatchers.Main) }
}
@Test
fun testImmediateDispatcher() = runBlockingTest {
Dispatchers.setMain(ImmediateDispatcher())
expect(1)
withContext(Dispatchers.Main) {
expect(3)
}
Dispatchers.setMain(RegularDispatcher())
withContext(Dispatchers.Main) {
expect(6)
}
finish(7)
}
private inner class ImmediateDispatcher : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
expect(2)
return false
}
override fun dispatch(context: CoroutineContext, block: Runnable) = throw RuntimeException("Shouldn't be reached")
}
private inner class RegularDispatcher : CoroutineDispatcher() {
override fun isDispatchNeeded(context: CoroutineContext): Boolean {
expect(4)
return true
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
expect(5)
block.run()
}
}
}