ProfileSpeechServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tts/ProfileSpeechServiceTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.tts45import kotlin.test.Test6import kotlin.test.assertEquals7import kotlin.test.assertFailsWith8import kotlin.test.assertFalse9import kotlin.test.assertTrue10import kotlinx.coroutines.CancellationException11import kotlinx.coroutines.CompletableDeferred12import kotlinx.coroutines.CoroutineScope13import kotlinx.coroutines.NonCancellable14import kotlinx.coroutines.SupervisorJob15import kotlinx.coroutines.async16import kotlinx.coroutines.awaitCancellation17import kotlinx.coroutines.cancelAndJoin18import kotlinx.coroutines.test.StandardTestDispatcher19import kotlinx.coroutines.test.TestScope20import kotlinx.coroutines.test.runCurrent21import kotlinx.coroutines.test.runTest22import kotlinx.coroutines.withContext2324class ProfileSpeechServiceTest {25 @Test fun completedUtteranceCleansUpAndExpiresRetainedProgress() = runTest {26 val f = Fixture(this)27 var progress = 028 f.native.speech = { f.native.progress?.invoke(0, 2) }29 try {30 f.service.speak("First", TextToSpeechRequest()) { _, _ -> progress++ }31 assertEquals(listOf("speak:First", "stop"), f.native.events)32 assertEquals(1, progress)33 f.native.progress?.invoke(2, 4)34 assertEquals(1, progress)35 assertEquals(listOf("voice"), f.service.voices(null))36 } finally { f.close() }37 }3839 @Test fun canceledCallerWaitsForNativeCleanup() = runTest {40 val f = Fixture(this)41 val release = CompletableDeferred<Unit>()42 f.native.stopping = { release.await() }43 try {44 val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }45 runCurrent()46 call.cancel()47 runCurrent()48 assertFalse(call.isCompleted)49 assertEquals(listOf("speak:First", "stop"), f.native.events)50 release.complete(Unit)51 call.join()52 assertTrue(call.isCancelled)53 } finally { release.complete(Unit); f.close() }54 }5556 @Test fun readerRetirementWaitsBeforeReplacementCanSpeak() = runTest {57 val f = Fixture(this)58 val release = CompletableDeferred<Unit>()59 f.native.stopping = { release.await() }60 try {61 val first = f.service.reader()62 val second = f.service.reader()63 val oldCall = async { first.speak("Old", TextToSpeechRequest()) { _, _ -> } }64 runCurrent()65 first.retire()66 val replacement = async { second.speak("New", TextToSpeechRequest()) { _, _ -> } }67 runCurrent()68 assertEquals(listOf("Old"), f.native.spoken)69 assertFalse(oldCall.isCompleted)70 assertFailsWith<CancellationException> { first.stop() }71 release.complete(Unit)72 runCurrent()73 assertEquals(listOf("Old", "New"), f.native.spoken)74 oldCall.join()75 replacement.cancelAndJoin()76 } finally { release.complete(Unit); f.close() }77 }7879 @Test fun oldReadersStopCannotInterruptAnotherReader() = runTest {80 val f = Fixture(this)81 try {82 val old = f.service.reader()83 val current = f.service.reader()84 val call = async { current.speak("Current", TextToSpeechRequest()) { _, _ -> } }85 runCurrent()86 old.stop()87 assertTrue(call.isActive)88 assertEquals(0, f.native.stops)89 current.stop()90 call.join()91 assertTrue(call.isCancelled)92 assertEquals(1, f.native.stops)93 } finally { f.close() }94 }9596 @Test fun queuedVoicesDoNotAccessNativeEngineUntilUtteranceCleansUp() = runTest {97 val f = Fixture(this)98 try {99 val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }100 runCurrent()101 val voices = async { f.service.voices(null) }102 runCurrent()103 assertEquals(0, f.native.voiceReads)104 call.cancelAndJoin()105 assertEquals(listOf("voice"), voices.await())106 assertEquals(listOf("speak:First", "stop", "voices"), f.native.events)107 } finally { f.close() }108 }109110 @Test fun retiringStatusRejectsCallsAndProgressBeforeScopeCancellation() = runTest {111 val f = Fixture(this)112 var progress = 0113 try {114 val reader = f.service.reader()115 val call = async { reader.speak("First", TextToSpeechRequest()) { _, _ -> progress++ } }116 runCurrent()117 f.open = false118 f.native.progress?.invoke(0, 3)119 assertEquals(0, progress)120 assertTrue(f.owner.isActive)121 assertFailsWith<CancellationException> { reader.voices(null) }122 assertFailsWith<CancellationException> { f.service.speak("Late", TextToSpeechRequest()) { _, _ -> } }123 assertFailsWith<CancellationException> { f.service.reader() }124 assertEquals(listOf("First"), f.native.spoken)125 call.cancelAndJoin()126 } finally { f.close() }127 }128129 @Test fun closeJoinsCleanupThenReleasesNativeEngineAndPreservesParent() = runTest {130 val f = Fixture(this)131 val release = CompletableDeferred<Unit>()132 f.native.stopping = { release.await() }133 try {134 val call = async { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }135 runCurrent()136 val close = async { f.service.closeAndJoin() }137 runCurrent()138 assertFalse(close.isCompleted)139 assertEquals(0, f.native.releases)140 assertFailsWith<CancellationException> { f.service.voices(null) }141 release.complete(Unit)142 close.await()143 call.join()144 f.service.closeAndJoin()145 assertEquals(listOf("speak:First", "stop", "release"), f.native.events)146 assertTrue(f.owner.isActive)147 } finally { release.complete(Unit); f.close() }148 }149150 @Test fun canceledCloseCallerStillJoinsEngineRelease() = runTest {151 val f = Fixture(this)152 val release = CompletableDeferred<Unit>()153 f.native.releasing = { release.await() }154 try {155 val close = async { f.service.closeAndJoin() }156 runCurrent()157 close.cancel()158 runCurrent()159 assertFalse(close.isCompleted)160 release.complete(Unit)161 close.join()162 assertEquals(1, f.native.releases)163 f.service.closeAndJoin()164 assertEquals(1, f.native.releases)165 } finally { release.complete(Unit); f.close() }166 }167168 @Test fun failedEngineReleaseRetainsCleanupForRetry() = runTest {169 val f = Fixture(this)170 f.native.releasing = { if (f.native.releases == 1) error("shutdown failed") }171 try {172 assertFailsWith<IllegalStateException> { f.service.closeAndJoin() }173 assertFailsWith<CancellationException> { f.service.voices(null) }174 f.service.closeAndJoin()175 f.service.closeAndJoin()176 assertEquals(2, f.native.releases)177 assertTrue(f.owner.isActive)178 } finally { f.close() }179 }180181 @Test fun failedStopMustBeRetriedBeforeAllocatingAnotherUtterance() = runTest {182 val f = Fixture(this)183 f.native.speech = { }184 f.native.stopping = { if (f.native.stops < 3) error("native stop failed") }185 try {186 assertFailsWith<IllegalStateException> { f.service.speak("First", TextToSpeechRequest()) { _, _ -> } }187 assertFailsWith<IllegalStateException> { f.service.speak("Blocked", TextToSpeechRequest()) { _, _ -> } }188 assertEquals(listOf("First"), f.native.spoken)189 f.service.speak("Next", TextToSpeechRequest()) { _, _ -> }190 assertEquals(listOf("speak:First", "stop", "stop", "stop", "speak:Next", "stop"), f.native.events)191 } finally { f.close() }192 }193194 @Test fun canceledVoiceLookupJoinsItsInitializationFinalizer() = runTest {195 val f = Fixture(this)196 val release = CompletableDeferred<Unit>()197 f.native.voiceLookup = {198 try { awaitCancellation() }199 finally { withContext(NonCancellable) { release.await() } }200 }201 try {202 val call = async { f.service.voices(null) }203 runCurrent()204 val close = async { f.service.closeAndJoin() }205 runCurrent()206 assertFalse(call.isCompleted)207 assertFalse(close.isCompleted)208 assertEquals(0, f.native.releases)209 release.complete(Unit)210 close.await()211 call.join()212 assertEquals(1, f.native.releases)213 } finally { release.complete(Unit); f.close() }214 }215216 @Test fun independentOwnersRetainTheirOwnEnginesAndCallbacks() = runTest {217 val a = Fixture(this)218 val b = Fixture(this)219 var aProgress = 0220 var bProgress = 0221 try {222 val old = async { a.service.speak("A", TextToSpeechRequest()) { _, _ -> aProgress++ } }223 val current = async { b.service.speak("B", TextToSpeechRequest()) { _, _ -> bProgress++ } }224 runCurrent()225 a.service.closeAndJoin()226 a.native.progress?.invoke(0, 1)227 b.native.progress?.invoke(0, 1)228 assertEquals(0, aProgress)229 assertEquals(1, bProgress)230 assertTrue(current.isActive)231 assertEquals(0, b.native.stops)232 old.join()233 current.cancelAndJoin()234 } finally { a.close(); b.close() }235 }236237 private class Fixture(test: TestScope) {238 val owner = SupervisorJob()239 var open = true240 val native = Native()241 val service = ProfileSpeechService(native, CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))) { open }242 suspend fun close() { service.closeAndJoin(); owner.cancelAndJoin() }243 }244245 private class Native : TextToSpeechService {246 val events = mutableListOf<String>()247 val spoken = mutableListOf<String>()248 var progress: ((Int, Int) -> Unit)? = null249 var stops = 0250 var releases = 0251 var voiceReads = 0252 var speech: suspend () -> Unit = { awaitCancellation() }253 var stopping: suspend () -> Unit = { }254 var releasing: suspend () -> Unit = { }255 var voiceLookup: suspend () -> List<String> = { listOf("voice") }256 override suspend fun voices(language: String?): List<String> {257 voiceReads++258 events += "voices"259 return voiceLookup()260 }261 override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {262 events += "speak:$text"263 spoken += text264 progress = onProgress265 speech()266 }267 override suspend fun stop() { stops++; events += "stop"; stopping() }268 override suspend fun closeAndJoin() { releases++; events += "release"; releasing() }269 }270}271