153 lines · 6.7 KB · KotlinRaw
package com.cottondb.android.keyboardimport android.Manifestimport android.content.Intentimport android.content.pm.PackageManagerimport android.os.ParcelFileDescriptorimport androidx.test.platform.app.InstrumentationRegistryimport androidx.test.uiautomator.Byimport androidx.test.uiautomator.UiDeviceimport androidx.test.uiautomator.Untilimport com.cottondb.android.CottonApplicationimport com.cottondb.android.MainActivityimport com.cottondb.android.RuntimeStateimport com.cottondb.android.boot.BootStateimport java.util.concurrent.TimeUnitimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withTimeoutimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.booleanimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitive/** * Serial emulator fixture for real-IME scenarios. * * It owns every device-wide setting it changes, restores the complete raw channel rather than * reconstructing it, and uses the production boot gate to create a local synthetic workspace. */class ImeTestFixture { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private val device = UiDevice.getInstance(instrumentation) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private val imeId = "${context.packageName}/com.cottondb.android.keyboard.CottonInputMethodService" private val priorIme = shell("settings get secure default_input_method").trim() private val priorHardware = shell("settings get secure show_ime_with_hard_keyboard").trim() private val wasEnabled = shell("ime list -s").lineSequence().any { it.trim() == imeId } private val hadMicrophone = context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED private val store = AndroidKeyboardChannelStore.open(context, scope) private val original: JsonObject = runBlocking { store.read() } fun enableCottonImeAndMicrophone() { shell("settings put secure show_ime_with_hard_keyboard 1") shell("ime enable $imeId") shell("ime set $imeId") shell("pm grant ${context.packageName} ${Manifest.permission.RECORD_AUDIO}") } /** Starts the actual application and, on a fresh test install, starts its local workspace. */ fun bootReadySyntheticWorkspace() { context.startActivity( Intent(context, MainActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP), ) val runtime = context.applicationContext as CottonApplication val ready = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { runtime.runtime.state.first { it is RuntimeState.Ready || it is RuntimeState.Error } } } check(ready is RuntimeState.Ready) { "Cotton did not open for the IME handback test: ${(ready as RuntimeState.Error).message}" } val boot = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { ready.boot.state.first { it is BootState.Start || it is BootState.Ready || it is BootState.Error } } } if (boot is BootState.Start) { check(device.wait(Until.hasObject(By.desc("Start a new database")), UI_TIMEOUT_MILLIS)) { "The app reported a fresh workspace but did not show the production start control." } device.findObject(By.desc("Start a new database")).click() } val settled = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { ready.boot.state.first { it is BootState.Ready || it is BootState.Error } } } check(settled is BootState.Ready) { "The synthetic local workspace did not become ready: ${(settled as BootState.Error).message}" } } suspend fun readChannel(): JsonObject = store.read() suspend fun updateChannel(transform: (JsonObject) -> JsonObject): JsonObject = store.update(transform) fun launchExternalEditor() { context.startActivity( Intent(context, ExternalEditorHarnessActivity::class.java) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP), ) check(device.wait(Until.hasObject(By.desc("External keyboard editor")), UI_TIMEOUT_MILLIS)) { "The external editor did not open." } device.findObject(By.text("Show keyboard")).click() } /** The bridge can consume the receipt immediately, so no assertion inspects the outbox. */ fun awaitTakeAcknowledgement(text: String) = runBlocking { withTimeout(UI_TIMEOUT_MILLIS) { while (true) { val snapshot = store.read()[KeyboardChannelKeys.SNAPSHOT] as? JsonObject val received = snapshot?.get("takes")?.jsonArray ?.map { it.jsonObject } ?.firstOrNull { it["text"]?.jsonPrimitive?.content == text } if (received != null && received["pending"]?.jsonPrimitive?.boolean == false) return@withTimeout delay(POLL_MILLIS) } } } fun closeExternalEditorIfOpen() { if (!device.hasObject(By.desc("External keyboard editor"))) return device.pressBack() if (device.wait(Until.hasObject(By.desc("External keyboard editor")), SHORT_UI_TIMEOUT_MILLIS)) { device.pressBack() } } fun restore() = runBlocking { try { if (priorIme.isNotBlank() && priorIme != "null") shell("ime set $priorIme") if (!wasEnabled) shell("ime disable $imeId") if (priorHardware == "null") shell("settings delete secure show_ime_with_hard_keyboard") else shell("settings put secure show_ime_with_hard_keyboard $priorHardware") store.update { original } if (!hadMicrophone) shell("pm revoke ${context.packageName} ${Manifest.permission.RECORD_AUDIO}") } finally { scope.cancel() } } private fun shell(command: String): String = ParcelFileDescriptor.AutoCloseInputStream(instrumentation.uiAutomation.executeShellCommand(command)) .bufferedReader() .use { it.readText() } private companion object { const val POLL_MILLIS = 100L val SHORT_UI_TIMEOUT_MILLIS = TimeUnit.MILLISECONDS.toMillis(500L) val UI_TIMEOUT_MILLIS = TimeUnit.SECONDS.toMillis(12L) }}