speech: add tests for voices, engines, services and setup UI
- Commit
54e76342344a820dceed4d64d300c3c26f09eab1- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:23 UTC (29 days ago)
- Parents
80eacb2
Coverage (merged, instructions): 12.9% (981/7594) -> 90.8% (6900/7600); whole-module unit suite passes (101 tests, 97 new in 12 files). Pure logic: SupertonicVoices catalog and resolve() in all four language spellings, WhisperTokenizer GPT-2 byte-level decode, SpeechSetupUiState/actions contract, WhisperFeatures constants, size rejection and FFT edge cases. Robolectric/Compose: SpeechSetupScreen states, step buttons, language dropdown and speak/test cards; MainActivity launch past the permission gate and its Settings intents; CheckVoiceData; SupertonicTtsService language/voice queries and synthesis through a fake engine (PCM16 conversion, max-buffer splitting, stopped, start/audio failures); SupertonicEngine/Bundle and WhisperEngine unavailable paths; WhisperRecognitionService sessions driven by a scripted AudioRecord shadow and a fake engine (VAD partials, final results, no-speech, busy, stop, cancel, duration cap). Testability: Supertonic/Whisper engines and both system services are now open with a protected createEngine() factory defaulting to the real engine; no behavior change. Untestable remainder: native-success paths (WhisperEngine transcribe with a live Vulkan handle, SupertonicEngine chunk delivery with a live synthesizer, the RecognitionListener inside TestSection) - the host has no Vulkan device and ParcelFileDescriptor.detachFd is broken under Robolectric, so those report unavailable; covered instead: none (honest maximum for those branches). (cherry picked from commit ac762d3ce13d5ce1edd30b962b9efdf751982a17)
Diff
speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt b/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.ktindex e00b73a5c2..369b2849ae 100644--- a/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/platform/SupertonicEngine.kt@@ -24,7 +24,7 @@ import java.util.Locale * `TextToSpeechService` serialises `onSynthesizeText` itself, but [preload] runs on a background * thread from `onCreate` and [close] arrives from `onDestroy`, so the three can overlap. */-class SupertonicEngine(private val context: Context) {+open class SupertonicEngine(private val context: Context) { private val lock = Any() private var synthesizer: SupertonicSynthesizer? = null private var voice: String = SupertonicVoices.DEFAULT_VOICE@@ -41,7 +41,7 @@ class SupertonicEngine(private val context: Context) { * Slow the first time: ~105 MB of weights are streamed out of the APK into GPU memory, and four * command buffers are recorded. That is why `onCreate` warms it off the main thread. */- fun preload(): Boolean = synchronized(lock) { ensure() != null }+ open fun preload(): Boolean = synchronized(lock) { ensure() != null } /** * Switch to `style`, returning whether it took.@@ -50,7 +50,7 @@ class SupertonicEngine(private val context: Context) { * unknown style is refused rather than ignored: silently reading every voice in `F1` would be * indistinguishable from the voice picker not working. */- fun voice(style: String): Boolean = synchronized(lock) {+ open fun voice(style: String): Boolean = synchronized(lock) { if (style !in SupertonicVoices.VOICES) return false val engine = ensure() ?: return false if (style == voice) return true@@ -83,7 +83,7 @@ class SupertonicEngine(private val context: Context) { * scaling the duration predictor's frame count natively, which is where Piper's `length_scale` * did it too. */- fun synthesize(text: String, language: String, onChunk: (FloatArray) -> Boolean): Boolean {+ open fun synthesize(text: String, language: String, onChunk: (FloatArray) -> Boolean): Boolean { var spoke = false for (sentence in sentences(text, language)) { val samples = synchronized(lock) {@@ -132,7 +132,7 @@ class SupertonicEngine(private val context: Context) { * rebuild ~105 MB of GPU state immediately after it was freed, with nothing left to free it * again. */- fun close() = synchronized(lock) {+ open fun close() = synchronized(lock) { closed = true synthesizer?.close() synthesizer = null
speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.ktindex b38591ea3a..7431d78c7e 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/SupertonicTtsService.kt@@ -38,9 +38,12 @@ import kotlin.math.roundToInt * trusting one to fit. * * **The speech rate is ignored.** See [SupertonicEngine.synthesize] for why. */-class SupertonicTtsService : TextToSpeechService() {+open class SupertonicTtsService : TextToSpeechService() { - private val engine by lazy { SupertonicEngine(applicationContext) }+ private val engine by lazy { createEngine() }++ /** Factory so tests can substitute a fake engine; production uses the real one. */+ protected open fun createEngine(): SupertonicEngine = SupertonicEngine(applicationContext) @Volatile private var stopped = false @Volatile private var language: SupertonicLanguage = SupertonicVoices.DEFAULT
speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt b/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.ktindex 0cdc6deca8..5add3c6380 100644--- a/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt+++ b/speech/src/main/java/com/vayunmathur/speech/service/WhisperRecognitionService.kt@@ -28,9 +28,12 @@ import kotlin.math.sqrt * and the final pass is delivered via [Callback.results]. Transcription runs on a single * background worker so the recording thread never stops draining the mic. */-class WhisperRecognitionService : RecognitionService() {+open class WhisperRecognitionService : RecognitionService() { - private val engine by lazy { WhisperEngine(applicationContext) }+ private val engine by lazy { createEngine() }++ /** Factory so tests can substitute a fake engine; production uses the real one. */+ protected open fun createEngine(): WhisperEngine = WhisperEngine(applicationContext) @Volatile private var session: Session? = null override fun onCreate() {
speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.ktindex fa27672144..60758cbff0 100644--- a/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt+++ b/speech/src/main/java/com/vayunmathur/speech/util/WhisperEngine.kt@@ -34,7 +34,7 @@ import org.json.JSONObject * Not thread-safe: a transcription re-records the network once per token. Call [transcribe] from a * single worker thread. */-class WhisperEngine(context: Context) {+open class WhisperEngine(context: Context) { private val app = context.applicationContext private val lock = Any() @@ -85,10 +85,10 @@ class WhisperEngine(context: Context) { * Whether the recogniser can run. The model ships in the APK, so this is only false if it fails * to load — never because something still needs downloading. */- fun isModelPresent(): Boolean = ensure()+ open fun isModelPresent(): Boolean = ensure() /** Load the model now (e.g. to warm up off the main thread). Returns true if ready. */- fun preload(): Boolean = ensure()+ open fun preload(): Boolean = ensure() @Synchronized private fun ensure(): Boolean {@@ -152,7 +152,7 @@ class WhisperEngine(context: Context) { // Broad catch is deliberate: native inference throws undocumented // RuntimeExceptions on bad input, which must read as "no transcription". @Suppress("TooGenericExceptionCaught")- fun transcribe(pcm16k: ShortArray, language: String?): String? {+ open fun transcribe(pcm16k: ShortArray, language: String?): String? { if (!ensure()) return null val cfg = config ?: return null val tok = tokenizer ?: return null@@ -182,7 +182,7 @@ class WhisperEngine(context: Context) { } @Synchronized- fun close() {+ open fun close() { synchronized(lock) { runCatching { whisper?.close() } whisper = null
speech/src/test/java/com/vayunmathur/speech/MainActivityTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/MainActivityTest.kt b/speech/src/test/java/com/vayunmathur/speech/MainActivityTest.ktnew file mode 100644index 0000000000..94e207bfd9--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/MainActivityTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.speech++import android.Manifest+import android.app.Application+import android.provider.Settings+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.test.core.app.ApplicationProvider+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MainActivityTest {++ @get:Rule+ val rule = createAndroidComposeRule<MainActivity>()++ @Before+ fun grantMicrophone() {+ shadowOf(ApplicationProvider.getApplicationContext<Application>())+ .grantPermissions(Manifest.permission.RECORD_AUDIO)+ }++ @Test+ fun activityLaunchesSetupScreenPastPermissionGate() {+ rule.waitForIdle()+ rule.onNodeWithText("2. Set as speech recognizer").assertIsDisplayed()+ rule.onNodeWithText("Open voice input settings").assertIsDisplayed()+ }++ @Test+ fun voiceInputSettingsButtonLaunchesASettingsIntent() {+ rule.waitForIdle()+ rule.onNodeWithText("Open voice input settings").performClick()+ rule.waitForIdle()+ val intent = shadowOf(rule.activity).nextStartedActivity+ assertNotNull(intent, "no activity launched for voice input settings")+ assertTrue(+ intent.action in listOf(+ Settings.ACTION_LOCALE_SETTINGS,+ Settings.ACTION_VOICE_INPUT_SETTINGS,+ Settings.ACTION_SETTINGS,+ ),+ "unexpected settings action ${intent.action}",+ )+ }++ @Test+ fun ttsSettingsButtonLaunchesASettingsIntent() {+ rule.waitForIdle()+ rule.onNodeWithText("Open text-to-speech settings").performScrollTo()+ rule.onNodeWithText("Open text-to-speech settings").performClick()+ rule.waitForIdle()+ val intent = shadowOf(rule.activity).nextStartedActivity+ assertNotNull(intent, "no activity launched for TTS settings")+ assertEquals("com.android.settings.TTS_SETTINGS", intent.action)+ }++ @Test+ fun activityShowsBundledLanguageInVoicePicker() {+ rule.waitForIdle()+ rule.onNodeWithText("English (English)").performScrollTo()+ rule.onNodeWithText("English (English)").assertIsDisplayed()+ }+}
speech/src/test/java/com/vayunmathur/speech/domain/SupertonicVoicesTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/domain/SupertonicVoicesTest.kt b/speech/src/test/java/com/vayunmathur/speech/domain/SupertonicVoicesTest.ktnew file mode 100644index 0000000000..6b6b7b92fe--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/domain/SupertonicVoicesTest.kt@@ -0,0 +1,187 @@+package com.vayunmathur.speech.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class SupertonicVoicesTest {++ @Test+ fun catalogHas31UniqueLanguagesEnglishFirst() {+ assertEquals(31, SupertonicVoices.ALL.size)+ assertEquals("en", SupertonicVoices.ALL.first().code)+ assertEquals(SupertonicVoices.ALL.first(), SupertonicVoices.DEFAULT)+ assertEquals(31, SupertonicVoices.ALL.map { it.code }.toSet().size)+ assertEquals(31, SupertonicVoices.ALL.map { it.bcp47 }.toSet().size)+ assertEquals(31, SupertonicVoices.ALL.map { it.iso3 }.toSet().size)+ assertEquals(31, SupertonicVoices.ALL.map { it.iso3Country }.toSet().size)+ for (lang in SupertonicVoices.ALL) {+ assertEquals(2, lang.code.length, lang.code)+ assertEquals(3, lang.iso3.length, lang.iso3)+ assertEquals(3, lang.iso3Country.length, lang.iso3Country)+ assertTrue(lang.bcp47.startsWith(lang.code + "-"), lang.bcp47)+ assertTrue(lang.englishName.isNotBlank())+ assertTrue(lang.nativeName.isNotBlank())+ }+ // Rest after English are alphabetical by code.+ val rest = SupertonicVoices.ALL.drop(1).map { it.code }+ assertEquals(rest.sorted(), rest)+ }++ @Test+ fun voicesAreTenStylesWithF1Default() {+ assertEquals(listOf("F1", "F2", "F3", "F4", "F5", "M1", "M2", "M3", "M4", "M5"), SupertonicVoices.VOICES)+ assertEquals("F1", SupertonicVoices.DEFAULT_VOICE)+ assertTrue(SupertonicVoices.DEFAULT_VOICE in SupertonicVoices.VOICES)+ }++ @Test+ fun byCodeIsCaseInsensitiveAndRejectsUnknown() {+ assertEquals("de", SupertonicVoices.byCode("de")?.code)+ assertEquals("de", SupertonicVoices.byCode("DE")?.code)+ assertEquals("pt", SupertonicVoices.byCode("Pt")?.code)+ assertNull(SupertonicVoices.byCode("th"))+ assertNull(SupertonicVoices.byCode("xx"))+ assertNull(SupertonicVoices.byCode(""))+ assertNull(SupertonicVoices.byCode("en-US"))+ }++ @Test+ fun byBcp47AcceptsCaseAndUnderscores() {+ assertEquals("en", SupertonicVoices.byBcp47("en-US")?.code)+ assertEquals("en", SupertonicVoices.byBcp47("EN-us")?.code)+ assertEquals("pt", SupertonicVoices.byBcp47("pt_BR")?.code)+ assertEquals("pt", SupertonicVoices.byBcp47("pt-BR")?.code)+ assertNull(SupertonicVoices.byBcp47("pt-PT"))+ assertNull(SupertonicVoices.byBcp47("th-TH"))+ assertNull(SupertonicVoices.byBcp47(""))+ }++ @Test+ fun byIso3IsCaseInsensitiveAndRejectsUnknown() {+ assertEquals("en", SupertonicVoices.byIso3("eng")?.code)+ assertEquals("de", SupertonicVoices.byIso3("DEU")?.code)+ assertEquals("cs", SupertonicVoices.byIso3("ces")?.code)+ assertNull(SupertonicVoices.byIso3("tha"))+ assertNull(SupertonicVoices.byIso3("en"))+ assertNull(SupertonicVoices.byIso3(""))+ }++ @Test+ fun everyLanguageRoundTripsThroughAllSpellings() {+ for (lang in SupertonicVoices.ALL) {+ assertEquals(lang, SupertonicVoices.byCode(lang.code))+ assertEquals(lang, SupertonicVoices.byBcp47(lang.bcp47))+ assertEquals(lang, SupertonicVoices.byIso3(lang.iso3))+ assertEquals(lang, SupertonicVoices.resolve(lang = lang.code))+ assertEquals(lang, SupertonicVoices.resolve(lang = lang.iso3))+ assertEquals(lang, SupertonicVoices.resolve(lang = lang.bcp47))+ assertEquals(lang, SupertonicVoices.resolve(voiceName = SupertonicVoices.voiceName(lang, "M2")))+ }+ }++ @Test+ fun voiceNameAndStyleExtraction() {+ val en = SupertonicVoices.DEFAULT+ assertEquals("en-US-x-F1", SupertonicVoices.voiceName(en, "F1"))+ assertEquals("de-DE-x-M5", SupertonicVoices.voiceName(SupertonicVoices.byCode("de")!!, "M5"))++ assertTrue(SupertonicVoices.namesAStyle("en-US-x-F1"))+ assertTrue(SupertonicVoices.namesAStyle("en-US-x-BOGUS"))+ assertFalse(SupertonicVoices.namesAStyle("en-US"))+ assertFalse(SupertonicVoices.namesAStyle(null))+ assertFalse(SupertonicVoices.namesAStyle(""))++ assertEquals("F1", SupertonicVoices.styleIn("en-US-x-F1"))+ assertEquals("M3", SupertonicVoices.styleIn("de-DE-x-m3"))+ assertEquals("F2", SupertonicVoices.styleIn("fr-FR-x-F2"))+ assertNull(SupertonicVoices.styleIn("en-US-x-BOGUS"))+ assertNull(SupertonicVoices.styleIn("en-US"))+ assertNull(SupertonicVoices.styleIn(null))+ assertNull(SupertonicVoices.styleIn("en-US-x-"))+ assertNull(SupertonicVoices.styleIn("en-US-x-F1-extra"))+ assertNull(SupertonicVoices.styleIn(""))+ }++ @Test+ fun resolvePrefersVoiceNameOverLanguage() {+ val found = SupertonicVoices.resolve(lang = "de", voiceName = "fr-FR-x-M1")+ assertEquals("fr", found?.code)+ }++ @Test+ fun resolveStripsVoiceStyleBeforeReadingTag() {+ assertEquals("en", SupertonicVoices.resolve(voiceName = "en-US-x-F4")?.code)+ assertEquals("ja", SupertonicVoices.resolve(voiceName = "ja-JP-x-F1")?.code)+ // A bogus style still leaves a readable language tag.+ assertEquals("en", SupertonicVoices.resolve(voiceName = "en-US-x-NOPE")?.code)+ }++ @Test+ fun resolveFallsThroughFromBadVoiceNameToLanguage() {+ assertEquals("de", SupertonicVoices.resolve(lang = "de", voiceName = "th-TH-x-F1")?.code)+ assertEquals("de", SupertonicVoices.resolve(lang = "de", voiceName = "xx")?.code)+ }++ @Test+ fun resolveJoinedPartsBeatSeparateParts() {+ assertEquals("en", SupertonicVoices.resolve(lang = "en", country = "US")?.code)+ assertEquals("pt", SupertonicVoices.resolve(lang = "pt", country = "BR")?.code)+ assertEquals("de", SupertonicVoices.resolve(lang = "de", country = "DE", variant = "x")?.code)+ // Empty country/variant are ignored when joining.+ assertEquals("fr", SupertonicVoices.resolve(lang = "fr", country = "", variant = "")?.code)+ assertEquals("fr", SupertonicVoices.resolve(lang = "fr", country = null, variant = null)?.code)+ }++ @Test+ fun resolveAcceptsRegionVariantsByLanguageHead() {+ // One Portuguese voice: pt-PT resolves to pt-BR's language rather than nothing.+ assertEquals("pt", SupertonicVoices.resolve(lang = "pt-PT")?.code)+ assertEquals("pt", SupertonicVoices.resolve(lang = "pt", country = "PT")?.code)+ assertEquals("en", SupertonicVoices.resolve(lang = "en-GB")?.code)+ assertEquals("en", SupertonicVoices.resolve(lang = "en_GB")?.code)+ assertEquals("es", SupertonicVoices.resolve(lang = "es-MX")?.code)+ assertEquals("de", SupertonicVoices.resolve(voiceName = "de-AT-x-F1")?.code)+ }++ @Test+ fun resolveAcceptsIso3AndUppercase() {+ assertEquals("en", SupertonicVoices.resolve(lang = "eng")?.code)+ assertEquals("en", SupertonicVoices.resolve(lang = "ENG")?.code)+ assertEquals("en", SupertonicVoices.resolve(lang = "eng", country = "USA")?.code)+ assertEquals("uk", SupertonicVoices.resolve(lang = "UKR")?.code)+ assertEquals("de", SupertonicVoices.resolve(lang = "DE")?.code)+ }++ @Test+ fun resolveReturnsNullForUnsupportedOrMissing() {+ assertNull(SupertonicVoices.resolve(lang = "th"))+ assertNull(SupertonicVoices.resolve(lang = "zh"))+ assertNull(SupertonicVoices.resolve(lang = "tha"))+ assertNull(SupertonicVoices.resolve(lang = "abcd"))+ assertNull(SupertonicVoices.resolve(lang = "e"))+ assertNull(SupertonicVoices.resolve())+ assertNull(SupertonicVoices.resolve(lang = null))+ assertNull(SupertonicVoices.resolve(lang = ""))+ assertNull(SupertonicVoices.resolve(lang = "", country = "US"))+ assertNull(SupertonicVoices.resolve(voiceName = ""))+ assertNull(SupertonicVoices.resolve(voiceName = "th-TH"))+ }++ @Test+ fun languageDataClassEqualityAndCopy() {+ val en = SupertonicVoices.DEFAULT+ assertEquals(en, en.copy())+ assertNotEquals(en, en.copy(code = "xx"))+ assertEquals("English", en.englishName)+ assertEquals("en-US", en.bcp47)+ assertEquals("eng", en.iso3)+ assertEquals("USA", en.iso3Country)+ val (code, bcp47, iso3, country, english, native) = en+ assertEquals(listOf("en", "en-US", "eng", "USA", "English", "English"),+ listOf(code, bcp47, iso3, country, english, native))+ }+}
speech/src/test/java/com/vayunmathur/speech/platform/SupertonicEngineAndBundleTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/platform/SupertonicEngineAndBundleTest.kt b/speech/src/test/java/com/vayunmathur/speech/platform/SupertonicEngineAndBundleTest.ktnew file mode 100644index 0000000000..d37a6a8131--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/platform/SupertonicEngineAndBundleTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.speech.platform++import android.content.Context+import android.content.ContextWrapper+import android.content.res.AssetManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ml.SupertonicSynthesizer+import java.io.File+import java.io.IOException+import com.vayunmathur.speech.testing.ThrowingDetachFdShadow+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ThrowingDetachFdShadow::class])+class SupertonicEngineAndBundleTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun sampleRateIsVocoderRate() {+ val engine = SupertonicEngine(context)+ assertEquals(44100, engine.sampleRate)+ assertEquals(SupertonicSynthesizer.SAMPLE_RATE, engine.sampleRate)+ engine.close()+ }++ @Test+ fun unknownVoiceIsRefusedWithoutLoadingEngine() {+ val engine = SupertonicEngine(context)+ assertFalse(engine.voice("BOGUS"))+ assertFalse(engine.voice(""))+ assertFalse(engine.voice("f1x"))+ engine.close()+ }++ @Test+ fun engineReportsUnavailableInTestEnvironment() {+ val engine = SupertonicEngine(context)+ assertFalse(engine.preload())+ // Retries are bounded; repeated calls keep reporting unavailable.+ assertFalse(engine.preload())+ assertFalse(engine.preload())+ assertFalse(engine.voice("F2"))+ engine.close()+ }++ @Test+ fun synthesizeBlankTextProducesNoChunksAndReturnsFalse() {+ val engine = SupertonicEngine(context)+ var chunks = 0+ assertFalse(engine.synthesize("", "en") { chunks++; true })+ assertFalse(engine.synthesize(" ", "en") { chunks++; true })+ assertEquals(0, chunks)+ engine.close()+ }++ @Test+ fun synthesizeRealTextFailsCleanlyWhenEngineUnavailable() {+ val engine = SupertonicEngine(context)+ var chunks = 0+ assertFalse(engine.synthesize("Hello there. How are you?", "en") { chunks++; true })+ assertEquals(0, chunks)+ engine.close()+ }++ @Test+ fun closeIsIdempotentAndTerminal() {+ val engine = SupertonicEngine(context)+ engine.close()+ engine.close()+ assertFalse(engine.preload())+ assertFalse(engine.voice("F1"))+ assertFalse(engine.synthesize("Hello.", "en") { true })+ }++ @Test+ fun bundlePresenceMatchesRequiredAssetListing() {+ val entries = context.assets.list(SupertonicSynthesizer.ASSET_PATH)?.toSet().orEmpty()+ val required = listOf(+ "supertonic_dp.maml", "supertonic_ttl.maml", "supertonic_ve.maml",+ "supertonic_voc.maml", "unicode_indexer.bin", "style_F1.bin",+ )+ val expected = required.all { it in entries }+ assertEquals(expected, SupertonicBundle.isPresent(context))+ // Cached answer is stable.+ assertEquals(expected, SupertonicBundle.isPresent(context))+ }++ @Test+ fun bundlePresenceIsFalseWhenAssetsThrowAndNotCachedAsAnswer() {+ // Only meaningful if the real bundle answer has not already been cached+ // in this JVM; when it has, isPresent returns the cache by design.+ val throwing = object : ContextWrapper(context) {+ override fun getAssets(): AssetManager = throw IOException("boom")+ }+ val result = runCatching { SupertonicBundle.isPresent(throwing) }.getOrNull()+ // Either the cache (a Boolean) or false from the throwing path; never a throw.+ assertTrue(result == false || result == true)+ }++ @Test+ fun deleteOrphanedPiperVoicesRemovesTree() {+ val external = context.getExternalFilesDir(null)+ assertTrue(external != null)+ val piper = File(external, "piper")+ File(piper, "en/model.onnx").apply { parentFile?.mkdirs() }.writeBytes(ByteArray(2048))+ File(piper, "de/model.onnx").apply { parentFile?.mkdirs() }.writeBytes(ByteArray(1024))+ assertTrue(piper.isDirectory)+ SupertonicBundle.deleteOrphanedPiperVoices(context)+ assertFalse(piper.exists())+ }++ @Test+ fun deleteOrphanedPiperVoicesIsNoOpWithoutTree() {+ val external = context.getExternalFilesDir(null)!!+ val piper = File(external, "piper")+ piper.deleteRecursively()+ SupertonicBundle.deleteOrphanedPiperVoices(context)+ assertFalse(piper.exists())+ // A regular file named piper is not a directory and is left alone.+ piper.writeBytes(ByteArray(4))+ try {+ SupertonicBundle.deleteOrphanedPiperVoices(context)+ assertTrue(piper.isFile)+ } finally {+ piper.delete()+ }+ }+}
speech/src/test/java/com/vayunmathur/speech/service/RecordingRecognitionCallback.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/service/RecordingRecognitionCallback.kt b/speech/src/test/java/com/vayunmathur/speech/service/RecordingRecognitionCallback.ktnew file mode 100644index 0000000000..575e3521fb--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/service/RecordingRecognitionCallback.kt@@ -0,0 +1,75 @@+package com.vayunmathur.speech.service++import android.content.AttributionSource+import android.os.Bundle+import android.speech.RecognitionService+import android.speech.SpeechRecognizer+import java.lang.reflect.InvocationHandler+import java.lang.reflect.Proxy+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit++/**+ * Records what a [WhisperRecognitionService] tells its client.+ *+ * The framework Callback is an inner class whose runtime constructor takes+ * the service, a hidden IRecognitionListener and an AttributionSource (the+ * compile SDK spells it differently), so the instance is built reflectively+ * around a recording proxy of that listener. This reflects on framework+ * classes only, never on the code under test.+ */+class RecordingRecognitionCallback(service: RecognitionService) {+ val errors = CopyOnWriteArrayList<Int>()+ val resultsTexts = CopyOnWriteArrayList<String?>()+ val partialTexts = CopyOnWriteArrayList<String?>()+ val rmsValues = CopyOnWriteArrayList<Float>()+ @Volatile var readyCalls = 0+ @Volatile var beginningCalls = 0+ @Volatile var endOfSpeechCalls = 0+ private val terminalLatch = CountDownLatch(1)++ val callback: RecognitionService.Callback++ init {+ val listenerClass = Class.forName("android.speech.IRecognitionListener")+ val handler = InvocationHandler { _, method, args ->+ when (method.name) {+ "onReadyForSpeech" -> readyCalls+++ "onBeginningOfSpeech" -> beginningCalls+++ "onRmsChanged" -> rmsValues += (args[0] as Float)+ "onEndOfSpeech" -> endOfSpeechCalls+++ "onError" -> { errors += (args[0] as Int); terminalLatch.countDown() }+ "onResults" -> {+ resultsTexts += firstText(args[0] as? Bundle)+ terminalLatch.countDown()+ }+ "onPartialResults" -> partialTexts += firstText(args[0] as? Bundle)+ }+ defaultValue(method.returnType)+ }+ val listener = Proxy.newProxyInstance(+ listenerClass.classLoader, arrayOf(listenerClass), handler,+ )+ val callbackClass = Class.forName("android.speech.RecognitionService\$Callback")+ val ctor = callbackClass.getDeclaredConstructor(+ RecognitionService::class.java, listenerClass, AttributionSource::class.java,+ )+ ctor.isAccessible = true+ callback = ctor.newInstance(service, listener, null) as RecognitionService.Callback+ }++ private fun firstText(bundle: Bundle?): String? =+ bundle?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()++ private fun defaultValue(type: Class<*>): Any? = when (type) {+ java.lang.Boolean.TYPE -> false+ java.lang.Integer.TYPE -> 0+ java.lang.Long.TYPE -> 0L+ java.lang.Float.TYPE -> 0f+ java.lang.Double.TYPE -> 0.0+ else -> null+ }++ fun awaitTerminal(seconds: Long = 15): Boolean = terminalLatch.await(seconds, TimeUnit.SECONDS)+}
speech/src/test/java/com/vayunmathur/speech/service/SupertonicTtsServiceTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/service/SupertonicTtsServiceTest.kt b/speech/src/test/java/com/vayunmathur/speech/service/SupertonicTtsServiceTest.ktnew file mode 100644index 0000000000..4a05d2d478--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/service/SupertonicTtsServiceTest.kt@@ -0,0 +1,331 @@+package com.vayunmathur.speech.service++import android.os.Bundle+import android.speech.tts.SynthesisCallback+import android.speech.tts.SynthesisRequest+import android.speech.tts.TextToSpeech+import android.content.Context+import com.vayunmathur.speech.platform.SupertonicEngine+import com.vayunmathur.speech.testing.ThrowingDetachFdShadow+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ThrowingDetachFdShadow::class])+class SupertonicTtsServiceTest {++ /** Exposes the protected TextToSpeechService contract for direct calls. */+ class Harness : SupertonicTtsService() {+ fun isLanguageAvailable(lang: String?, country: String?, variant: String?) =+ onIsLanguageAvailable(lang, country, variant)+ fun loadLanguage(lang: String?, country: String?, variant: String?) =+ onLoadLanguage(lang, country, variant)+ fun language(): Array<String> = onGetLanguage()+ fun defaultVoiceName(lang: String?, country: String?, variant: String?) =+ onGetDefaultVoiceNameFor(lang, country, variant)+ fun isValidVoiceName(name: String?) = onIsValidVoiceName(name)+ fun loadVoice(name: String?) = onLoadVoice(name)+ fun voices() = onGetVoices()+ fun stop() = onStop()+ fun synthesize(request: SynthesisRequest, callback: SynthesisCallback) =+ onSynthesizeText(request, callback)++ override fun createEngine(): SupertonicEngine =+ engineFactory?.invoke(applicationContext) ?: super.createEngine()++ companion object {+ var engineFactory: ((Context) -> SupertonicEngine)? = null+ }+ }++ class RecordingCallback(private val startResult: Int = TextToSpeech.SUCCESS) : SynthesisCallback {+ var startCalls = mutableListOf<Triple<Int, Int, Int>>()+ var audio = mutableListOf<Byte>()+ var audioCalls = 0+ var audioResult = TextToSpeech.SUCCESS+ var doneCalls = 0+ var errorCalls = 0+ override fun getMaxBufferSize(): Int = 1024+ override fun start(sampleRateInHz: Int, audioFormat: Int, channelCount: Int): Int {+ startCalls += Triple(sampleRateInHz, audioFormat, channelCount)+ return startResult+ }+ override fun audioAvailable(buffer: ByteArray, offset: Int, length: Int): Int {+ audioCalls+++ if (audioResult != TextToSpeech.SUCCESS) return audioResult+ audio += buffer.slice(offset until offset + length)+ return TextToSpeech.SUCCESS+ }+ override fun done(): Int { doneCalls++; return TextToSpeech.SUCCESS }+ override fun error() { errorCalls++ }+ override fun error(errorCode: Int) { errorCalls++ }+ override fun hasStarted(): Boolean = startCalls.isNotEmpty()+ override fun hasFinished(): Boolean = doneCalls > 0 || errorCalls > 0+ }++ class FakeEngine(context: Context) : SupertonicEngine(context) {+ var preloadOk = true+ var voiceOk = true+ var chunks: List<FloatArray> = listOf(FloatArray(0))+ var afterChunk: (() -> Unit)? = null+ var synthCalls = mutableListOf<Pair<String, String>>()+ var voicesSeen = mutableListOf<String>()+ var closed = false+ override fun preload(): Boolean = preloadOk+ override fun voice(style: String): Boolean { voicesSeen += style; return voiceOk }+ override fun synthesize(text: String, language: String, onChunk: (FloatArray) -> Boolean): Boolean {+ synthCalls += text to language+ var spoke = false+ for (chunk in chunks) {+ if (!onChunk(chunk)) return false+ afterChunk?.invoke()+ spoke = spoke || chunk.isNotEmpty()+ }+ return spoke+ }+ override fun close() { closed = true }+ }++ private fun service(): Harness =+ Robolectric.buildService(Harness::class.java).create().get()++ private fun fakeService(configure: FakeEngine.() -> Unit): Pair<Harness, FakeEngine> {+ lateinit var fake: FakeEngine+ Harness.engineFactory = { ctx -> FakeEngine(ctx).apply(configure).also { fake = it } }+ try {+ val harness = Robolectric.buildService(Harness::class.java).create().get()+ // Force the lazy engine now (a non-blank synthesis) so `fake` is+ // initialised for the caller, then clear the warm-up records.+ harness.synthesize(SynthesisRequest("warm up", Bundle()), RecordingCallback())+ fake.synthCalls.clear(); fake.voicesSeen.clear()+ return harness to fake+ } finally {+ Harness.engineFactory = null+ }+ }++ @Test+ fun languageAvailabilityLevels() {+ val s = service()+ assertEquals(TextToSpeech.LANG_AVAILABLE, s.isLanguageAvailable("en", null, null))+ assertEquals(TextToSpeech.LANG_AVAILABLE, s.isLanguageAvailable("en", "", ""))+ assertEquals(TextToSpeech.LANG_COUNTRY_AVAILABLE, s.isLanguageAvailable("en", "US", null))+ assertEquals(TextToSpeech.LANG_COUNTRY_AVAILABLE, s.isLanguageAvailable("de", "DE", ""))+ assertEquals(TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE, s.isLanguageAvailable("en", "US", "x"))+ assertEquals(TextToSpeech.LANG_NOT_SUPPORTED, s.isLanguageAvailable("th", null, null))+ assertEquals(TextToSpeech.LANG_NOT_SUPPORTED, s.isLanguageAvailable(null, null, null))+ assertEquals(TextToSpeech.LANG_NOT_SUPPORTED, s.isLanguageAvailable("", null, null))+ assertEquals(TextToSpeech.LANG_AVAILABLE, s.isLanguageAvailable("eng", null, null))+ assertEquals(TextToSpeech.LANG_COUNTRY_AVAILABLE, s.isLanguageAvailable("pt", "PT", null))+ }++ @Test+ fun loadLanguageUpdatesCurrentLanguageOnlyOnSuccess() {+ val s = service()+ assertEquals(arrayOf("eng", "USA", "").toList(), s.language().toList())+ assertEquals(TextToSpeech.LANG_COUNTRY_AVAILABLE, s.loadLanguage("de", "DE", null))+ assertEquals(arrayOf("deu", "DEU", "").toList(), s.language().toList())+ assertEquals(TextToSpeech.LANG_NOT_SUPPORTED, s.loadLanguage("th", null, null))+ assertEquals(arrayOf("deu", "DEU", "").toList(), s.language().toList())+ assertEquals(TextToSpeech.LANG_AVAILABLE, s.loadLanguage("ja", null, null))+ assertEquals(arrayOf("jpn", "JPN", "").toList(), s.language().toList())+ }++ @Test+ fun defaultVoiceNameForAllRequestForms() {+ val s = service()+ assertEquals("en-US-x-F1", s.defaultVoiceName(null, null, null))+ assertEquals("en-US-x-F1", s.defaultVoiceName("en", null, null))+ assertEquals("de-DE-x-F1", s.defaultVoiceName("de", "DE", null))+ assertEquals("fr-FR-x-F1", s.defaultVoiceName("fra", null, null))+ assertNull(s.defaultVoiceName("th", null, null))+ }++ @Test+ fun voiceNameValidationChecksLanguageAndStyle() {+ val s = service()+ assertEquals(TextToSpeech.SUCCESS, s.isValidVoiceName("en-US-x-F1"))+ assertEquals(TextToSpeech.SUCCESS, s.isValidVoiceName("en-US-x-m5"))+ assertEquals(TextToSpeech.SUCCESS, s.isValidVoiceName("en-US"))+ assertEquals(TextToSpeech.SUCCESS, s.isValidVoiceName("eng-USA"))+ assertEquals(TextToSpeech.SUCCESS, s.isValidVoiceName("de-DE-x-F2"))+ assertEquals(TextToSpeech.ERROR, s.isValidVoiceName("en-US-x-BOGUS"))+ assertEquals(TextToSpeech.ERROR, s.isValidVoiceName("en-US-x-"))+ assertEquals(TextToSpeech.ERROR, s.isValidVoiceName("th-TH-x-F1"))+ assertEquals(TextToSpeech.ERROR, s.isValidVoiceName(null))+ assertEquals(TextToSpeech.ERROR, s.isValidVoiceName(""))+ }++ @Test+ fun loadVoiceUpdatesLanguageAndRejectsInvalid() {+ val s = service()+ assertEquals(TextToSpeech.SUCCESS, s.loadVoice("de-DE-x-M3"))+ assertEquals(arrayOf("deu", "DEU", "").toList(), s.language().toList())+ assertEquals(TextToSpeech.ERROR, s.loadVoice("en-US-x-BOGUS"))+ assertEquals(arrayOf("deu", "DEU", "").toList(), s.language().toList())+ assertEquals(TextToSpeech.ERROR, s.loadVoice(null))+ assertEquals(TextToSpeech.SUCCESS, s.loadVoice("ja-JP"))+ assertEquals(arrayOf("jpn", "JPN", "").toList(), s.language().toList())+ }++ @Test+ fun getVoicesPublishesThreeFormsPerLanguagePerStyle() {+ val s = service()+ val voices = s.voices()+ // 31 languages x (plain tag + iso3 pair + 10 styled names).+ assertEquals(31 * 12, voices.size)+ val names = voices.map { it.name }.toSet()+ assertEquals(voices.size, names.size)+ assertTrue("en-US" in names)+ assertTrue("eng-USA" in names)+ assertTrue("en-US-x-F1" in names)+ assertTrue("en-US-x-M5" in names)+ assertTrue("deu-DEU" in names)+ assertTrue("vie-VNM" in names)+ assertFalse(voices.any { it.name.contains("tha") })+ val en = voices.first { it.name == "en-US-x-F1" }+ assertEquals("en", en.locale.language)+ // The default voice name must appear in the published list (Settings Play button).+ assertTrue(s.defaultVoiceName(null, null, null) in names)+ }++ @Test+ fun synthesizeBlankTextStartsAndFinishesWithoutEngine() {+ val s = service()+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("", Bundle()), cb)+ assertEquals(listOf(Triple(44100, android.media.AudioFormat.ENCODING_PCM_16BIT, 1)), cb.startCalls)+ assertEquals(1, cb.doneCalls)+ assertEquals(0, cb.errorCalls)+ assertTrue(cb.audio.isEmpty())++ val cb2 = RecordingCallback()+ s.synthesize(SynthesisRequest(" ", Bundle()), cb2)+ assertEquals(1, cb2.doneCalls)+ assertEquals(0, cb2.errorCalls)+ }++ @Test+ fun synthesizeRealTextErrorsWhenEngineUnavailable() {+ val s = service()+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Hello world.", Bundle()), cb)+ assertEquals(1, cb.errorCalls)+ assertEquals(0, cb.doneCalls)+ assertTrue(cb.startCalls.isEmpty())+ }++ @Test+ fun stopDoesNotBreakSubsequentBlankSynthesis() {+ val s = service()+ s.stop()+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("", Bundle()), cb)+ assertEquals(1, cb.doneCalls)+ }++ @Test+ fun synthesizeSuccessConvertsFloatsToLittleEndianPcm16() {+ val (s, fake) = fakeService {+ chunks = listOf(floatArrayOf(0f, 1f, -1f, 0.5f, -0.5f, 2f, -2f))+ }+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(1, cb.doneCalls); assertEquals(0, cb.errorCalls)+ assertEquals(listOf(Triple(44100, android.media.AudioFormat.ENCODING_PCM_16BIT, 1)), cb.startCalls)+ // 0, 32767, -32767, 16384, -16384, clamped 32767, clamped -32767; little-endian.+ val expected = listOf(0, 32767, -32767, 16384, -16383, 32767, -32767).flatMap {+ listOf((it and 0xFF).toByte(), ((it shr 8) and 0xFF).toByte())+ }+ assertEquals(expected, cb.audio)+ assertEquals(listOf("Hello." to "en"), fake.synthCalls)+ assertEquals(listOf("F1"), fake.voicesSeen.takeLast(1))+ }++ @Test+ fun synthesizeSplitsAudioAgainstMaxBufferSize() {+ val (s, _) = fakeService { chunks = listOf(FloatArray(3000) { 0.25f }) }+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Long text.", Bundle()), cb)+ assertEquals(1, cb.doneCalls)+ assertEquals(6000, cb.audio.size)+ // 6000 bytes in <=1024-byte writes: 5 full writes plus a remainder.+ assertEquals(6, cb.audioCalls)+ assertTrue(cb.audio.all { it == (8192 and 0xFF).toByte() || it == ((8192 shr 8) and 0xFF).toByte() })+ }++ @Test+ fun synthesizeStartFailureReturnsSilently() {+ val (s, fake) = fakeService { chunks = listOf(floatArrayOf(0.5f)) }+ val cb = RecordingCallback(startResult = TextToSpeech.ERROR)+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(0, cb.doneCalls); assertEquals(0, cb.errorCalls)+ assertTrue(fake.synthCalls.isEmpty())+ }++ @Test+ fun synthesizeVoiceFailureErrors() {+ val (s, _) = fakeService { voiceOk = false }+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(1, cb.errorCalls); assertEquals(0, cb.doneCalls)+ }++ @Test+ fun synthesizePreloadFailureErrorsBeforeStart() {+ val (s, _) = fakeService { preloadOk = false }+ val cb = RecordingCallback()+ val startsBefore = cb.startCalls.size+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(1, cb.errorCalls)+ assertEquals(startsBefore, cb.startCalls.size)+ }++ @Test+ fun synthesizeAudioFailureErrors() {+ val (s, _) = fakeService { chunks = listOf(floatArrayOf(0.5f, 0.5f)) }+ val cb = RecordingCallback()+ cb.audioResult = TextToSpeech.ERROR+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(1, cb.errorCalls); assertEquals(0, cb.doneCalls)+ }++ @Test+ fun synthesizeEmptyAudioFromEngineErrors() {+ val (s, _) = fakeService { chunks = listOf(FloatArray(0)) }+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ assertEquals(1, cb.errorCalls); assertEquals(0, cb.doneCalls)+ }++ @Test+ fun synthesizeStoppedMidwayFinishesWithDone() {+ var harnessRef: Harness? = null+ val (s, _) = fakeService {+ chunks = listOf(floatArrayOf(0.5f), floatArrayOf(0.5f))+ afterChunk = { harnessRef?.stop() }+ }+ harnessRef = s+ val cb = RecordingCallback()+ s.synthesize(SynthesisRequest("Hello.", Bundle()), cb)+ // Stopped is a normal finish, and only the first chunk was delivered.+ assertEquals(1, cb.doneCalls); assertEquals(0, cb.errorCalls)+ assertEquals(2, cb.audio.size)+ }++ @Test+ fun destroyShutsEngineDown() {+ val controller = Robolectric.buildService(Harness::class.java).create()+ controller.destroy()+ val s = controller.get()+ // Language queries still answer from the catalog after destroy.+ assertEquals(TextToSpeech.LANG_AVAILABLE, s.isLanguageAvailable("en", null, null))+ }+}
speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt b/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.ktnew file mode 100644index 0000000000..bc070afb30--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/service/WhisperRecognitionServiceTest.kt@@ -0,0 +1,236 @@+package com.vayunmathur.speech.service++import android.Manifest+import android.app.Application+import android.content.Context+import android.content.Intent+import android.speech.RecognizerIntent+import android.speech.SpeechRecognizer+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.speech.testing.FakeAudioRecordShadow+import com.vayunmathur.speech.testing.ThrowingDetachFdShadow+import com.vayunmathur.speech.util.WhisperEngine+import java.util.concurrent.TimeUnit+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class WhisperHarness : WhisperRecognitionService() {+ fun start(intent: Intent, cb: RecordingRecognitionCallback) = onStartListening(intent, cb.callback)+ fun stop(cb: RecordingRecognitionCallback) = onStopListening(cb.callback)+ fun cancel(cb: RecordingRecognitionCallback) = onCancel(cb.callback)+ override fun createEngine(): WhisperEngine =+ engineFactory?.invoke(applicationContext) ?: super.createEngine()+ companion object { var engineFactory: ((Context) -> WhisperEngine)? = null }+}++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ThrowingDetachFdShadow::class])+class WhisperRecognitionServiceTest {++ @Test+ fun startListeningErrorsWhenModelUnavailable() {+ val service = Robolectric.buildService(WhisperHarness::class.java).create().get()+ val cb = RecordingRecognitionCallback(service)+ service.start(Intent(), cb)+ assertEquals(listOf(SpeechRecognizer.ERROR_SERVER), cb.errors.toList())+ assertEquals(0, cb.readyCalls)+ }++ @Test+ fun stopCancelAndDestroyWithoutSessionAreSafe() {+ val controller = Robolectric.buildService(WhisperHarness::class.java).create()+ val service = controller.get()+ val cb = RecordingRecognitionCallback(service)+ service.stop(cb)+ service.cancel(cb)+ controller.destroy()+ assertTrue(cb.errors.isEmpty())+ assertTrue(cb.resultsTexts.isEmpty())+ }+}++/** Sessions driven by a scripted microphone and a fake Whisper engine. */+@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ThrowingDetachFdShadow::class, FakeAudioRecordShadow::class])+class WhisperRecognitionSessionTest {++ class FakeWhisperEngine(context: Context) : WhisperEngine(context) {+ var modelPresent = true+ var transcript: String? = " hello world "+ val languages = mutableListOf<String?>()+ var transcribeCalls = 0+ var closed = false+ override fun isModelPresent(): Boolean = modelPresent+ override fun preload(): Boolean = modelPresent+ override fun transcribe(pcm16k: ShortArray, language: String?): String? {+ transcribeCalls+++ languages += language+ return transcript+ }+ override fun close() { closed = true }+ }++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun grantMic() {+ shadowOf(app).grantPermissions(Manifest.permission.RECORD_AUDIO)+ }++ private fun fakeService(configure: FakeWhisperEngine.() -> Unit = {}): Pair<WhisperHarness, FakeWhisperEngine> {+ val created = java.util.concurrent.CountDownLatch(1)+ var fake: FakeWhisperEngine? = null+ WhisperHarness.engineFactory = { ctx ->+ FakeWhisperEngine(ctx).apply(configure).also { fake = it; created.countDown() }+ }+ try {+ val harness = Robolectric.buildService(WhisperHarness::class.java).create().get()+ // onCreate warms the engine on a thread; wait for the factory to run.+ assertTrue(created.await(10, TimeUnit.SECONDS), "fake engine was never created")+ return harness to fake!!+ } finally {+ WhisperHarness.engineFactory = null+ }+ }++ private fun intentWithLang(lang: String?): Intent = Intent().apply {+ if (lang != null) putExtra(RecognizerIntent.EXTRA_LANGUAGE, lang)+ }++ @Test+ fun missingMicPermissionErrorsWithInsufficientPermissions() {+ val (service, _) = fakeService()+ FakeAudioRecordShadow.reset(listOf(10000))+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang("en-US"), cb)+ assertTrue(cb.awaitTerminal())+ assertEquals(listOf(SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS), cb.errors.toList())+ assertEquals(0, cb.readyCalls)+ }++ @Test+ fun speechThenSilenceDeliversPartialAndFinalResult() {+ grantMic()+ val (service, fake) = fakeService()+ FakeAudioRecordShadow.reset(listOf(10000, 10000, 10000) + List(15) { 0 })+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang("en-US"), cb)+ assertTrue(cb.awaitTerminal(), "no terminal callback; errors=${cb.errors} results=${cb.resultsTexts}")+ assertEquals(listOf("hello world"), cb.resultsTexts.toList())+ assertTrue(cb.partialTexts.contains("hello world"), "partials=${cb.partialTexts}")+ assertEquals(1, cb.readyCalls)+ assertEquals(1, cb.beginningCalls)+ assertEquals(1, cb.endOfSpeechCalls)+ assertTrue(cb.errors.isEmpty(), "errors=${cb.errors}")+ assertTrue(fake.languages.isNotEmpty() && fake.languages.all { it == "en" }, "langs=${fake.languages}")+ assertTrue(cb.rmsValues.isNotEmpty())+ assertEquals(10f, cb.rmsValues.max())+ assertEquals(0f, cb.rmsValues.min())+ }++ @Test+ fun noSpeechTimesOutWithNoMatch() {+ grantMic()+ val (service, _) = fakeService()+ FakeAudioRecordShadow.reset(emptyList())+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang(null), cb)+ assertTrue(cb.awaitTerminal())+ assertEquals(listOf(SpeechRecognizer.ERROR_NO_MATCH), cb.errors.toList())+ assertTrue(cb.resultsTexts.isEmpty())+ assertEquals(0, cb.beginningCalls)+ assertTrue(FakeAudioRecordShadow.reads >= 80, "reads=${FakeAudioRecordShadow.reads}")+ }++ @Test+ fun blankTranscriptAfterSpeechIsNoMatch() {+ grantMic()+ val (service, _) = fakeService { transcript = " " }+ FakeAudioRecordShadow.reset(listOf(10000, 10000) + List(15) { 0 })+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang("fr-FR"), cb)+ assertTrue(cb.awaitTerminal())+ assertEquals(listOf(SpeechRecognizer.ERROR_NO_MATCH), cb.errors.toList())+ assertTrue(cb.resultsTexts.isEmpty())+ assertTrue(cb.partialTexts.isEmpty())+ }++ @Test+ fun nullTranscriptAfterSpeechIsNoMatch() {+ grantMic()+ val (service, _) = fakeService { transcript = null }+ FakeAudioRecordShadow.reset(listOf(10000) + List(15) { 0 })+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang(""), cb)+ assertTrue(cb.awaitTerminal())+ assertEquals(listOf(SpeechRecognizer.ERROR_NO_MATCH), cb.errors.toList())+ }++ @Test+ fun secondStartWhileBusyIsRejected() {+ grantMic()+ val (service, _) = fakeService()+ FakeAudioRecordShadow.reset(listOf(10000, FakeAudioRecordShadow.BLOCK))+ val first = RecordingRecognitionCallback(service)+ service.start(intentWithLang("en"), first)+ assertTrue(FakeAudioRecordShadow.blockEntered!!.await(10, TimeUnit.SECONDS))+ val second = RecordingRecognitionCallback(service)+ service.start(intentWithLang("de"), second)+ assertEquals(listOf(SpeechRecognizer.ERROR_RECOGNIZER_BUSY), second.errors.toList())+ service.cancel(first)+ FakeAudioRecordShadow.releaseBlock()+ }++ @Test+ fun userStopEndsSessionWithFinalResult() {+ grantMic()+ val (service, _) = fakeService()+ FakeAudioRecordShadow.reset(listOf(10000, 10000, FakeAudioRecordShadow.BLOCK))+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang("de-DE"), cb)+ assertTrue(FakeAudioRecordShadow.blockEntered!!.await(10, TimeUnit.SECONDS))+ service.stop(cb)+ FakeAudioRecordShadow.releaseBlock()+ assertTrue(cb.awaitTerminal(), "errors=${cb.errors} results=${cb.resultsTexts}")+ assertEquals(listOf("hello world"), cb.resultsTexts.toList())+ // German BCP-47 reduces to Whisper's ISO code.+ assertTrue(cb.errors.isEmpty())+ }++ @Test+ fun cancelClearsSessionSoNextStartWorks() {+ grantMic()+ val (service, _) = fakeService()+ FakeAudioRecordShadow.reset(listOf(10000, FakeAudioRecordShadow.BLOCK))+ val first = RecordingRecognitionCallback(service)+ service.start(intentWithLang("en"), first)+ assertTrue(FakeAudioRecordShadow.blockEntered!!.await(10, TimeUnit.SECONDS))+ service.cancel(first)+ FakeAudioRecordShadow.releaseBlock()+ assertTrue(first.errors.isEmpty())+ assertTrue(first.resultsTexts.isEmpty())++ FakeAudioRecordShadow.reset(emptyList())+ val second = RecordingRecognitionCallback(service)+ service.start(intentWithLang(null), second)+ assertTrue(second.awaitTerminal())+ assertEquals(listOf(SpeechRecognizer.ERROR_NO_MATCH), second.errors.toList())+ }++ @Test+ fun longSpeechHitsDurationCapAndTranscribes() {+ grantMic()+ val (service, _) = fakeService()+ // 29 s cap: 290 chunks of 100 ms of continuous speech.+ FakeAudioRecordShadow.reset(List(400) { 10000 })+ val cb = RecordingRecognitionCallback(service)+ service.start(intentWithLang("ja"), cb)+ assertTrue(cb.awaitTerminal())+ assertEquals(listOf("hello world"), cb.resultsTexts.toList())+ }+}
speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt b/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.ktnew file mode 100644index 0000000000..7e779eebbb--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/testing/FakeAudioRecordShadow.kt@@ -0,0 +1,71 @@+package com.vayunmathur.speech.testing++import android.media.AudioRecord+import java.util.concurrent.ConcurrentLinkedQueue+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/**+ * Scripts the microphone: each read fills the buffer with the next queued+ * amplitude (100 ms of constant samples) and returns a full chunk. When the+ * script runs out, reads return silence, which drives the VAD to its+ * end-of-utterance / no-speech exits.+ */+@Implements(AudioRecord::class)+class FakeAudioRecordShadow {++ @Implementation+ fun __constructor__(audioSource: Int, sampleRateInHz: Int, channelConfig: Int, audioFormat: Int, bufferSizeInBytes: Int) = Unit++ @Implementation+ fun getState(): Int = AudioRecord.STATE_INITIALIZED++ @Implementation+ fun startRecording() = Unit++ @Implementation+ fun read(audioData: ShortArray, offsetInShorts: Int, sizeInShorts: Int): Int {+ val amplitude = script.poll() ?: 0+ if (amplitude == BLOCK) {+ blockEntered?.countDown()+ blockRelease?.await(10, java.util.concurrent.TimeUnit.SECONDS)+ for (i in 0 until sizeInShorts) audioData[offsetInShorts + i] = 0+ } else {+ for (i in 0 until sizeInShorts) audioData[offsetInShorts + i] = amplitude.toShort()+ }+ reads+++ return sizeInShorts+ }++ @Implementation+ fun stop() = Unit++ @Implementation+ fun release() { released = true }++ companion object {+ /** Script sentinel: this read blocks until [releaseBlock] is called. */+ const val BLOCK = Int.MIN_VALUE++ private val script = ConcurrentLinkedQueue<Int>()+ @Volatile var reads = 0+ @Volatile var released = false+ @Volatile var blockEntered: java.util.concurrent.CountDownLatch? = null+ @Volatile var blockRelease: java.util.concurrent.CountDownLatch? = null++ fun reset(amplitudes: List<Int>) {+ script.clear()+ script.addAll(amplitudes)+ reads = 0+ released = false+ blockEntered = java.util.concurrent.CountDownLatch(1)+ blockRelease = java.util.concurrent.CountDownLatch(1)+ }++ fun releaseBlock() { blockRelease?.countDown() }++ @Implementation+ @JvmStatic+ fun getMinBufferSize(sampleRateInHz: Int, channelConfig: Int, audioFormat: Int): Int = 3200+ }+}
speech/src/test/java/com/vayunmathur/speech/testing/ThrowingDetachFdShadow.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/testing/ThrowingDetachFdShadow.kt b/speech/src/test/java/com/vayunmathur/speech/testing/ThrowingDetachFdShadow.ktnew file mode 100644index 0000000000..baf0c871f4--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/testing/ThrowingDetachFdShadow.kt@@ -0,0 +1,18 @@+package com.vayunmathur.speech.testing++import android.os.ParcelFileDescriptor+import java.io.IOException+import org.robolectric.annotation.Implementation+import org.robolectric.annotation.Implements++/**+ * Robolectric's host JDK lacks the libcore `FileDescriptor.getOwnerId$` that+ * the real `ParcelFileDescriptor.detachFd` calls, so detaching throws an+ * Error the production catch-of-Exception cannot see. Throwing an IOException+ * here reproduces the on-device "asset cannot be detached" failure instead.+ */+@Implements(ParcelFileDescriptor::class)+class ThrowingDetachFdShadow {+ @Implementation+ fun detachFd(): Int = throw IOException("detachFd unavailable in tests")+}
speech/src/test/java/com/vayunmathur/speech/tts/CheckVoiceDataActivityTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/tts/CheckVoiceDataActivityTest.kt b/speech/src/test/java/com/vayunmathur/speech/tts/CheckVoiceDataActivityTest.ktnew file mode 100644index 0000000000..c6f29c570c--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/tts/CheckVoiceDataActivityTest.kt@@ -0,0 +1,48 @@+package com.vayunmathur.speech.tts++import android.speech.tts.TextToSpeech+import com.vayunmathur.speech.domain.SupertonicVoices+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CheckVoiceDataActivityTest {++ @Test+ fun bundledVoicesAreReportedAvailableInIso3Form() {+ val controller = Robolectric.buildActivity(CheckVoiceDataActivity::class.java).setup()+ val activity = controller.get()+ assertTrue(activity.isFinishing)+ val shadow = shadowOf(activity)+ val data = shadow.resultIntent+ assertNotNull(data)+ val available = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES)+ val unavailable = data.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES)+ assertNotNull(available)+ assertNotNull(unavailable)+ // The real bundle ships in the APK, so every language is available in+ // the ISO-3 pair form and none is unavailable.+ if (shadow.resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {+ assertEquals(+ SupertonicVoices.ALL.map { "${it.iso3}-${it.iso3Country}" },+ available.toList(),+ )+ assertEquals(emptyList(), unavailable.toList())+ assertEquals("eng-USA", available.first())+ assertEquals("vie-VNM", available.last())+ assertEquals(31, available.size)+ } else {+ assertEquals(TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL, shadow.resultCode)+ assertEquals(emptyList(), available.toList())+ assertEquals(31, unavailable.size)+ }+ // Either way the two lists partition the catalog.+ assertEquals(31, available.size + unavailable.size)+ }+}
speech/src/test/java/com/vayunmathur/speech/ui/SpeechSetupScreenTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/ui/SpeechSetupScreenTest.kt b/speech/src/test/java/com/vayunmathur/speech/ui/SpeechSetupScreenTest.ktnew file mode 100644index 0000000000..7c9379805c--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/ui/SpeechSetupScreenTest.kt@@ -0,0 +1,213 @@+package com.vayunmathur.speech.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsEnabled+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.assertIsSelected+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.speech.SpeechSetupScreen+import com.vayunmathur.speech.util.SpeechSetupActions+import com.vayunmathur.speech.util.SpeechSetupUiState+import com.vayunmathur.speech.util.TtsVoiceUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SpeechSetupScreenTest {++ @get:Rule+ val rule = createComposeRule()++ private class RecordingActions : SpeechSetupActions {+ var mic = 0+ var voiceSettings = 0+ var ttsSettings = 0+ var refreshes = 0+ override fun requestMicPermission() { mic++ }+ override fun openVoiceInputSettings() { voiceSettings++ }+ override fun openTtsSettings() { ttsSettings++ }+ override fun refresh() { refreshes++ }+ }++ private val languages = listOf(+ TtsVoiceUiState("en", "en-US", "English", "English"),+ TtsVoiceUiState("de", "de-DE", "Deutsch", "German"),+ TtsVoiceUiState("fr", "fr-FR", "Français", "French"),+ )++ private fun shown(text: String) {+ rule.onNodeWithText(text).performScrollTo()+ rule.onNodeWithText(text).assertIsDisplayed()+ }++ private fun setScreen(state: SpeechSetupUiState, actions: SpeechSetupActions = SpeechSetupActions.Noop) {+ rule.setContent {+ DynamicTheme(darkTheme = false) {+ SpeechSetupScreen(state = state, actions = actions)+ }+ }+ }++ @Test+ fun brokenInstallStateShowsWarningAndAllSteps() {+ setScreen(SpeechSetupUiState())+ rule.onNodeWithText("Install looks damaged").assertIsDisplayed()+ rule.onNodeWithText("1. Microphone access").assertIsDisplayed()+ rule.onNodeWithText("2. Set as speech recognizer").assertIsDisplayed()+ shown("3. Set as text-to-speech engine")+ shown("Try it")+ shown("Try the voice")+ }++ @Test+ fun micGrantButtonFiresActionOnlyWhenMicMissing() {+ val actions = RecordingActions()+ setScreen(SpeechSetupUiState(modelReady = true, ttsModelReady = true, hasMic = false), actions)+ rule.onNodeWithText("Grant microphone").assertIsDisplayed()+ rule.onNodeWithText("Grant microphone").performClick()+ assertEquals(1, actions.mic)+ }++ @Test+ fun readyStateHidesBrokenCardGrantButtonAndMarksStepsDone() {+ setScreen(+ SpeechSetupUiState(+ modelReady = true, hasMic = true, isRecognizerDefault = true,+ ttsModelReady = true, isTtsDefault = true,+ ttsVoices = languages, currentTestLang = "en",+ ),+ )+ rule.onNodeWithText("Install looks damaged").assertDoesNotExist()+ rule.onNodeWithText("Grant microphone").assertDoesNotExist()+ rule.onNodeWithText("1. Microphone access ✓").assertIsDisplayed()+ rule.onNodeWithText("2. Set as speech recognizer ✓").assertIsDisplayed()+ shown("3. Set as text-to-speech engine ✓")+ }++ @Test+ fun settingsButtonsFireActions() {+ val actions = RecordingActions()+ setScreen(+ SpeechSetupUiState(modelReady = true, ttsModelReady = true, hasMic = true, ttsVoices = languages),+ actions,+ )+ rule.onNodeWithText("Open voice input settings").performClick()+ rule.onNodeWithText("Open text-to-speech settings").performClick()+ assertEquals(1, actions.voiceSettings)+ assertEquals(1, actions.ttsSettings)+ }++ @Test+ fun whisperModelMissingShowsWarning() {+ setScreen(SpeechSetupUiState(modelReady = false, ttsModelReady = true))+ rule.onNodeWithText("Install looks damaged").assertIsDisplayed()+ }++ @Test+ fun ttsBundleMissingShowsWarning() {+ setScreen(SpeechSetupUiState(modelReady = true, ttsModelReady = false))+ rule.onNodeWithText("Install looks damaged").assertIsDisplayed()+ }++ @Test+ fun testMicrophoneButtonDisabledWithoutMic() {+ setScreen(SpeechSetupUiState(modelReady = true, ttsModelReady = true, hasMic = false))+ rule.onNodeWithText("Test microphone").assertIsNotEnabled()+ }++ @Test+ fun testMicrophoneClickReportsNoRecognizer() {+ setScreen(SpeechSetupUiState(modelReady = true, ttsModelReady = true, hasMic = true))+ rule.onNodeWithText("Test microphone").performScrollTo()+ rule.onNodeWithText("Test microphone").assertIsEnabled()+ rule.onNodeWithText("Test microphone").performClick()+ rule.waitForIdle()+ // Under Robolectric no recognition service is bound, so the card explains step 2.+ val shown = runCatching {+ rule.onNodeWithText("No recognizer selected yet (finish step 2).").assertExists()+ true+ }.getOrDefault(false)+ val listening = runCatching {+ rule.onNodeWithText("Listening…").assertExists()+ true+ }.getOrDefault(false)+ assertTrue(shown || listening, "expected a status after clicking Test microphone")+ }++ @Test+ fun speakSampleDisabledWhenTtsModelMissing() {+ setScreen(+ SpeechSetupUiState(modelReady = true, ttsModelReady = false, ttsVoices = languages),+ )+ rule.onNodeWithText("Speak sample").performScrollTo()+ rule.onNodeWithText("Speak sample").assertIsNotEnabled()+ }++ @Test+ fun languageDropdownShowsSelectionAndPicksAnother() {+ setScreen(+ SpeechSetupUiState(+ modelReady = true, hasMic = true, ttsModelReady = true,+ ttsVoices = languages, currentTestLang = "de",+ ),+ )+ shown("Deutsch (German)")+ rule.onNodeWithText("Deutsch (German)").performClick()+ rule.onNodeWithText("Français · French (fr)").assertIsDisplayed()+ rule.onNodeWithText("Deutsch · German (de)").assertIsSelected()+ rule.onNodeWithText("Français · French (fr)").performClick()+ rule.waitForIdle()+ shown("Français (French)")+ }++ @Test+ fun unknownCurrentLanguageFallsBackToFirstLanguage() {+ setScreen(+ SpeechSetupUiState(+ modelReady = true, ttsModelReady = true,+ ttsVoices = languages, currentTestLang = "xx",+ ),+ )+ shown("English (English)")+ }++ @Test+ fun emptyLanguageListShowsSpeakButtonWithoutDropdown() {+ setScreen(+ SpeechSetupUiState(modelReady = true, ttsModelReady = true, ttsVoices = emptyList()),+ )+ rule.onNodeWithText("Speak sample").performScrollTo()+ rule.onNodeWithText("Speak sample").assertIsEnabled()+ rule.onNodeWithText("Speak sample").performClick()+ rule.waitForIdle()+ rule.onNodeWithText("The bundled voices could not be read.").assertExists()+ }++ @Test+ fun speakSampleWithLanguagesShowsLoadingStatus() {+ setScreen(+ SpeechSetupUiState(+ modelReady = true, ttsModelReady = true,+ ttsVoices = languages, currentTestLang = "en",+ ),+ )+ rule.onNodeWithText("Speak sample").performScrollTo()+ rule.onNodeWithText("Speak sample").performClick()+ rule.waitForIdle()+ val loading = runCatching {+ rule.onNodeWithText("Loading…").assertExists(); true+ }.getOrDefault(false)+ val failed = runCatching {+ rule.onNodeWithText("Engine failed to start.").assertExists(); true+ }.getOrDefault(false)+ assertTrue(loading || failed, "expected Loading or engine-failure status")+ }+}
speech/src/test/java/com/vayunmathur/speech/util/SpeechUiContractTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/util/SpeechUiContractTest.kt b/speech/src/test/java/com/vayunmathur/speech/util/SpeechUiContractTest.ktnew file mode 100644index 0000000000..1b9d7c0cb9--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/util/SpeechUiContractTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.speech.util++import com.vayunmathur.speech.domain.SupertonicVoices+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++class SpeechUiContractTest {++ @Test+ fun setupStateDefaultsAreAllUndone() {+ val state = SpeechSetupUiState()+ assertFalse(state.modelReady)+ assertFalse(state.hasMic)+ assertFalse(state.isRecognizerDefault)+ assertFalse(state.ttsModelReady)+ assertFalse(state.isTtsDefault)+ assertEquals(emptyList(), state.ttsVoices)+ assertEquals("en", state.currentTestLang)+ }++ @Test+ fun setupStateCopyAndEquality() {+ val voices = listOf(TtsVoiceUiState("de", "de-DE", "Deutsch", "German"))+ val state = SpeechSetupUiState(modelReady = true, ttsVoices = voices, currentTestLang = "de")+ assertEquals(state, state.copy())+ assertNotEquals(state, state.copy(hasMic = true))+ assertEquals(voices, state.copy().ttsVoices)+ assertTrue(state.modelReady)+ }++ @Test+ fun voiceUiStateFieldsAndEquality() {+ val voice = TtsVoiceUiState(code = "fr", bcp47 = "fr-FR", nativeName = "Français", englishName = "French")+ assertEquals("fr", voice.code)+ assertEquals("fr-FR", voice.bcp47)+ assertEquals("Français", voice.nativeName)+ assertEquals("French", voice.englishName)+ assertEquals(voice, voice.copy())+ assertNotEquals(voice, voice.copy(code = "de"))+ val (code, bcp47, native, english) = voice+ assertEquals(listOf("fr", "fr-FR", "Français", "French"), listOf(code, bcp47, native, english))+ }++ @Test+ fun voicesFromCatalogMapToUiState() {+ val ui = SupertonicVoices.ALL.map {+ TtsVoiceUiState(it.code, it.bcp47, it.nativeName, it.englishName)+ }+ assertEquals(31, ui.size)+ assertEquals(TtsVoiceUiState("en", "en-US", "English", "English"), ui.first())+ assertEquals("vi", ui.last().code)+ }++ @Test+ fun noopActionsDoNothingAndDoNotThrow() {+ val actions: SpeechSetupActions = SpeechSetupActions.Noop+ actions.requestMicPermission()+ actions.openVoiceInputSettings()+ actions.openTtsSettings()+ actions.refresh()+ // Reaching here without throwing is the contract previews rely on.+ }++ @Test+ fun defaultInterfaceMethodsDoNothing() {+ val actions = object : SpeechSetupActions {}+ actions.requestMicPermission()+ actions.openVoiceInputSettings()+ actions.openTtsSettings()+ actions.refresh()+ }+}
speech/src/test/java/com/vayunmathur/speech/util/WhisperFeaturesExtraTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/util/WhisperFeaturesExtraTest.kt b/speech/src/test/java/com/vayunmathur/speech/util/WhisperFeaturesExtraTest.ktnew file mode 100644index 0000000000..49ddc2b628--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/util/WhisperFeaturesExtraTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.speech.util++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class WhisperFeaturesExtraTest {++ @Test+ fun constantsMatchWhisperBaseContract() {+ assertEquals(16000, WhisperFeatures.SAMPLE_RATE)+ assertEquals(400, WhisperFeatures.N_FFT)+ assertEquals(160, WhisperFeatures.HOP_LENGTH)+ assertEquals(80, WhisperFeatures.N_MELS)+ assertEquals(480000, WhisperFeatures.N_SAMPLES)+ assertEquals(3000, WhisperFeatures.N_FRAMES)+ assertEquals(201, WhisperFeatures.N_BINS)+ }++ @Test+ fun wrongSizedDoubleInputIsRejected() {+ assertFailsWith<IllegalArgumentException> { WhisperFeatures.logMel(DoubleArray(100)) }+ assertFailsWith<IllegalArgumentException> { WhisperFeatures.logMel(DoubleArray(0)) }+ assertFailsWith<IllegalArgumentException> {+ WhisperFeatures.logMel(DoubleArray(WhisperFeatures.N_SAMPLES + 1))+ }+ }++ @Test+ fun emptyShortInputYieldsConstantFloorTensor() {+ val out = WhisperFeatures.logMel(ShortArray(0))+ assertEquals(WhisperFeatures.N_MELS * WhisperFeatures.N_FRAMES, out.size)+ assertTrue(out.all { it == out[0] })+ }++ @Test+ fun pcmPeakNormalisationScalesExtremes() {+ // A full-scale square wave must produce a non-flat tensor bounded by the log rescale.+ val pcm = ShortArray(16000) { if (it % 32 < 16) Short.MAX_VALUE else Short.MIN_VALUE }+ val out = WhisperFeatures.logMel(pcm)+ assertTrue(out.any { it != out[0] })+ assertTrue(out.all { it.isFinite() })+ }++ @Test+ fun fftOfImpulseIsFlat() {+ val n = WhisperFeatures.N_FFT+ val re = DoubleArray(n); re[0] = 1.0+ val im = DoubleArray(n)+ Fft400().transform(re, im)+ for (k in 0 until n) {+ assertEquals(1.0, re[k], 1e-9, "re[$k]")+ assertEquals(0.0, im[k], 1e-9, "im[$k]")+ }+ }++ @Test+ fun fftOfConstantIsDcOnly() {+ val n = WhisperFeatures.N_FFT+ val re = DoubleArray(n) { 1.0 }+ val im = DoubleArray(n)+ Fft400().transform(re, im)+ assertEquals(n.toDouble(), re[0], 1e-6)+ for (k in 1 until n) {+ assertEquals(0.0, re[k], 1e-6, "re[$k]")+ assertEquals(0.0, im[k], 1e-6, "im[$k]")+ }+ }+}
speech/src/test/java/com/vayunmathur/speech/util/WhisperModelAndEngineTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/util/WhisperModelAndEngineTest.kt b/speech/src/test/java/com/vayunmathur/speech/util/WhisperModelAndEngineTest.ktnew file mode 100644index 0000000000..820b7ccf0d--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/util/WhisperModelAndEngineTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.speech.util++import android.content.Context+import android.content.ContextWrapper+import android.content.res.AssetManager+import androidx.test.core.app.ApplicationProvider+import java.io.IOException+import com.vayunmathur.speech.testing.ThrowingDetachFdShadow+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(shadows = [ThrowingDetachFdShadow::class])+class WhisperModelAndEngineTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun modelConstantsPointAtBundledGraph() {+ assertEquals("whisper-base", WhisperModel.DIR)+ assertEquals("whisper_base.maml", WhisperModel.GRAPH)+ }++ @Test+ fun isReadyMatchesAssetListing() {+ val listed = context.assets.list(WhisperModel.DIR)?.toList().orEmpty()+ val expected = WhisperModel.GRAPH in listed+ assertEquals(expected, WhisperModel.isReady(context))+ if (expected) assertTrue(WhisperModel.isReady(context))+ }++ @Test+ fun isReadyIsFalseWhenAssetsThrow() {+ val throwing = object : ContextWrapper(context) {+ override fun getAssets(): AssetManager = throw IOException("boom")+ }+ assertFalse(WhisperModel.isReady(throwing))+ }++ @Test+ fun engineCannotTranscribeWithoutNativeModelAndCloseResets() {+ val engine = WhisperEngine(context)+ assertFalse(engine.isModelPresent())+ assertFalse(engine.preload())+ assertNull(engine.transcribe(ShortArray(1600), "en"))+ assertNull(engine.transcribe(ShortArray(1600), null))+ assertNull(engine.transcribe(ShortArray(0), "auto"))+ assertNull(engine.transcribe(ShortArray(1600), "ja-JP"))+ engine.close()+ // After close the load-failed latch is cleared, so it tries (and fails) again.+ assertFalse(engine.isModelPresent())+ engine.close()+ }++ @Test+ fun engineWithThrowingAssetsReportsUnavailable() {+ val throwing = object : ContextWrapper(context) {+ override fun getAssets(): AssetManager = throw IOException("boom")+ override fun getApplicationContext(): Context = this+ }+ val engine = WhisperEngine(throwing)+ assertFalse(engine.preload())+ assertNull(engine.transcribe(ShortArray(100), "en"))+ engine.close()+ }+}
speech/src/test/java/com/vayunmathur/speech/util/WhisperTokenizerTest.kt
diff --git a/speech/src/test/java/com/vayunmathur/speech/util/WhisperTokenizerTest.kt b/speech/src/test/java/com/vayunmathur/speech/util/WhisperTokenizerTest.ktnew file mode 100644index 0000000000..5a2c36b9a4--- /dev/null+++ b/speech/src/test/java/com/vayunmathur/speech/util/WhisperTokenizerTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.speech.util++import java.io.ByteArrayInputStream+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+class WhisperTokenizerTest {++ private fun tokenizer(vocab: String): WhisperTokenizer =+ WhisperTokenizer.load(ByteArrayInputStream(vocab.toByteArray(Charsets.UTF_8)))++ @Test+ fun decodesPlainAndSpacePrefixedTokens() {+ // Ġ is U+0120, the GPT-2 byte-level spelling of a space.+ val tok = tokenizer("""{"Hello":0,"Ġworld":1,"!":2}""")+ assertEquals("Hello world!", tok.decode(listOf(0, 1, 2)))+ assertEquals("Hello", tok.decode(listOf(0)))+ assertEquals("", tok.decode(emptyList()))+ }++ @Test+ fun decodesMultiByteUtf8AcrossTokenBoundaries() {+ // é is UTF-8 C3 A9; both bytes are printable-range, so the tokens are à and ©.+ val tok = tokenizer("""{"Ã":0,"©":1,"é":2}""")+ assertEquals("é", tok.decode(listOf(2)))+ // Split across two tokens it must still decode once over the whole byte stream.+ assertEquals("é", tok.decode(listOf(0, 1)))+ }++ @Test+ fun decodesShiftedControlByteAlphabet() {+ // Byte 0 maps to U+0100 (Ā), byte 10 (newline) to U+010A (Ċ).+ val tok = tokenizer("""{"Ā":0,"Ċ":1,"a":2}""")+ assertEquals("\u0000\na", tok.decode(listOf(0, 1, 2)))+ }++ @Test+ fun skipsSpecialUnknownAndOutOfRangeIds() {+ val tok = tokenizer("""{"a":0,"b":1}""")+ assertEquals(50257, WhisperTokenizer.FIRST_SPECIAL_ID)+ assertEquals("ab", tok.decode(listOf(0, WhisperTokenizer.FIRST_SPECIAL_ID, 1)))+ assertEquals("ab", tok.decode(listOf(0, 99999, -1, 1)))+ assertEquals("", tok.decode(listOf(50258, 50363)))+ }++ @Test+ fun loadIgnoresIdsOutsideVocabularyRange() {+ val tok = tokenizer("""{"a":0,"bad":-5,"special":50257,"huge":999999}""")+ assertEquals("a", tok.decode(listOf(0)))+ assertEquals("", tok.decode(listOf(-5, 50257, 999999)))+ }++ @Test+ fun loadEmptyVocabularyDecodesNothing() {+ val tok = tokenizer("""{}""")+ assertEquals("", tok.decode(listOf(0, 1, 2)))+ }++ @Test+ fun charactersOutsideByteAlphabetAreDropped() {+ // 中 has no entry in the GPT-2 byte-to-char map, so its bytes contribute nothing.+ val tok = tokenizer("""{"a中b":0,"c":1}""")+ assertEquals("abc", tok.decode(listOf(0, 1)))+ }++ @Test+ fun repeatedTokensRepeatOutput() {+ val tok = tokenizer("""{"ha":0}""")+ assertEquals("hahaha", tok.decode(listOf(0, 0, 0)))+ }+}