aboutsummaryrefslogtreecommitdiffstats
path: root/kotlinx-coroutines-core/common/test/flow/operators/MapNotNullTest.kt
blob: 893811df15f360a3c887f5bdefff779e17945128 (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
/*
 * 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 MapNotNullTest : TestBase() {
    @Test
    fun testMap() = runTest {
        val flow = flow {
            emit(1)
            emit(null)
            emit(2)
        }

        val result = flow.mapNotNull { it }.sum()
        assertEquals(3, result)
    }

    @Test
    fun testEmptyFlow() = runTest {
        val sum = emptyFlow<Int>().mapNotNull { expectUnreached(); it }.sum()
        assertEquals(0, sum)
    }

    @Test
    fun testErrorCancelsUpstream() = runTest {
        var cancelled = false
        val latch = Channel<Unit>()
        val flow = flow {
            coroutineScope {
                launch {
                    latch.send(Unit)
                    hang { cancelled = true }
                }
                emit(1)
            }
        }.mapNotNull {
            latch.receive()
            throw TestException()
            it + 1
        }.catch { emit(42) }

        assertEquals(42, flow.single())
        assertTrue(cancelled)
    }
}