@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) package eu.friedcutlet.yokan.services.tts import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertFalse import kotlin.test.assertTrue import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitCancellation import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext class ProfileSpeechServiceTest { @Test fun completedUtteranceCleansUpAndExpiresRetainedProgress() = runTest { val f = Fixture(this) var progress = 0 f.native.speech = { f.native.progress?.invoke(0, 2) } try { f.service.speak("First", TextToSpeechRequest()) { _, _ -> progress++ } assertEquals(listOf("speak:First", "stop"), f.native.events) assertEquals(1, progress) f.native.progress?.invoke(2, 4) assertEquals(1, progress) assertEquals(listOf("voice"), f.service.voices(null)) } finally { f.close() } } @Test fun canceledCallerWaitsForNativeCleanup() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.native.stopping = { release.await() } try { val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } } runCurrent() call.cancel() runCurrent() assertFalse(call.isCompleted) assertEquals(listOf("speak:First", "stop"), f.native.events) release.complete(Unit) call.join() assertTrue(call.isCancelled) } finally { release.complete(Unit); f.close() } } @Test fun readerRetirementWaitsBeforeReplacementCanSpeak() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.native.stopping = { release.await() } try { val first = f.service.reader() val second = f.service.reader() val oldCall = async { first.speak("Old", TextToSpeechRequest()) { _, _ -> } } runCurrent() first.retire() val replacement = async { second.speak("New", TextToSpeechRequest()) { _, _ -> } } runCurrent() assertEquals(listOf("Old"), f.native.spoken) assertFalse(oldCall.isCompleted) assertFailsWith { first.stop() } release.complete(Unit) runCurrent() assertEquals(listOf("Old", "New"), f.native.spoken) oldCall.join() replacement.cancelAndJoin() } finally { release.complete(Unit); f.close() } } @Test fun oldReadersStopCannotInterruptAnotherReader() = runTest { val f = Fixture(this) try { val old = f.service.reader() val current = f.service.reader() val call = async { current.speak("Current", TextToSpeechRequest()) { _, _ -> } } runCurrent() old.stop() assertTrue(call.isActive) assertEquals(0, f.native.stops) current.stop() call.join() assertTrue(call.isCancelled) assertEquals(1, f.native.stops) } finally { f.close() } } @Test fun queuedVoicesDoNotAccessNativeEngineUntilUtteranceCleansUp() = runTest { val f = Fixture(this) try { val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } } runCurrent() val voices = async { f.service.voices(null) } runCurrent() assertEquals(0, f.native.voiceReads) call.cancelAndJoin() assertEquals(listOf("voice"), voices.await()) assertEquals(listOf("speak:First", "stop", "voices"), f.native.events) } finally { f.close() } } @Test fun retiringStatusRejectsCallsAndProgressBeforeScopeCancellation() = runTest { val f = Fixture(this) var progress = 0 try { val reader = f.service.reader() val call = async { reader.speak("First", TextToSpeechRequest()) { _, _ -> progress++ } } runCurrent() f.open = false f.native.progress?.invoke(0, 3) assertEquals(0, progress) assertTrue(f.owner.isActive) assertFailsWith { reader.voices(null) } assertFailsWith { f.service.speak("Late", TextToSpeechRequest()) { _, _ -> } } assertFailsWith { f.service.reader() } assertEquals(listOf("First"), f.native.spoken) call.cancelAndJoin() } finally { f.close() } } @Test fun closeJoinsCleanupThenReleasesNativeEngineAndPreservesParent() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.native.stopping = { release.await() } try { val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } } runCurrent() val close = async { f.service.closeAndJoin() } runCurrent() assertFalse(close.isCompleted) assertEquals(0, f.native.releases) assertFailsWith { f.service.voices(null) } release.complete(Unit) close.await() call.join() f.service.closeAndJoin() assertEquals(listOf("speak:First", "stop", "release"), f.native.events) assertTrue(f.owner.isActive) } finally { release.complete(Unit); f.close() } } @Test fun canceledCloseCallerStillJoinsEngineRelease() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.native.releasing = { release.await() } try { val close = async { f.service.closeAndJoin() } runCurrent() close.cancel() runCurrent() assertFalse(close.isCompleted) release.complete(Unit) close.join() assertEquals(1, f.native.releases) f.service.closeAndJoin() assertEquals(1, f.native.releases) } finally { release.complete(Unit); f.close() } } @Test fun failedEngineReleaseRetainsCleanupForRetry() = runTest { val f = Fixture(this) f.native.releasing = { if (f.native.releases == 1) error("shutdown failed") } try { assertFailsWith { f.service.closeAndJoin() } assertFailsWith { f.service.voices(null) } f.service.closeAndJoin() f.service.closeAndJoin() assertEquals(2, f.native.releases) assertTrue(f.owner.isActive) } finally { f.close() } } @Test fun failedStopMustBeRetriedBeforeAllocatingAnotherUtterance() = runTest { val f = Fixture(this) f.native.speech = { } f.native.stopping = { if (f.native.stops < 3) error("native stop failed") } try { assertFailsWith { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } } assertFailsWith { f.service.speak("Blocked", TextToSpeechRequest()) { _, _ -> } } assertEquals(listOf("First"), f.native.spoken) f.service.speak("Next", TextToSpeechRequest()) { _, _ -> } assertEquals(listOf("speak:First", "stop", "stop", "stop", "speak:Next", "stop"), f.native.events) } finally { f.close() } } @Test fun canceledVoiceLookupJoinsItsInitializationFinalizer() = runTest { val f = Fixture(this) val release = CompletableDeferred() f.native.voiceLookup = { try { awaitCancellation() } finally { withContext(NonCancellable) { release.await() } } } try { val call = async { f.service.voices(null) } runCurrent() val close = async { f.service.closeAndJoin() } runCurrent() assertFalse(call.isCompleted) assertFalse(close.isCompleted) assertEquals(0, f.native.releases) release.complete(Unit) close.await() call.join() assertEquals(1, f.native.releases) } finally { release.complete(Unit); f.close() } } @Test fun independentOwnersRetainTheirOwnEnginesAndCallbacks() = runTest { val a = Fixture(this) val b = Fixture(this) var aProgress = 0 var bProgress = 0 try { val old = async { a.service.speak("A", TextToSpeechRequest()) { _, _ -> aProgress++ } } val current = async { b.service.speak("B", TextToSpeechRequest()) { _, _ -> bProgress++ } } runCurrent() a.service.closeAndJoin() a.native.progress?.invoke(0, 1) b.native.progress?.invoke(0, 1) assertEquals(0, aProgress) assertEquals(1, bProgress) assertTrue(current.isActive) assertEquals(0, b.native.stops) old.join() current.cancelAndJoin() } finally { a.close(); b.close() } } private class Fixture(test: TestScope) { val owner = SupervisorJob() var open = true val native = Native() val service = ProfileSpeechService(native, CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))) { open } suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() } } private class Native : TextToSpeechService { val events = mutableListOf() val spoken = mutableListOf() var progress: ((Int, Int) -> Unit)? = null var stops = 0 var releases = 0 var voiceReads = 0 var speech: suspend () -> Unit = { awaitCancellation() } var stopping: suspend () -> Unit = { } var releasing: suspend () -> Unit = { } var voiceLookup: suspend () -> List = { listOf("voice") } override suspend fun voices(language: String?): List { voiceReads++ events += "voices" return voiceLookup() } override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) { events += "speak:$text" spoken += text progress = onProgress speech() } override suspend fun stop() { stops++; events += "stop"; stopping() } override suspend fun closeAndJoin() { releases++; events += "release"; releasing() } } }