package eu.friedcutlet.yokan.services import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancel import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.job import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext class ConcurrencyTest { private fun TestScope.owner() = CoroutineScope(backgroundScope.coroutineContext + SupervisorJob(backgroundScope.coroutineContext.job)) @Test fun runJoinedReturnsTheActionResult() = runTest { assertEquals(42, owner().runJoined { 42 }) } @Test fun rejectedAdmissionNeverStartsTheAction() = runTest { var started = false assertFailsWith { owner().runJoined(admit = { error("closed") }) { started = true } } assertFalse(started) } @Test fun cancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizers() = runTest { val owner = owner() val entered = CompletableDeferred() var finalized = false val caller = launch { owner.runJoined { entered.complete(Unit) try { awaitCancellation() } finally { withContext(NonCancellable) { delay(10) finalized = true } } } } entered.await() caller.cancelAndJoin() assertTrue(finalized) assertTrue(owner.coroutineContext.job.isActive) } @Test fun closingTheOwnerCancelsInFlightWork() = runTest { val owner = owner() val entered = CompletableDeferred() var cancelled = false val call = async { assertFailsWith { owner.runJoined { entered.complete(Unit) try { awaitCancellation() } finally { cancelled = true } } } } entered.await() owner.cancel() call.await() assertTrue(cancelled) } @Test fun resultProducedAfterTheOwnerClosedIsDiscarded() = runTest { val owner = owner() assertFailsWith { owner.runJoined { // A delegate that returns from a non-cancellable section after its owner closed. withContext(NonCancellable) { owner.cancel() "stale" } } } } }