blob: 370fd5b9a2756a7bd604c40f3372385666633080 (
plain)
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
|
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.channels
import kotlinx.coroutines.*
import kotlin.test.*
open class ConflatedChannelTest : TestBase() {
protected open fun <T> createConflatedChannel() =
Channel<T>(Channel.CONFLATED)
@Test
fun testBasicConflationOfferTryReceive() {
val q = createConflatedChannel<Int>()
assertNull(q.tryReceive().getOrNull())
assertTrue(q.trySend(1).isSuccess)
assertTrue(q.trySend(2).isSuccess)
assertTrue(q.trySend(3).isSuccess)
assertEquals(3, q.tryReceive().getOrNull())
assertNull(q.tryReceive().getOrNull())
}
@Test
fun testConflatedSend() = runTest {
val q = createConflatedChannel<Int>()
q.send(1)
q.send(2) // shall conflated previously sent
assertEquals(2, q.receiveCatching().getOrNull())
}
@Test
fun testConflatedClose() = runTest {
val q = createConflatedChannel<Int>()
q.send(1)
q.close() // shall become closed but do not conflate last sent item yet
assertTrue(q.isClosedForSend)
assertFalse(q.isClosedForReceive)
assertEquals(1, q.receive())
// not it is closed for receive, too
assertTrue(q.isClosedForSend)
assertTrue(q.isClosedForReceive)
assertNull(q.receiveCatching().getOrNull())
}
@Test
fun testConflationSendReceive() = runTest {
val q = createConflatedChannel<Int>()
expect(1)
launch { // receiver coroutine
expect(4)
assertEquals(2, q.receive())
expect(5)
assertEquals(3, q.receive()) // this receive suspends
expect(8)
assertEquals(6, q.receive()) // last conflated value
expect(9)
}
expect(2)
q.send(1)
q.send(2) // shall conflate
expect(3)
yield() // to receiver
expect(6)
q.send(3) // send to the waiting receiver
q.send(4) // buffer
q.send(5) // conflate
q.send(6) // conflate again
expect(7)
yield() // to receiver
finish(10)
}
@Test
fun testConsumeAll() = runTest {
val q = createConflatedChannel<Int>()
expect(1)
for (i in 1..10) {
q.send(i) // stores as last
}
q.cancel()
check(q.isClosedForSend)
check(q.isClosedForReceive)
assertFailsWith<CancellationException> { q.receiveCatching().getOrThrow() }
finish(2)
}
@Test
fun testCancelWithCause() = runTest({ it is TestCancellationException }) {
val channel = createConflatedChannel<Int>()
channel.cancel(TestCancellationException())
channel.receive()
}
}
|