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
|
/*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913
package kotlinx.coroutines.selects
import kotlinx.coroutines.*
import kotlin.test.*
class SelectDeferredTest : TestBase() {
@Test
fun testSimpleReturnsImmediately() = runTest {
expect(1)
val d1 = async {
expect(3)
42
}
expect(2)
val res = select<String> {
d1.onAwait { v ->
expect(4)
assertEquals(42, v)
"OK"
}
}
expect(5)
assertEquals("OK", res)
finish(6)
}
@Test
fun testSimpleWithYield() = runTest {
expect(1)
val d1 = async {
expect(3)
42
}
launch {
expect(4)
yield() // back to main
expect(6)
}
expect(2)
val res = select<String> {
d1.onAwait { v ->
expect(5)
assertEquals(42, v)
yield() // to launch
expect(7)
"OK"
}
}
finish(8)
assertEquals("OK", res)
}
@Test
fun testSelectIncompleteLazy() = runTest {
expect(1)
val d1 = async(start = CoroutineStart.LAZY) {
expect(5)
42
}
launch {
expect(3)
val res = select<String> {
d1.onAwait { v ->
expect(7)
assertEquals(42, v)
"OK"
}
}
expect(8)
assertEquals("OK", res)
}
expect(2)
yield() // to launch
expect(4)
yield() // to started async
expect(6)
yield() // to triggered select
finish(9)
}
@Test
fun testSelectTwo() = runTest {
expect(1)
val d1 = async {
expect(3)
yield() // to the other deffered
expect(5)
yield() // to fired select
expect(7)
"d1"
}
val d2 = async {
expect(4)
"d2" // returns result
}
expect(2)
val res = select<String> {
d1.onAwait {
expectUnreached()
"FAIL"
}
d2.onAwait { v2 ->
expect(6)
assertEquals("d2", v2)
yield() // to first deferred
expect(8)
"OK"
}
}
assertEquals("OK", res)
finish(9)
}
@Test
fun testSelectCancel() = runTest(
expected = { it is CancellationException }
) {
expect(1)
val d = CompletableDeferred<String>()
launch {
finish(3)
d.cancel() // will cancel after select starts
}
expect(2)
select<Unit> {
d.onAwait {
expectUnreached() // will not select
}
}
expectUnreached()
}
}
|