1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settingslib.spa.framework.util
18 
19 import androidx.test.ext.junit.runners.AndroidJUnit4
20 import com.google.common.truth.Truth.assertThat
21 import kotlinx.coroutines.ExperimentalCoroutinesApi
22 import kotlinx.coroutines.flow.count
23 import kotlinx.coroutines.flow.emptyFlow
24 import kotlinx.coroutines.flow.first
25 import kotlinx.coroutines.flow.flowOf
26 import kotlinx.coroutines.flow.toList
27 import kotlinx.coroutines.test.runTest
28 import org.junit.Test
29 import org.junit.runner.RunWith
30 
31 @OptIn(ExperimentalCoroutinesApi::class)
32 @RunWith(AndroidJUnit4::class)
33 class FlowsTest {
34     @Test
35     fun mapItem() = runTest {
36         val inputFlow = flowOf(listOf("A", "BB", "CCC"))
37 
38         val outputFlow = inputFlow.mapItem { it.length }
39 
40         assertThat(outputFlow.first()).containsExactly(1, 2, 3).inOrder()
41     }
42 
43     @Test
44     fun asyncMapItem() = runTest {
45         val inputFlow = flowOf(listOf("A", "BB", "CCC"))
46 
47         val outputFlow = inputFlow.asyncMapItem { it.length }
48 
49         assertThat(outputFlow.first()).containsExactly(1, 2, 3).inOrder()
50     }
51 
52     @Test
53     fun filterItem() = runTest {
54         val inputFlow = flowOf(listOf("A", "BB", "CCC"))
55 
56         val outputFlow = inputFlow.filterItem { it.length >= 2 }
57 
58         assertThat(outputFlow.first()).containsExactly("BB", "CCC").inOrder()
59     }
60 
61     @Test
62     fun waitFirst_otherFlowEmpty() = runTest {
63         val mainFlow = flowOf("A")
64         val otherFlow = emptyFlow<String>()
65 
66         val outputFlow = mainFlow.waitFirst(otherFlow)
67 
68         assertThat(outputFlow.count()).isEqualTo(0)
69     }
70 
71     @Test
72     fun waitFirst_otherFlowOneValue() = runTest {
73         val mainFlow = flowOf("A")
74         val otherFlow = flowOf("B")
75 
76         val outputFlow = mainFlow.waitFirst(otherFlow)
77 
78         assertThat(outputFlow.toList()).containsExactly("A")
79     }
80 
81     @Test
82     fun waitFirst_otherFlowTwoValues() = runTest {
83         val mainFlow = flowOf("A")
84         val otherFlow = flowOf("B", "B")
85 
86         val outputFlow = mainFlow.waitFirst(otherFlow)
87 
88         assertThat(outputFlow.toList()).containsExactly("A")
89     }
90 }
91