package ch.skew.remotrix.bridge import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import org.junit.Assert.* import org.junit.Test class BridgeResetTest { @Test fun waitsForInFlightForwardingBeforeDeletingMappings() = runBlocking { val work = CoroutineScope(Job() + Dispatchers.Default) val started = CompletableDeferred() val mappings = mutableListOf() var clientsStopped = false work.launch { try { started.complete(Unit) awaitCancellation() } finally { // A forwarding job may still persist its result during cleanup. withContext(NonCancellable) { delay(20) mappings.add("old room") } } } started.await() resetBridge(work, stopClients = { clientsStopped = true }, clearData = { assertTrue(clientsStopped) assertEquals(listOf("old room"), mappings) mappings.clear() } ) assertTrue(mappings.isEmpty()) assertFalse(work.coroutineContext[Job]!!.isActive) } @Test fun doesNotDeleteStoresWhenStoppingClientsFails() = runBlocking { val work = CoroutineScope(Job()) var deleted = false val result = runCatching { resetBridge(work, stopClients = { error("store is still open") }, clearData = { deleted = true } ) } assertTrue(result.isFailure) assertFalse(deleted) } }