ConcurrencyTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/ConcurrencyTest.kt
1package eu.friedcutlet.yokan.services23import kotlin.test.Test4import kotlin.test.assertEquals5import kotlin.test.assertFailsWith6import kotlin.test.assertFalse7import kotlin.test.assertTrue8import kotlinx.coroutines.CancellationException9import kotlinx.coroutines.CompletableDeferred10import kotlinx.coroutines.CoroutineScope11import kotlinx.coroutines.NonCancellable12import kotlinx.coroutines.SupervisorJob13import kotlinx.coroutines.async14import kotlinx.coroutines.awaitCancellation15import kotlinx.coroutines.cancel16import kotlinx.coroutines.cancelAndJoin17import kotlinx.coroutines.delay18import kotlinx.coroutines.job19import kotlinx.coroutines.launch20import kotlinx.coroutines.test.TestScope21import kotlinx.coroutines.test.runTest22import kotlinx.coroutines.withContext2324class ConcurrencyTest {25 private fun TestScope.owner() = CoroutineScope(backgroundScope.coroutineContext + SupervisorJob(backgroundScope.coroutineContext.job))2627 @Test28 fun runJoinedReturnsTheActionResult() = runTest {29 assertEquals(42, owner().runJoined { 42 })30 }3132 @Test33 fun rejectedAdmissionNeverStartsTheAction() = runTest {34 var started = false3536 assertFailsWith<IllegalStateException> {37 owner().runJoined(admit = { error("closed") }) { started = true }38 }3940 assertFalse(started)41 }4243 @Test44 fun cancellingTheCallerCancelsTheWorkAndAwaitsItsFinalizers() = runTest {45 val owner = owner()46 val entered = CompletableDeferred<Unit>()47 var finalized = false48 val caller = launch {49 owner.runJoined {50 entered.complete(Unit)51 try {52 awaitCancellation()53 } finally {54 withContext(NonCancellable) {55 delay(10)56 finalized = true57 }58 }59 }60 }61 entered.await()6263 caller.cancelAndJoin()6465 assertTrue(finalized)66 assertTrue(owner.coroutineContext.job.isActive)67 }6869 @Test70 fun closingTheOwnerCancelsInFlightWork() = runTest {71 val owner = owner()72 val entered = CompletableDeferred<Unit>()73 var cancelled = false74 val call = async {75 assertFailsWith<CancellationException> {76 owner.runJoined {77 entered.complete(Unit)78 try {79 awaitCancellation()80 } finally {81 cancelled = true82 }83 }84 }85 }86 entered.await()8788 owner.cancel()89 call.await()9091 assertTrue(cancelled)92 }9394 @Test95 fun resultProducedAfterTheOwnerClosedIsDiscarded() = runTest {96 val owner = owner()9798 assertFailsWith<CancellationException> {99 owner.runJoined {100 // A delegate that returns from a non-cancellable section after its owner closed.101 withContext(NonCancellable) {102 owner.cancel()103 "stale"104 }105 }106 }107 }108}109