-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathLimitedParallelismSharedTest.kt
59 lines (54 loc) · 2.08 KB
/
LimitedParallelismSharedTest.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
package kotlinx.coroutines
import kotlinx.coroutines.testing.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.test.*
class LimitedParallelismSharedTest : TestBase() {
@Test
fun testLimitedDefault() = runTest {
// Test that evaluates the very basic completion of tasks in limited dispatcher
// for all supported platforms.
// For more specific and concurrent tests, see 'concurrent' package.
val view = Dispatchers.Default.limitedParallelism(1)
val view2 = Dispatchers.Default.limitedParallelism(1)
val j1 = launch(view) {
while (true) {
yield()
}
}
val j2 = launch(view2) { j1.cancel() }
joinAll(j1, j2)
}
@Test
fun testParallelismSpec() {
assertFailsWith<IllegalArgumentException> { Dispatchers.Default.limitedParallelism(0) }
assertFailsWith<IllegalArgumentException> { Dispatchers.Default.limitedParallelism(-1) }
assertFailsWith<IllegalArgumentException> { Dispatchers.Default.limitedParallelism(Int.MIN_VALUE) }
Dispatchers.Default.limitedParallelism(Int.MAX_VALUE)
}
/**
* Checks that even if the dispatcher sporadically fails, the limited dispatcher will still allow reaching the
* target parallelism level.
*/
@Test
fun testLimitedParallelismOfOccasionallyFailingDispatcher() {
val limit = 5
var doFail = false
val workerQueue = mutableListOf<Runnable>()
val limited = object: CoroutineDispatcher() {
override fun dispatch(context: CoroutineContext, block: Runnable) {
if (doFail) throw TestException()
workerQueue.add(block)
}
}.limitedParallelism(limit)
repeat(6 * limit) {
try {
limited.dispatch(EmptyCoroutineContext, Runnable { /* do nothing */ })
} catch (_: DispatchException) {
// ignore
}
doFail = !doFail
}
assertEquals(limit, workerQueue.size)
}
}