Cotton code
240 lines · 9.7 KB · KotlinRaw
package com.cottondb.android.ui.navigationimport androidx.activity.compose.setContentimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport android.Manifestimport android.content.ClipboardManagerimport androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.performClickimport androidx.test.ext.junit.runners.AndroidJUnit4import com.cottondb.android.TakeModelsimport com.cottondb.android.capture.CaptureSpeechEventimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.platform.PermissionHarnessActivityimport com.cottondb.android.take.TakePhaseimport com.cottondb.android.take.TakeHandbackimport com.cottondb.android.take.TakeHandbackOutcomeimport com.cottondb.android.take.TakeVoiceimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class TakeHostTest {    @get:Rule    val compose = createAndroidComposeRule<PermissionHarnessActivity>()    private val instrumentation get() = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation()    private val context get() = instrumentation.targetContext    private var fixture: Fixture? = null    @After    fun closeFixture() {        instrumentation.runOnMainSync { fixture?.close() }    }    @Test    fun grantedMicrophoneStartsOnceFinalWritesOnceAndCopyShowsFeedback() {        grantMicrophonePermission()        val host = mount("granted-visit")        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        instrumentation.runOnMainSync { host.voice.final("synthetic final take") }        compose.waitUntil(5_000) { host.core.dictations.get() == 1 }        compose.onNodeWithContentDescription("Copy").performClick()        compose.onNodeWithText("Copied.").assertExists()        val clipboard = context.getSystemService(ClipboardManager::class.java)        assertEquals("synthetic final take", clipboard.primaryClip?.getItemAt(0)?.text)        assertEquals(1, host.core.dictations.get())    }    @Test    fun recreationKeepsTheRetainedVisitAndDoesNotStartRecognitionAgain() {        grantMicrophonePermission()        val host = mount("recreate-visit")        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        compose.activityRule.scenario.recreate()        compose.activityRule.scenario.onActivity { activity ->            activity.setContent {                CottonTheme { TakeHost(host.models, "recreate-visit", {}, { host.voiceFactoryCalls.incrementAndGet(); host.voice }) }            }        }        compose.onNodeWithContentDescription("Done").assertExists()        assertEquals(1, host.voiceFactoryCalls.get())        assertEquals(1, host.core.reads.get())        assertEquals(1, host.voice.starts.get())    }    @Test    fun discardInvokesBackAndReleasesTheListeningVoice() {        grantMicrophonePermission()        val host = mount("discard-visit")        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        compose.onNodeWithContentDescription("Discard").performClick()        assertEquals(1, host.back.get())        assertTrue(host.voice.cancelled.get() > 0)        instrumentation.runOnMainSync { assertEquals(TakePhase.Unavailable, host.models.take("discard-visit") { host.voice }.state.value.phase) }    }    @Test    fun microphoneDeniedBoundaryDoesNotStartVoiceAndExplicitRetryStartsAfterGrant() {        // Android can kill this instrumentation process when its own permission is revoked.        // Exercise denial at the model boundary; PermissionHarnessActivityTest covers the real        // ActivityResult denial callback independently.        val host = Fixture()        fixture = host        val model = host.models.take("denied-visit") { host.voice }        instrumentation.runOnMainSync { model.microphoneDenied() }        assertEquals(TakePhase.Unavailable, model.state.value.phase)        assertEquals(0, host.voice.starts.get())        grantMicrophonePermission()        runBlocking { withContext(Dispatchers.Main) { model.retry()?.join() } }        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        assertEquals(1, host.core.reads.get())    }    @Test    fun publishedHandbackShowsReturnOnlyAfterTheFinalTakeIsPublished() {        grantMicrophonePermission()        val published = AtomicInteger()        val returned = AtomicInteger()        val host = Fixture(TakeHandback { _, _, _ -> published.incrementAndGet(); TakeHandbackOutcome.Published })        fixture = host        compose.setContent {            CottonTheme { TakeHost(host.models, "keyboard-return", {}, { host.voice }, { returned.incrementAndGet() }) }        }        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        compose.onNodeWithContentDescription("Done").performClick()        instrumentation.runOnMainSync { host.voice.final("synthetic return") }        compose.waitUntil(5_000) { published.get() == 1 }        compose.onNodeWithContentDescription("Return to keyboard").performClick()        assertEquals(1, returned.get())    }    @Test    fun failedHandbackLeavesCopyVisibleWithoutReturn() {        grantMicrophonePermission()        val host = Fixture(TakeHandback { _, _, _ -> TakeHandbackOutcome.Failed("Keyboard unavailable; you can still copy this take.") })        fixture = host        compose.setContent { CottonTheme { TakeHost(host.models, "keyboard-failed", {}, { host.voice }, {}) } }        compose.waitUntil(5_000) { host.voice.starts.get() == 1 }        compose.onNodeWithContentDescription("Done").performClick()        instrumentation.runOnMainSync { host.voice.final("synthetic copy") }        compose.waitUntil(5_000) { host.core.dictations.get() == 1 }        compose.onNodeWithContentDescription("Copy").assertExists()        compose.onNodeWithText("Keyboard unavailable; you can still copy this take.").assertExists()        compose.onNodeWithContentDescription("Return to keyboard").assertDoesNotExist()    }    private fun mount(visit: String): Fixture {        val host = Fixture()        fixture = host        compose.setContent {            CottonTheme {                TakeHost(                    models = host.models,                    visit = visit,                    onBack = { host.back.incrementAndGet() },                    voiceFactory = {                        host.voiceFactoryCalls.incrementAndGet()                        host.voice                    },                )            }        }        return host    }    private fun grantMicrophonePermission() {        shell("pm grant ${context.packageName} ${Manifest.permission.RECORD_AUDIO}")        assertTrue(context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED)    }    private fun shell(command: String) {        android.os.ParcelFileDescriptor.AutoCloseInputStream(instrumentation.uiAutomation.executeShellCommand(command)).use { it.readBytes() }    }    private class Fixture(handback: TakeHandback? = null) {        private val job = SupervisorJob()        private val scope = CoroutineScope(job + Dispatchers.Main.immediate)        val core = TakeCore()        val voice = TakeVoiceFake()        val voiceFactoryCalls = AtomicInteger()        val back = AtomicInteger()        val models = TakeModels(core, scope, scope, monotonicMillis = { 1_000L }, handback = handback)        fun close() {            models.retain(emptySet())            scope.cancel()        }    }    private class TakeVoiceFake : TakeVoice {        val starts = AtomicInteger()        val cancelled = AtomicInteger()        private var listener: ((CaptureSpeechEvent) -> Unit)? = null        override fun start(biasTerms: List<String>, listener: (CaptureSpeechEvent) -> Unit) {            starts.incrementAndGet()            this.listener = listener        }        override fun finish() = Unit        override fun cancel() {            cancelled.incrementAndGet()        }        fun final(text: String) {            listener?.invoke(CaptureSpeechEvent.Final(text))        }    }    private class TakeCore : CottonCalling {        override val events: SharedFlow<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        val reads = AtomicInteger()        val dictations = AtomicInteger()        override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) {            "read.take" -> {                reads.incrementAndGet()                Json.parseToJsonElement(                    """{"corpusCount":0,"vocabularyTerms":["Cotton"],"biasTerms":["Cotton"]}""",                )            }            "dictation.create" -> {                dictations.incrementAndGet()                Json.parseToJsonElement("""{"id":"synthetic-take"}""")            }            else -> error("Unexpected Take host core method: $method")        }        override suspend fun close() = Unit    }}