Cotton code
162 lines · 5.6 KB · KotlinRaw
package com.cottondb.android.platformimport android.content.Intentimport android.os.Buildimport android.os.Bundleimport android.speech.RecognitionListenerimport android.speech.SpeechRecognizerimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.capture.CaptureSpeechEventimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class AndroidDictationTest {    @Test    fun deniedMicrophoneNeverConstructsARecognizer() = onMain {        val factory = FakeFactory()        val events = mutableListOf<CaptureSpeechEvent>()        AndroidDictation.withBoundary({ false }, factory).start(listOf("Cotton", "Cedar"), events::add)        assertEquals(0, factory.created)        assertEquals(            listOf(                CaptureSpeechEvent.Failed("Dictation needs microphone access — you can turn it on in Settings."),                CaptureSpeechEvent.Ended,            ),            events,        )    }    @Test    fun absentRecognizerIsANamedUnavailableOutcome() = onMain {        val events = mutableListOf<CaptureSpeechEvent>()        val unavailable = object : AndroidSpeechRecognizerFactory {            override fun create(listener: RecognitionListener): AndroidSpeechRecognizerSession =                throw IllegalStateException("No recognizer on this emulator.")        }        AndroidDictation.withBoundary({ true }, unavailable).start(events::add)        assertEquals(            listOf(                CaptureSpeechEvent.Failed("Dictation isn't available on this device right now."),                CaptureSpeechEvent.Ended,            ),            events,        )    }    @Test    fun rawPartialAndFinalAreForwardedAndLateCallbacksAreIgnored() = onMain {        val factory = FakeFactory()        val dictation = AndroidDictation.withBoundary({ true }, factory)        val events = mutableListOf<CaptureSpeechEvent>()        dictation.start(events::add)        assertFalse(factory.session.intent.hasExtra(BIASING_STRINGS_EXTRA))        factory.session.listener.onPartialResults(results("  raw partial  "))        factory.session.listener.onResults(results("raw final"))        factory.session.listener.onPartialResults(results("late text"))        assertEquals(            listOf(                CaptureSpeechEvent.Partial("  raw partial  "),                CaptureSpeechEvent.Final("raw final"),                CaptureSpeechEvent.Ended,            ),            events,        )        assertTrue(factory.session.destroyed)    }    @Test    fun finishWaitsForTheRecognizerFinalBeforeDestroyingIt() = onMain {        val factory = FakeFactory()        val dictation = AndroidDictation.withBoundary({ true }, factory)        val events = mutableListOf<CaptureSpeechEvent>()        dictation.start(events::add)        dictation.finish()        assertTrue(factory.session.stopped)        assertFalse(factory.session.destroyed)        factory.session.listener.onResults(results("final after stop"))        assertEquals(CaptureSpeechEvent.Final("final after stop"), events.first())        assertTrue(factory.session.destroyed)    }    @Test    fun cancelDestroysRecognizerAndIgnoresItsStaleError() = onMain {        val factory = FakeFactory()        val dictation = AndroidDictation.withBoundary({ true }, factory)        val events = mutableListOf<CaptureSpeechEvent>()        dictation.start(events::add)        dictation.cancel()        factory.session.listener.onError(SpeechRecognizer.ERROR_NETWORK)        assertTrue(factory.session.cancelled)        assertTrue(factory.session.destroyed)        assertFalse(events.any { it is CaptureSpeechEvent.Failed })    }    @Test    fun takeBiasTermsAreForwardedInTheirNativeOrderWithoutChangingCaptureStart() = onMain {        val factory = FakeFactory()        val dictation = AndroidDictation.withBoundary({ true }, factory)        val terms = listOf("Cotton", "Cedar", "Cotton", "")        dictation.start(terms) { }        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {            assertEquals(terms, factory.session.intent.getStringArrayListExtra(BIASING_STRINGS_EXTRA))        } else {            assertFalse(factory.session.intent.hasExtra(BIASING_STRINGS_EXTRA))        }    }    private fun results(text: String): Bundle = Bundle().apply {        putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, arrayListOf(text))    }    private fun onMain(block: () -> Unit) {        InstrumentationRegistry.getInstrumentation().runOnMainSync(block)    }    private class FakeFactory : AndroidSpeechRecognizerFactory {        var created = 0        lateinit var session: FakeSession        override fun create(listener: RecognitionListener): AndroidSpeechRecognizerSession {            created += 1            return FakeSession(listener).also { session = it }        }    }    private class FakeSession(        val listener: RecognitionListener,    ) : AndroidSpeechRecognizerSession {        override val onDevice = false        lateinit var intent: Intent        var stopped = false        var cancelled = false        var destroyed = false        override fun startListening(intent: Intent) {            this.intent = intent        }        override fun stopListening() { stopped = true }        override fun cancel() { cancelled = true }        override fun destroy() { destroyed = true }    }    private companion object {        const val BIASING_STRINGS_EXTRA = "android.speech.extra.BIASING_STRINGS"    }}