-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathJobExtensionsTest.kt
95 lines (81 loc) · 2.74 KB
/
JobExtensionsTest.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
/*
* Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import kotlin.coroutines.*
import kotlin.test.*
class JobExtensionsTest : TestBase() {
private val job = Job()
private val scope = CoroutineScope(job + CoroutineExceptionHandler { _, _ -> })
@Test
fun testIsActive() = runTest {
expect(1)
scope.launch(Dispatchers.Unconfined) {
ensureActive()
coroutineContext.ensureActive()
coroutineContext[Job]!!.ensureActive()
expect(2)
delay(Long.MAX_VALUE)
}
expect(3)
job.ensureActive()
scope.ensureActive()
scope.coroutineContext.ensureActive()
job.cancelAndJoin()
finish(4)
}
@Test
fun testIsCompleted() = runTest {
expect(1)
scope.launch(Dispatchers.Unconfined) {
ensureActive()
coroutineContext.ensureActive()
coroutineContext[Job]!!.ensureActive()
expect(2)
}
expect(3)
job.complete()
job.join()
assertFailsWith<JobCancellationException> { job.ensureActive() }
assertFailsWith<JobCancellationException> { scope.ensureActive() }
assertFailsWith<JobCancellationException> { scope.coroutineContext.ensureActive() }
finish(4)
}
@Test
fun testIsCancelled() = runTest {
expect(1)
scope.launch(Dispatchers.Unconfined) {
ensureActive()
coroutineContext.ensureActive()
coroutineContext[Job]!!.ensureActive()
expect(2)
throw TestException()
}
expect(3)
checkException { job.ensureActive() }
checkException { scope.ensureActive() }
checkException { scope.coroutineContext.ensureActive() }
finish(4)
}
@Test
fun testEnsureActiveWithEmptyContext() = runTest {
withEmptyContext {
ensureActive() // should not do anything
}
}
private inline fun checkException(block: () -> Unit) {
val result = runCatching(block)
val exception = result.exceptionOrNull() ?: fail()
assertTrue(exception is JobCancellationException)
assertTrue(exception.cause is TestException)
}
@Test
fun testJobExtension() = runTest {
assertSame(coroutineContext[Job]!!, coroutineContext.job)
assertSame(NonCancellable, NonCancellable.job)
assertSame(job, job.job)
assertFailsWith<IllegalStateException> { EmptyCoroutineContext.job }
assertFailsWith<IllegalStateException> { Dispatchers.Default.job }
assertFailsWith<IllegalStateException> { (Dispatchers.Default + CoroutineName("")).job }
}
}