@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, kotlinx.coroutines.InternalCoroutinesApi::class) package eu.friedcutlet.yokan.ui.screens.player import eu.friedcutlet.yokan.services.media.player.MediaPlayerController import eu.friedcutlet.yokan.services.media.player.MpvBridgeEvent import eu.friedcutlet.yokan.services.media.player.ProfilePlayerServicesTest import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineName import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.FlowCollector import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue class PlayerUiBindingTest { @Test fun bridgeDeliveryUsesCapturedUiContextAndExpiresOnClose() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob() val events = MutableSharedFlow(); val delivered = mutableListOf() val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler) + CoroutineName("captured-ui"))) val collect = async { binding.collectBridgeEvents { delivered += it } } try { runCurrent(); assertEquals(1, events.subscriptionCount.value) events.emit(Event); runCurrent(); assertEquals(listOf(Event), delivered) binding.close(); collect.join(); events.emit(Event) assertEquals(listOf(Event), delivered); assertEquals(0, events.subscriptionCount.value) assertTrue(parent.isActive); assertTrue(f.service.isAvailable) } finally { binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() } } @Test fun readerDeliveryRetainsCallersContextAcrossOwnedCollection() = runTest { val f = ProfilePlayerServicesTest.Fixture(this) var deliveredContext: String? = null val source = flow { emit(Event); awaitCancellation() } val collect = async(CoroutineName("captured-ui")) { f.reader.collectBridgeEvents(controller(source)) { deliveredContext = currentCoroutineContext()[CoroutineName]?.name } } try { runCurrent(); assertEquals("captured-ui", deliveredContext) } finally { collect.cancelAndJoin(); f.close() } } @Test fun disposedBindingJoinsFinalizerAndRejectsItsLateEvent() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred() val delivered = mutableListOf(); var rejectedLate = false val source = object : Flow { override suspend fun collect(collector: FlowCollector) { collector.emit(Event) try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() try { collector.emit(Event.copy(value = "late")) } catch (_: CancellationException) { rejectedLate = true } } } } } val binding = PlayerUiBinding(f.reader, controller(source), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val collect = async { binding.collectBridgeEvents { delivered += it } } try { runCurrent(); binding.close(); runCurrent() assertFalse(collect.isCompleted); assertFalse(binding.active()); assertTrue(parent.isActive) finish.complete(Unit); collect.join() assertEquals(listOf(Event), delivered); assertTrue(rejectedLate) } finally { finish.complete(Unit); binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() } } @Test fun callerCancellationJoinsCollectionWithoutCancelingSiblingBinding() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred() val uiScope = CoroutineScope(parent + StandardTestDispatcher(testScheduler)) val source = flow { try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() } } } val first = PlayerUiBinding(f.reader, controller(source), uiScope) val events = MutableSharedFlow(); val delivered = mutableListOf() val sibling = PlayerUiBinding(f.reader, controller(events), uiScope) val a = async { first.collectBridgeEvents { } }; val b = async { sibling.collectBridgeEvents { delivered += it } } try { runCurrent(); a.cancel(); runCurrent(); assertFalse(a.isCompleted) events.emit(Event); runCurrent(); assertEquals(listOf(Event), delivered); assertTrue(sibling.active()) finish.complete(Unit); a.join(); assertTrue(first.active()); assertTrue(parent.isActive) } finally { finish.complete(Unit); first.close(); sibling.close(); a.cancelAndJoin(); b.cancelAndJoin(); parent.cancelAndJoin(); f.close() } } @Test fun sessionRetirementJoinsBridgeFinalizerBeforeReturning() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); val finish = CompletableDeferred() val source = flow { try { awaitCancellation() } finally { withContext(NonCancellable) { finish.await() } } } val binding = PlayerUiBinding(f.reader, controller(source), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) val collect = async { binding.collectBridgeEvents { } } try { runCurrent(); val close = async { f.service.closeAndJoin() }; runCurrent() assertFalse(close.isCompleted); assertFalse(collect.isCompleted); assertFalse(binding.active()) finish.complete(Unit); close.await(); collect.join() assertTrue(parent.isActive); assertTrue(f.owner.isActive) } finally { finish.complete(Unit); binding.close(); collect.cancelAndJoin(); parent.cancelAndJoin(); f.close() } } @Test fun inactiveOrExpiredBindingsCannotSubscribe() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob(); var active = false val events = MutableSharedFlow() val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) { active } try { binding.collectBridgeEvents { error("Inactive delivery") }; assertEquals(0, events.subscriptionCount.value) active = true; f.reader.retire() binding.collectBridgeEvents { error("Expired delivery") }; assertEquals(0, events.subscriptionCount.value) } finally { binding.close(); parent.cancelAndJoin(); f.close() } } @Test fun alreadyCanceledCallerCannotSubscribeIntoLiveBinding() = runTest { val f = ProfilePlayerServicesTest.Fixture(this); val parent = SupervisorJob() val events = MutableSharedFlow() val binding = PlayerUiBinding(f.reader, controller(events), CoroutineScope(parent + StandardTestDispatcher(testScheduler))) try { val call = async(UnconfinedTestDispatcher(testScheduler)) { requireNotNull(currentCoroutineContext()[Job]).cancel() assertFailsWith { binding.collectBridgeEvents { } } } call.join(); assertEquals(0, events.subscriptionCount.value); assertTrue(binding.active()) } finally { binding.close(); parent.cancelAndJoin(); f.close() } } companion object { val Event = MpvBridgeEvent("aniyomi/switch_episode", "n") fun controller(events: Flow): MediaPlayerController = object : MediaPlayerController by ProfilePlayerServicesTest.Controller() { override val mpvBridgeEvents = events } } }