@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class) package eu.friedcutlet.yokan.services.media.player import androidx.compose.runtime.SideEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.ImageComposeScene import eu.friedcutlet.yokan.database.DbSettings import eu.friedcutlet.yokan.ui.screens.player.rememberPlayerServices import java.util.concurrent.CountDownLatch import java.util.concurrent.FutureTask import java.util.concurrent.TimeUnit import javax.swing.SwingUtilities import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertNotSame import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext class ProfilePlayerServicesLifecycleTest { @Test fun canceledFactoryCallerJoinsBlockingAllocationAndLateNativeCleanup() = runTest { val entered = CountDownLatch(1); val release = CountDownLatch(1) val controller = ProfilePlayerControllerTest.Controller() val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO, factory = { _, _ -> entered.countDown(); check(release.await(10, TimeUnit.SECONDS)); controller }) var published = false val configuration = f.reader.configuration(DbSettings()) val call = async { f.reader.withController(configuration) { published = true } } try { runCurrent(); withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) } call.cancel(); runCurrent(); assertFalse(call.isCompleted) release.countDown(); call.join() assertFalse(published); assertEquals(1, controller.closes); assertTrue(controller.released) assertTrue(f.service.isAvailable) } finally { release.countDown(); call.cancelAndJoin(); f.close() } } @Test fun canceledConfigurationCallerJoinsBlockingWriteAndSkipsSecondFile() = runTest { val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO) val entered = CountDownLatch(1) val release = CountDownLatch(1) f.files.onWrite = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) } val configuration = f.reader.configuration(DbSettings()) val request = async { f.reader.prepareConfiguration(configuration) } try { runCurrent() withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) } request.cancel(); runCurrent() assertFalse(request.isCompleted) release.countDown() request.join() assertEquals(listOf("/A/cache/mpv/mpv.conf"), f.files.writes) assertTrue(f.service.isAvailable) } finally { release.countDown(); request.cancelAndJoin(); f.close() } } @Test fun retirementJoinsBlockingScreenshotSeedAndDeletesItWithoutDispatch() = runTest { val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO) val controller = ProfilePlayerServicesTest.Controller() val entered = CountDownLatch(1) val release = CountDownLatch(1) f.files.onWrite = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) } val request = async { f.reader.requestScreenshot(controller, "Book", "Episode") } try { runCurrent() withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) } val close = async { f.service.closeAndJoin() } runCurrent() assertFalse(close.isCompleted) assertFalse(request.isCompleted) release.countDown() close.await() assertFailsWith { request.await() } assertTrue(controller.commands.isEmpty()) assertEquals(f.files.writes, f.files.deletions) assertTrue(f.owner.isActive) } finally { release.countDown(); request.cancelAndJoin(); f.close() } } @Test fun closeDrainsNativeThreadProxyRegistrationOffUiThread() = runTest { val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO) val entered = CountDownLatch(1) val release = CountDownLatch(1) f.proxy.onRegister = { entered.countDown(); check(release.await(10, TimeUnit.SECONDS)) } val request = async(Dispatchers.IO) { f.reader.streamProxy.proxyUrl("https://stream.test", emptyMap()) } try { withContext(Dispatchers.IO) { assertTrue(entered.await(5, TimeUnit.SECONDS)) } val close = async { f.service.closeAndJoin() } runCurrent() assertFalse(close.isCompleted) assertFalse(f.service.isAvailable) release.countDown() close.await() assertFailsWith { request.await() } assertEquals(0, f.proxy.stops) } finally { release.countDown(); request.cancelAndJoin(); f.close() } } @Test fun compositionDisposalExpiresCallsAndRemountGetsFreshHandle() = runTest { val f = UiFixture(this) try { val old = f.reader f.show(false) assertFalse(old.isAvailable) assertFailsWith { old.markers(42, 1, 0) } assertFailsWith { old.streamProxy.proxyUrl("Old", emptyMap()) } assertTrue(f.a.http.requests.isEmpty()) assertTrue(f.a.proxy.urls.isEmpty()) f.show(true) assertNotSame(old, f.reader) assertEquals("proxy:New", f.reader.streamProxy.proxyUrl("New", emptyMap())) } finally { f.close() } } @Test fun chapterReplacementRejectsOldConfigurationAndProxyWithoutStoppingSession() = runTest { val f = UiFixture(this) try { val old = f.reader val configuration = old.configuration(DbSettings()) f.ui { f.chapter.value = 20L }; f.pump() assertNotSame(old, f.reader) assertFailsWith { old.prepareConfiguration(configuration) } old.streamProxy.stop() assertEquals("proxy:New chapter", f.reader.streamProxy.proxyUrl("New chapter", emptyMap())) assertEquals(0, f.a.proxy.stops) assertTrue(f.a.files.writes.isEmpty()) } finally { f.close() } } @Test fun serviceReplacementWithSameChapterUsesNewFilesAndRejectsOldScreenshot() = runTest { val f = UiFixture(this) try { val old = f.reader f.ui { f.current.value = f.b.service }; f.pump() assertNotSame(old, f.reader) assertFailsWith { old.requestScreenshot(ProfilePlayerServicesTest.Controller(), "Book", "Episode") } f.reader.prepareConfiguration(f.reader.configuration(DbSettings())) assertTrue(f.a.files.writes.isEmpty()) assertEquals(listOf("/B/cache/mpv/mpv.conf", "/B/cache/mpv/input.conf"), f.b.files.writes) } finally { f.close() } } @Test fun retiringStatusRejectsVisibleHandleBeforeOwnerScopeCancellation() = runTest { val f = UiFixture(this) try { f.a.open = false assertTrue(f.a.owner.isActive) assertFailsWith { f.reader.markers(42, 1, 0) } assertFailsWith { f.reader.streamProxy.proxyUrl("Late", emptyMap()) } assertTrue(f.a.http.requests.isEmpty()) assertTrue(f.a.proxy.urls.isEmpty()) } finally { f.close() } } private class UiFixture(val test: TestScope) { val a = ProfilePlayerServicesTest.Fixture(test, "A") val b = ProfilePlayerServicesTest.Fixture(test, "B") val current = mutableStateOf(a.service) val chapter = mutableStateOf(10L) val visible = mutableStateOf(true) lateinit var reader: ProfilePlayerServices.Reader val scene = ui { ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) { if (visible.value) { val binding = rememberPlayerServices(current.value, chapter.value) SideEffect { reader = binding } } } } init { pump() } fun show(value: Boolean) { ui { visible.value = value }; pump() } fun pump() = ui { repeat(3) { test.testScheduler.runCurrent() scene.render(test.testScheduler.currentTime * 1_000_000).close() test.testScheduler.runCurrent() } } fun ui(block: () -> T): T = onUi(block) suspend fun close() { ui { scene.close() }; a.close(); b.close() } } private companion object { fun onUi(block: () -> T): T { if (SwingUtilities.isEventDispatchThread()) return block() val task = FutureTask(block) SwingUtilities.invokeAndWait(task) return task.get() } } }