-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathChannelsTest.kt
112 lines (97 loc) · 2.76 KB
/
ChannelsTest.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
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
111
112
@file:Suppress("DEPRECATION")
package kotlinx.coroutines.channels
import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
import kotlin.math.*
import kotlin.test.*
class ChannelsTest: TestBase() {
private val testList = listOf(1, 2, 3)
@Test
fun testIterableAsReceiveChannel() = runTest {
assertEquals(testList, testList.asReceiveChannel().toList())
}
@Test
fun testCloseWithMultipleSuspendedReceivers() = runTest {
// Once the channel is closed, the waiting
// requests should be cancelled in the order
// they were suspended in the channel.
val channel = Channel<Int>()
launch {
try {
expect(2)
channel.receive()
expectUnreached()
} catch (e: ClosedReceiveChannelException) {
expect(5)
}
}
launch {
try {
expect(3)
channel.receive()
expectUnreached()
} catch (e: ClosedReceiveChannelException) {
expect(6)
}
}
expect(1)
yield()
expect(4)
channel.close()
yield()
finish(7)
}
@Test
fun testCloseWithMultipleSuspendedSenders() = runTest {
// Once the channel is closed, the waiting
// requests should be cancelled in the order
// they were suspended in the channel.
val channel = Channel<Int>()
launch {
try {
expect(2)
channel.send(42)
expectUnreached()
} catch (e: CancellationException) {
expect(5)
}
}
launch {
try {
expect(3)
channel.send(42)
expectUnreached()
} catch (e: CancellationException) {
expect(6)
}
}
expect(1)
yield()
expect(4)
channel.cancel()
yield()
finish(7)
}
@Test
fun testEmptyList() = runTest {
assertTrue(emptyList<Nothing>().asReceiveChannel().toList().isEmpty())
}
@Test
fun testToList() = runTest {
assertEquals(testList, testList.asReceiveChannel().toList())
}
@Test
fun testToListOnFailedChannel() = runTest {
val channel = Channel<Int>()
channel.close(TestException())
assertFailsWith<TestException> {
channel.toList()
}
}
private fun <E> Iterable<E>.asReceiveChannel(context: CoroutineContext = Dispatchers.Unconfined): ReceiveChannel<E> =
GlobalScope.produce(context) {
for (element in this@asReceiveChannel)
send(element)
}
}