Cotton code
284 lines · 11.6 KB · KotlinRaw
package com.cottondb.android.uiimport androidx.compose.ui.graphics.asAndroidBitmapimport androidx.compose.ui.test.captureToImageimport androidx.compose.ui.test.onRootimport com.cottondb.android.ScreenEvidenceimport androidx.compose.ui.test.junit4.createComposeRuleimport androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.onAllNodesWithTextimport androidx.compose.ui.test.performClickimport androidx.compose.ui.test.performTextInputimport androidx.compose.ui.test.assertIsNotEnabledimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.capture.CaptureModelimport com.cottondb.android.capture.CaptureRepositoryimport com.cottondb.android.capture.CaptureStartimport com.cottondb.android.capture.CaptureStateimport com.cottondb.android.core.CoreExceptionimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonCoreimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.day.thoughts.ThoughtRepositoryimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.ui.capture.CaptureOverlayimport java.io.Fileimport java.util.Base64import java.util.UUIDimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWith/** Compose capture behavior over a real, isolated JNI workspace. */@RunWith(AndroidJUnit4::class)class CaptureScreenTest {    @get:Rule val compose = createComposeRule()    private val context = InstrumentationRegistry.getInstrumentation().targetContext    private val container = File(context.noBackupFilesDir, "capture-ui-test-${UUID.randomUUID()}")    @After    fun removeSyntheticContainer() {        container.deleteRecursively()    }    @Test    fun typedCaptureSavesThroughTheRealJniCore() = runBlocking {        val core = openedCore("Android capture UI test")        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        try {            val model = CaptureModel(CaptureRepository(core))            var kept: String? = null            compose.setContent {                CottonTheme {                    CaptureOverlay(                        model = model,                        start = CaptureStart.Typing,                        writerScope = writerScope,                        requestMicrophone = { error("Typing must not ask for microphone permission.") },                        onKept = { kept = it },                        onClose = {},                    )                }            }            compose.onNodeWithContentDescription("Anything on your mind?")                .performTextInput("JNI Compose capture")            compose.onNodeWithContentDescription("Capture this thought").performClick()            compose.waitUntil(timeoutMillis = 5_000) { kept != null }            val thought = ThoughtRepository(core).read().thoughts.single { it.id == kept }            assertEquals("JNI Compose capture", thought.rawText)        } finally {            writerScope.cancel()            core.close()        }    }    @Test    fun closeDiscardsTheTypedDraftWithoutCreatingACapture() = runBlocking {        val core = openedCore("Android cancelled capture UI test")        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        try {            val model = CaptureModel(CaptureRepository(core))            var closes = 0            compose.setContent {                CottonTheme {                    CaptureOverlay(                        model = model,                        start = CaptureStart.Typing,                        writerScope = writerScope,                        requestMicrophone = { error("Typing must not ask for microphone permission.") },                        onKept = {},                        onClose = { closes += 1 },                    )                }            }            compose.onNodeWithContentDescription("Anything on your mind?")                .performTextInput("draft that must stay local")            compose.onNodeWithContentDescription("Close and discard this capture").performClick()            compose.waitUntil(timeoutMillis = 2_000) { closes == 1 }            assertTrue(ThoughtRepository(core).read().thoughts.isEmpty())        } finally {            writerScope.cancel()            core.close()        }    }    @Test    fun deniedMicrophoneKeepsTheOverlayAndNamesTheRequiredPermission() = runBlocking {        val core = openedCore("Android capture permission UI test")        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        try {            val model = CaptureModel(CaptureRepository(core))            compose.setContent {                CottonTheme {                    CaptureOverlay(                        model = model,                        start = CaptureStart.Listening,                        writerScope = writerScope,                        requestMicrophone = { result -> result(false) },                        onKept = {},                        onClose = {},                    )                }            }            val message = "Dictation needs microphone access — you can turn it on in Settings."            compose.waitUntil(timeoutMillis = 2_000) {                compose.onAllNodesWithText(message).fetchSemanticsNodes().isNotEmpty()            }            compose.onNodeWithText(message).assertExists()            compose.onNodeWithText("Keep editing").performClick()            compose.onNodeWithContentDescription("Anything on your mind?").assertExists()            assertTrue(ThoughtRepository(core).read().thoughts.isEmpty())        } finally {            writerScope.cancel()            core.close()        }    }    @Test    fun malformedCreateFreezesTheDraftWithoutASecondSendOrListenAndCanClose() = runBlocking {        val core = FakeCaptureCore(JsonPrimitive("not a receipt"))        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        try {            val model = CaptureModel(CaptureRepository(core))            var microphoneRequests = 0            var closes = 0            compose.setContent {                CottonTheme {                    CaptureOverlay(                        model = model,                        start = CaptureStart.Typing,                        writerScope = writerScope,                        requestMicrophone = { microphoneRequests += 1 },                        onKept = {},                        onClose = { closes += 1 },                    )                }            }            compose.onNodeWithContentDescription("Anything on your mind?")                .performTextInput("draft whose receipt is malformed")            compose.onNodeWithContentDescription("Capture this thought").performClick()            val warning = "The capture may have been saved, so it will not be sent again."            compose.waitUntil(2_000) {                compose.onAllNodesWithText(warning).fetchSemanticsNodes().isNotEmpty()            }            ScreenEvidence.capture("capture-unconfirmed") { compose.onRoot().captureToImage().asAndroidBitmap() }            assertEquals(1, core.calls)            assertEquals(                "draft whose receipt is malformed",                (model.state.value as CaptureState.Error).draft,            )            compose.onNodeWithContentDescription("Speak a thought").assertIsNotEnabled()            compose.onNodeWithContentDescription("Capture this thought").assertIsNotEnabled()            assertTrue(compose.onAllNodesWithText("Keep editing").fetchSemanticsNodes().isEmpty())            assertEquals(0, microphoneRequests)            compose.onNodeWithContentDescription("Close capture").performClick()            compose.waitUntil(2_000) { closes == 1 }            assertEquals(1, core.calls)            assertEquals(0, microphoneRequests)        } finally {            writerScope.cancel()        }    }    @Test    fun knownRefusalKeepsTheRetryableEditingDialog() = runBlocking {        val core = FakeCaptureCore(            CoreException("capture_refused", "Synthetic refusal", null),            buildJsonObject { put("id", "capture-1") },        )        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        try {            val model = CaptureModel(CaptureRepository(core))            var kept: String? = null            compose.setContent {                CottonTheme {                    CaptureOverlay(                        model = model,                        start = CaptureStart.Typing,                        writerScope = writerScope,                        requestMicrophone = { error("Typing must not request a microphone.") },                        onKept = { kept = it },                        onClose = {},                    )                }            }            compose.onNodeWithContentDescription("Anything on your mind?").performTextInput("retryable draft")            compose.onNodeWithContentDescription("Capture this thought").performClick()            compose.waitUntil(2_000) {                compose.onAllNodesWithText("Synthetic refusal").fetchSemanticsNodes().isNotEmpty()            }            compose.onNodeWithText("Keep editing").performClick()            compose.onNodeWithContentDescription("Capture this thought").performClick()            compose.waitUntil(2_000) { kept == "capture-1" }            assertEquals(2, core.calls)        } finally {            writerScope.cancel()        }    }    private suspend fun openedCore(deviceName: String): CottonCore {        val core = CottonCore.open(buildJsonObject {            put("containerPath", container.absolutePath)            put("appVersion", "0.0.0-instrumented")            put("timeZone", "Etc/UTC")            put("deviceSecret", SYNTHETIC_DEVICE_SEED)        })        core.call("workspace.startLocal", buildJsonObject {            put("deviceName", deviceName)            put("appVersion", "0.0.0-instrumented")        })        return core    }    private companion object {        val SYNTHETIC_DEVICE_SEED: String = Base64.getUrlEncoder().withoutPadding()            .encodeToString(ByteArray(32) { 0x63 })    }}private class FakeCaptureCore(vararg replies: Any) : CottonCalling {    override val events: SharedFlow<CottonEvent> = MutableSharedFlow()    override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()    private val replies = ArrayDeque(replies.toList())    var calls = 0        private set    override suspend fun call(method: String, request: JsonObject): JsonElement {        check(method == "capture.create")        calls += 1        return when (val reply = replies.removeFirst()) {            is Throwable -> throw reply            is JsonElement -> reply            else -> error("Unsupported fake reply: ${reply::class}")        }    }    override suspend fun close() = Unit}