-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathRunTestTest.kt
315 lines (291 loc) · 9.53 KB
/
RunTestTest.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
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
306
307
308
309
310
311
312
313
314
315
/*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.test
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.selects.*
import kotlin.coroutines.*
import kotlin.test.*
class RunTestTest {
/** Tests that [withContext] that sends work to other threads works in [runTest]. */
@Test
fun testWithContextDispatching() = runTest {
var counter = 0
withContext(Dispatchers.Default) {
counter += 1
}
assertEquals(counter, 1)
}
/** Tests that joining [GlobalScope.launch] works in [runTest]. */
@Test
fun testJoiningForkedJob() = runTest {
var counter = 0
val job = GlobalScope.launch {
counter += 1
}
job.join()
assertEquals(counter, 1)
}
/** Tests [suspendCoroutine] not failing [runTest]. */
@Test
fun testSuspendCoroutine() = runTest {
val answer = suspendCoroutine<Int> {
it.resume(42)
}
assertEquals(42, answer)
}
/** Tests that [runTest] attempts to detect it being run inside another [runTest] and failing in such scenarios. */
@Test
fun testNestedRunTestForbidden() = runTest {
assertFailsWith<IllegalStateException> {
runTest { }
}
}
/** Tests that even the dispatch timeout of `0` is fine if all the dispatches go through the same scheduler. */
@Test
fun testRunTestWithZeroTimeoutWithControlledDispatches() = runTest(dispatchTimeoutMs = 0) {
// below is some arbitrary concurrent code where all dispatches go through the same scheduler.
launch {
delay(2000)
}
val deferred = async {
val job = launch(StandardTestDispatcher(testScheduler)) {
launch {
delay(500)
}
delay(1000)
}
job.join()
}
deferred.await()
}
/** Tests that a dispatch timeout of `0` will fail the test if there are some dispatches outside the scheduler. */
@Test
@NoNative // the event loop was shut down
fun testRunTestWithZeroTimeoutWithUncontrolledDispatches() = testResultMap({ fn ->
assertFailsWith<UncompletedCoroutinesError> { fn() }
}) {
runTest(dispatchTimeoutMs = 0) {
withContext(Dispatchers.Default) {
delay(10)
3
}
fail("shouldn't be reached")
}
}
/** Tests that too low of a dispatch timeout causes crashes. */
@Test
@NoNative // TODO: timeout leads to `Cannot execute task because event loop was shut down` on Native
fun testRunTestWithSmallTimeout() = testResultMap({ fn ->
assertFailsWith<UncompletedCoroutinesError> { fn() }
}) {
runTest(dispatchTimeoutMs = 100) {
withContext(Dispatchers.Default) {
delay(10000)
3
}
fail("shouldn't be reached")
}
}
/** Tests that too low of a dispatch timeout causes crashes. */
@Test
fun testRunTestWithLargeTimeout() = runTest(dispatchTimeoutMs = 5000) {
withContext(Dispatchers.Default) {
delay(50)
}
}
/** Tests that [onTimeout] executes quickly. */
@Test
fun testOnTimeout() = runTest {
assertRunsFast {
val deferred = CompletableDeferred<Unit>()
val result = select<Boolean> {
onTimeout(SLOW) {
true
}
deferred.onJoin {
fail("unreached")
}
}
assertTrue(result)
}
}
/** Tests uncaught exceptions taking priority over dispatch timeout in error reports. */
@Test
@NoNative // TODO: timeout leads to `Cannot execute task because event loop was shut down` on Native
fun testRunTestTimingOutAndThrowing() = testResultMap({ fn ->
assertFailsWith<IllegalArgumentException> { fn() }
}) {
runTest(dispatchTimeoutMs = 1) {
coroutineContext[CoroutineExceptionHandler]!!.handleException(coroutineContext, IllegalArgumentException())
withContext(Dispatchers.Default) {
delay(10000)
3
}
fail("shouldn't be reached")
}
}
/** Tests that passing invalid contexts to [runTest] causes it to fail (on JS, without forking). */
@Test
fun testRunTestWithIllegalContext() {
for (ctx in TestScopeTest.invalidContexts) {
assertFailsWith<IllegalArgumentException> {
runTest(ctx) { }
}
}
}
/** Tests that throwing exceptions in [runTest] fails the test with them. */
@Test
fun testThrowingInRunTestBody() = testResultMap({
assertFailsWith<RuntimeException> { it() }
}) {
runTest {
throw RuntimeException()
}
}
/** Tests that throwing exceptions in pending tasks [runTest] fails the test with them. */
@Test
fun testThrowingInRunTestPendingTask() = testResultMap({
assertFailsWith<RuntimeException> { it() }
}) {
runTest {
launch {
delay(SLOW)
throw RuntimeException()
}
}
}
@Test
fun reproducer2405() = runTest {
val dispatcher = StandardTestDispatcher(testScheduler)
var collectedError = false
withContext(dispatcher) {
flow { emit(1) }
.combine(
flow<String> { throw IllegalArgumentException() }
) { int, string -> int.toString() + string }
.catch { emit("error") }
.collect {
assertEquals("error", it)
collectedError = true
}
}
assertTrue(collectedError)
}
/** Tests that, once the test body has thrown, the child coroutines are cancelled. */
@Test
fun testChildrenCancellationOnTestBodyFailure(): TestResult {
var job: Job? = null
return testResultMap({
assertFailsWith<AssertionError> { it() }
assertTrue(job!!.isCancelled)
}) {
runTest {
job = launch {
while (true) {
delay(1000)
}
}
throw AssertionError()
}
}
}
/** Tests that [runTest] reports [TimeoutCancellationException]. */
@Test
fun testTimeout() = testResultMap({
assertFailsWith<TimeoutCancellationException> { it() }
}) {
runTest {
withTimeout(50) {
launch {
delay(1000)
}
}
}
}
/** Checks that [runTest] throws the root cause and not [JobCancellationException] when a child coroutine throws. */
@Test
fun testRunTestThrowsRootCause() = testResultMap({
assertFailsWith<TestException> { it() }
}) {
runTest {
launch {
throw TestException()
}
}
}
/** Tests that [runTest] completes its job. */
@Test
fun testCompletesOwnJob(): TestResult {
var handlerCalled = false
return testResultMap({
it()
assertTrue(handlerCalled)
}) {
runTest {
coroutineContext.job.invokeOnCompletion {
handlerCalled = true
}
}
}
}
/** Tests that [runTest] doesn't complete the job that was passed to it as an argument. */
@Test
fun testDoesNotCompleteGivenJob(): TestResult {
var handlerCalled = false
val job = Job()
job.invokeOnCompletion {
handlerCalled = true
}
return testResultMap({
it()
assertFalse(handlerCalled)
assertEquals(0, job.children.filter { it.isActive }.count())
}) {
runTest(job) {
assertTrue(coroutineContext.job in job.children)
}
}
}
/** Tests that, when the test body fails, the reported exceptions are suppressed. */
@Test
fun testSuppressedExceptions() = testResultMap({
try {
it()
fail("should not be reached")
} catch (e: TestException) {
assertEquals("w", e.message)
val suppressed = e.suppressedExceptions +
(e.suppressedExceptions.firstOrNull()?.suppressedExceptions ?: emptyList())
assertEquals(3, suppressed.size)
assertEquals("x", suppressed[0].message)
assertEquals("y", suppressed[1].message)
assertEquals("z", suppressed[2].message)
}
}) {
runTest {
launch(SupervisorJob()) { throw TestException("x") }
launch(SupervisorJob()) { throw TestException("y") }
launch(SupervisorJob()) { throw TestException("z") }
throw TestException("w")
}
}
/** Tests that [TestCoroutineScope.runTest] does not inherit the exception handler and works. */
@Test
fun testScopeRunTestExceptionHandler(): TestResult {
val scope = TestScope()
return testResultMap({
try {
it()
fail("should not be reached")
} catch (e: TestException) {
// expected
}
}) {
scope.runTest {
launch(SupervisorJob()) { throw TestException("x") }
}
}
}
}