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
|
/*
* 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 kotlinx.coroutines.channels.*
import kotlin.test.*
class ScanTest : TestBase() {
@Test
fun testScan() = runTest {
val flow = flowOf(1, 2, 3, 4, 5)
val result = flow.runningReduce { acc, v -> acc + v }.toList()
assertEquals(listOf(1, 3, 6, 10, 15), result)
}
@Test
fun testScanWithInitial() = runTest {
val flow = flowOf(1, 2, 3)
val result = flow.scan(emptyList<Int>()) { acc, value -> acc + value }.toList()
assertEquals(listOf(emptyList(), listOf(1), listOf(1, 2), listOf(1, 2, 3)), result)
}
@Test
fun testNulls() = runTest {
val flow = flowOf(null, 2, null, null, null, 5)
val result = flow.runningReduce { acc, v -> if (v == null) acc else (if (acc == null) v else acc + v) }.toList()
assertEquals(listOf(null, 2, 2, 2, 2, 7), result)
}
@Test
fun testEmptyFlow() = runTest {
val result = emptyFlow<Int>().runningReduce { _, _ -> 1 }.toList()
assertTrue(result.isEmpty())
}
@Test
fun testErrorCancelsUpstream() = runTest {
expect(1)
val latch = Channel<Unit>()
val flow = flow {
coroutineScope {
launch {
latch.send(Unit)
hang { expect(3) }
}
emit(1)
emit(2)
}
}.runningReduce { _, value ->
expect(value) // 2
latch.receive()
throw TestException()
}.catch { /* ignore */ }
assertEquals(1, flow.single())
finish(4)
}
private operator fun <T> Collection<T>.plus(element: T): List<T> {
val result = ArrayList<T>(size + 1)
result.addAll(this)
result.add(element)
return result
}
}
|