-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlowUtil.kt
More file actions
305 lines (230 loc) · 8.18 KB
/
FlowUtil.kt
File metadata and controls
305 lines (230 loc) · 8.18 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
class FlowTestObserver<T>(
private val coroutineScope: CoroutineScope,
private val flow: Flow<T>,
private val waitForDelay: Boolean = false
) {
private val testValues = mutableListOf<T>()
private var error: Throwable? = null
private var isInitialized = false
private var isCompleted = false
private lateinit var job: Job
private suspend fun init() {
job = createJob(coroutineScope)
// Wait this job after end of possible delays
// job.join()
}
private suspend fun initialize() {
if (!isInitialized) {
if (waitForDelay) {
try {
withTimeout(Long.MAX_VALUE) {
job = createJob(this)
}
} catch (e: Exception) {
isCompleted = false
}
} else {
job = createJob(coroutineScope)
}
}
}
private fun createJob(scope: CoroutineScope): Job {
val job = flow
.onStart { isInitialized = true }
.onCompletion { cause ->
isCompleted = (cause == null)
}
.catch { throwable ->
error = throwable
}
.onEach { testValues.add(it) }
.launchIn(scope)
return job
}
suspend fun assertNoValue(): FlowTestObserver<T> {
initialize()
if (testValues.isNotEmpty()) throw AssertionError(
"Assertion error! Actual size ${testValues.size}"
)
return this
}
suspend fun assertValueCount(count: Int): FlowTestObserver<T> {
initialize()
if (count < 0) throw AssertionError(
"Assertion error! Value count cannot be smaller than zero"
)
if (count != testValues.size) throw AssertionError(
"Assertion error! Expected $count while actual ${testValues.size}"
)
return this
}
suspend fun assertValues(vararg values: T): FlowTestObserver<T> {
initialize()
if (!testValues.containsAll(values.asList()))
throw AssertionError("Assertion error! At least one value does not match")
return this
}
suspend fun assertValues(predicate: (List<T>) -> Boolean): FlowTestObserver<T> {
initialize()
if (!predicate(testValues))
throw AssertionError("Assertion error! At least one value does not match")
return this
}
/**
* Asserts that this [FlowTestObserver] received exactly one [Flow.onEach] or [Flow.collect]
* value for which the provided predicate returns `true`.
*/
suspend fun assertValue(predicate: (T) -> Boolean): FlowTestObserver<T> {
return assertValueAt(0, predicate)
}
suspend fun assertValueAt(index: Int, predicate: (T) -> Boolean): FlowTestObserver<T> {
initialize()
if (testValues.size == 0) throw AssertionError("Assertion error! No values")
if (index < 0) throw AssertionError(
"Assertion error! Index cannot be smaller than zero"
)
if (index > testValues.size) throw AssertionError(
"Assertion error! Invalid index: $index"
)
if (!predicate(testValues[index]))
throw AssertionError("Assertion error! At least one value does not match")
return this
}
suspend fun assertValueAt(index: Int, value: T): FlowTestObserver<T> {
initialize()
if (testValues.size == 0) throw AssertionError("Assertion error! No values")
if (index < 0) throw AssertionError(
"Assertion error! Index cannot be smaller than zero"
)
if (index > testValues.size) throw AssertionError(
"Assertion error! Invalid index: $index"
)
if (testValues[index] != value)
throw AssertionError("Assertion Error Objects don't match")
return this
}
/**
* Asserts that this [FlowTestObserver] received
* [Flow.catch] the exact same throwable. Since most exceptions don't implement `equals`
* it would be better to call overload to test against the class of
* an error instead of an instance of an error
*/
suspend fun assertError(throwable: Throwable): FlowTestObserver<T> {
initialize()
val errorNotNull = exceptionNotNull()
if (!(
errorNotNull::class.java == throwable::class.java &&
errorNotNull.message == throwable.message
)
)
throw AssertionError(
"Assertion Error! " +
"throwable: $throwable does not match $errorNotNull"
)
return this
}
/**
* Asserts that this [FlowTestObserver] received
* [Flow.catch] which is an instance of the specified errorClass Class.
*/
suspend fun assertError(errorClass: Class<out Throwable>): FlowTestObserver<T> {
initialize()
val errorNotNull = exceptionNotNull()
if (errorNotNull::class.java != errorClass)
throw AssertionError(
"Assertion Error! errorClass $errorClass" +
" does not match ${errorNotNull::class.java}"
)
return this
}
/**
* Asserts that this [FlowTestObserver] received exactly [Flow.catch] event for which
* the provided predicate returns `true`.
*/
suspend fun assertError(predicate: (Throwable) -> Boolean): FlowTestObserver<T> {
initialize()
val errorNotNull = exceptionNotNull()
if (!predicate(errorNotNull))
throw AssertionError("Assertion Error! Exception for $errorNotNull")
return this
}
suspend fun assertNoErrors(): FlowTestObserver<T> {
initialize()
if (error != null)
throw AssertionError("Assertion Error! Exception occurred $error")
return this
}
suspend fun assertNull(): FlowTestObserver<T> {
initialize()
testValues.forEach {
if (it != null) throw AssertionError(
"Assertion Error! " +
"There are more than one item that is not null"
)
}
return this
}
/**
* Assert that this [FlowTestObserver] received [Flow.onCompletion] event without a [Throwable]
*/
suspend fun assertComplete(): FlowTestObserver<T> {
initialize()
if (!isCompleted) throw AssertionError(
"Assertion Error!" +
" Job is not completed or onCompletion called with a error!"
)
return this
}
/**
* Assert that this [FlowTestObserver] either not received [Flow.onCompletion] event or
* received event with
*/
suspend fun assertNotComplete(): FlowTestObserver<T> {
initialize()
if (isCompleted) throw AssertionError("Assertion Error! Job is completed!")
return this
}
suspend fun values(predicate: (List<T>) -> Unit): FlowTestObserver<T> {
predicate(testValues)
return this
}
suspend fun values(): List<T> {
initialize()
return testValues
}
private fun exceptionNotNull(): Throwable {
if (error == null)
throw AssertionError("There is no exception")
return error!!
}
fun dispose() {
job.cancel()
}
}
/**
* Creates a RxJava2 style test observer that uses `onStart`, `onEach`, `onCompletion`
*
* * Set waitForDelay true for testing delay.
*
* ### Note: waiting for delay with a channel that sends values throw TimeoutCancellationException,
* don't use timeout with channel
* TODO Fix channel issue
*/
suspend fun <T> Flow<T>.test(
scope: CoroutineScope,
waitForDelay: Boolean = true
): FlowTestObserver<T> {
return FlowTestObserver(scope, this@test, waitForDelay)
}
/**
* Test function that awaits with time out until each delay method is run and then since
* it takes a predicate that runs after a timeout.
*/
suspend fun <T> Flow<T>.testAfterDelay(
scope: CoroutineScope,
predicate: suspend FlowTestObserver<T>.() -> Unit
): Job {
return scope.launch(coroutineContext) {
FlowTestObserver(this, this@testAfterDelay, true).predicate()
}
}