@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.media.player import eu.friedcutlet.yokan.database.DbSettings import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin 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 MpvCommandBlockingTest { @Test fun retirementWaitsForBlockingNativeCaptureBeforeDeletingFileAndReleasingPlayer() = runTest { val entered = CountDownLatch(1); val finish = CountDownLatch(1) val player = MediaPlayerInitializationTest.RecordingMpvPlayer() val controller = MpvMediaPlayerController(player, NoopMediaStreamProxy, Dispatchers.IO) val f = ProfilePlayerServicesTest.Fixture(this, dispatcher = Dispatchers.IO, factory = { _, _ -> controller }) val published = CompletableDeferred() val lifetime = async { f.reader.withController(f.reader.configuration(DbSettings())) { published.complete(Unit); awaitCancellation() } } player.onCommand = { entered.countDown(); check(finish.await(10, TimeUnit.SECONDS)) assertTrue(f.files.deletions.isEmpty()); assertEquals(0, player.releaseCount) f.files.bytes[f.files.writes.single()] = byteArrayOf(1) } val capture = async { published.await(); 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(capture.isCompleted) assertTrue(f.files.deletions.isEmpty()); assertEquals(0, player.releaseCount) finish.countDown(); close.await() assertFailsWith { capture.await() } assertTrue(f.files.bytes.isEmpty()); assertEquals(f.files.writes, f.files.deletions) assertEquals(1, player.releaseCount); assertTrue(f.owner.isActive) } finally { finish.countDown(); capture.cancelAndJoin(); lifetime.cancelAndJoin(); f.close(); controller.releaseAndJoin() } } }