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
|
/*
* 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
import kotlin.coroutines.*
import kotlin.test.*
class CancellableContinuationTest : TestBase() {
@Test
fun testResumeWithExceptionAndResumeWithException() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: TestException) {
expect(3)
}
}
expect(1)
yield()
continuation!!.resumeWithException(TestException())
yield()
assertFailsWith<IllegalStateException> { continuation!!.resumeWithException(TestException()) }
job.join()
finish(4)
}
@Test
fun testResumeAndResumeWithException() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
expect(3)
}
expect(1)
yield()
continuation!!.resume(Unit)
job.join()
assertFailsWith<IllegalStateException> { continuation!!.resumeWithException(TestException()) }
finish(4)
}
@Test
fun testResumeAndResume() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
expect(3)
}
expect(1)
yield()
continuation!!.resume(Unit)
job.join()
assertFailsWith<IllegalStateException> { continuation!!.resume(Unit) }
finish(4)
}
/**
* Cancelling outer job may, in practise, race with attempt to resume continuation and resumes
* should be ignored. Here suspended coroutine is cancelled but then resumed with exception.
*/
@Test
fun testCancelAndResumeWithException() = runTest(unhandled = listOf({e -> e is TestException})) {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: CancellationException) {
expect(3)
}
}
expect(1)
yield()
job.cancel() // Cancel job
yield()
continuation!!.resumeWithException(TestException()) // Should not fail
finish(4)
}
/**
* Cancelling outer job may, in practise, race with attempt to resume continuation and resumes
* should be ignored. Here suspended coroutine is cancelled but then resumed with exception.
*/
@Test
fun testCancelAndResume() = runTest {
var continuation: Continuation<Unit>? = null
val job = launch {
try {
expect(2)
suspendCancellableCoroutine<Unit> { c ->
continuation = c
}
} catch (e: CancellationException) {
expect(3)
}
}
expect(1)
yield()
job.cancel() // Cancel job
yield()
continuation!!.resume(Unit) // Should not fail
finish(4)
}
}
|