forked from Kotlin/kotlinx.coroutines
/
SingleTest.kt
94 lines (77 loc) · 2.3 KB
/
SingleTest.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
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.test.*
class SingleTest : TestBase() {
@Test
fun testSingle() = runTest {
val flow = flow {
emit(239L)
}
assertEquals(239L, flow.single())
assertEquals(239L, flow.singleOrNull())
}
@Test
fun testMultipleValues() = runTest {
val flow = flow {
emit(239L)
emit(240L)
}
assertFailsWith<IllegalArgumentException> { flow.single() }
assertNull(flow.singleOrNull())
}
@Test
fun testNoValues() = runTest {
assertFailsWith<NoSuchElementException> { flow<Int> {}.single() }
assertNull(flow<Int> {}.singleOrNull())
}
@Test
fun testException() = runTest {
val flow = flow<Int> {
throw TestException()
}
assertFailsWith<TestException> { flow.single() }
assertFailsWith<TestException> { flow.singleOrNull() }
}
@Test
fun testExceptionAfterValue() = runTest {
val flow = flow {
emit(1)
throw TestException()
}
assertFailsWith<TestException> { flow.single() }
assertFailsWith<TestException> { flow.singleOrNull() }
}
@Test
fun testNullableSingle() = runTest {
assertEquals(1, flowOf<Int?>(1).single())
assertNull(flowOf<Int?>(null).single())
assertFailsWith<NoSuchElementException> { flowOf<Int?>().single() }
assertEquals(1, flowOf<Int?>(1).singleOrNull())
assertNull(flowOf<Int?>(null).singleOrNull())
assertNull(flowOf<Int?>().singleOrNull())
}
@Test
fun testBadClass() = runTest {
val instance = BadClass()
val flow = flowOf(instance)
assertSame(instance, flow.single())
assertSame(instance, flow.singleOrNull())
val flow2 = flow {
emit(BadClass())
emit(BadClass())
}
assertFailsWith<IllegalArgumentException> { flow2.single() }
}
@Test
fun testSingleNoWait() = runTest {
val flow = flow {
emit(1)
emit(2)
awaitCancellation()
}
assertNull(flow.singleOrNull())
}
}