RoomClientAdmissionConcurrencyTest.kt
composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/together/RoomClientAdmissionConcurrencyTest.kt
1package eu.friedcutlet.yokan.services.together23import eu.friedcutlet.yokan.services.http.ProfileTestEngine4import kotlinx.coroutines.CoroutineScope5import kotlinx.coroutines.SupervisorJob6import kotlinx.coroutines.awaitCancellation7import kotlinx.coroutines.cancelAndJoin8import kotlinx.coroutines.test.StandardTestDispatcher9import kotlinx.coroutines.test.runTest10import java.util.concurrent.ConcurrentLinkedQueue11import java.util.concurrent.CountDownLatch12import java.util.concurrent.TimeUnit13import kotlin.concurrent.thread14import kotlin.test.Test15import kotlin.test.assertEquals16import kotlin.test.assertFalse17import kotlin.test.assertTrue1819class RoomClientAdmissionConcurrencyTest {20 @Test fun concurrentCloseDoesNotWaitForABlockedCredentialRead() = runTest {21 val parent = SupervisorJob(); val dispatcher = StandardTestDispatcher(testScheduler)22 val entered = CountDownLatch(1); val release = CountDownLatch(1); val closed = CountDownLatch(1)23 val failures = ConcurrentLinkedQueue<Throwable>()24 val engine = ProfileTestEngine(dispatcher) { awaitCancellation() }25 val client = RoomClient(engine, HubSession("https://hub.test", "token", "device"), "ABC",26 CoroutineScope(parent + dispatcher)) {27 entered.countDown()28 release.await()29 true30 }31 val connecting = thread(name = "room-admission-test", isDaemon = true) {32 try { client.connect() } catch (error: Throwable) { failures.add(error) }33 }34 var closing: Thread? = null35 try {36 assertTrue(entered.await(5, TimeUnit.SECONDS), "Credential read did not start")37 closing = thread(name = "room-close-test", isDaemon = true) {38 try { client.close() } catch (error: Throwable) { failures.add(error) }39 finally { closed.countDown() }40 }41 // If admission holds the room lock, release would wait for this blocked database read.42 assertTrue(closed.await(5, TimeUnit.SECONDS), "Close is blocked by the credential read")43 assertEquals(1, engine.closeCalls)44 } finally {45 release.countDown()46 connecting.join(5_000); closing?.join(5_000)47 client.closeAndJoin(); parent.cancelAndJoin()48 }49 assertFalse(connecting.isAlive); assertFalse(closing.isAlive)50 assertTrue(failures.isEmpty(), failures.toString())51 assertTrue(engine.requests.tryReceive().isFailure)52 }53}54