forked from Kotlin/kotlinx.coroutines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAwaitTest.kt
83 lines (74 loc) · 2.24 KB
/
AwaitTest.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
72
73
74
75
76
77
78
79
80
81
82
83
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.reactive
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.*
import org.junit.*
import org.reactivestreams.*
class AwaitTest: TestBase() {
/** Tests that calls to [awaitFirst] (and, thus, to the rest of these functions) throw [CancellationException] and
* unsubscribe from the publisher when their [Job] is cancelled. */
@Test
fun testAwaitCancellation() = runTest {
expect(1)
val publisher = Publisher<Int> { s ->
s.onSubscribe(object: Subscription {
override fun request(n: Long) {
expect(3)
}
override fun cancel() {
expect(5)
}
})
}
val job = launch(start = CoroutineStart.UNDISPATCHED) {
try {
expect(2)
publisher.awaitFirst()
} catch (e: CancellationException) {
expect(6)
throw e
}
}
expect(4)
job.cancelAndJoin()
finish(7)
}
@Test
fun testAwaitCancellationPerformedSerially() = runTest {
val requestCompletion = Mutex(locked = true)
val subscriptionStarted = Mutex(locked = true)
expect(1)
val publisher = Publisher<Int> { s ->
s.onSubscribe(object : Subscription {
override fun request(n: Long) {
expect(2)
subscriptionStarted.unlock()
runBlocking { requestCompletion.lock() }
expect(4)
}
override fun cancel() {
expect(5)
}
})
}
val job = launch(Dispatchers.Default) {
try {
publisher.awaitFirst()
} catch (e: CancellationException) {
expect(6)
throw e
}
}
subscriptionStarted.lock()
expect(3)
launch(Dispatchers.Default) {
job.cancel()
}
delay(10)
requestCompletion.unlock()
job.join()
finish(7)
}
}