Modern Apps git

← Modern-Apps.git

passwords: add tests for pages, relay, autofill and repository

Commit
a5d8a3c2be7f7412451be4cfa61b4628e60579ac
Author
Vayun Mathur <[email protected]>
When
2026-11-16 13:55 UTC (20 days ago)
Parents
e6d28e7
Coverage work for the passwords module only, measured with
:passwords:createMergedCoverageReport before and after.

Covered 24405 -> 28978 instructions (+4573, missed 11332 -> 6759),
past the +3000 goal.

New tests:
- PageWrappersComposeTest renders the ViewModel-backed PasskeyPage,
  PasswordPage, PasswordEditPage, MenuPage and Navigation composables.
  The Room-backed stateIn flows are replaced with plain MutableStateFlows
  in the test because collecting the real ones opens SQLCipher, whose
  native library is unavailable under Robolectric and whose Error escapes
  the sharing coroutine; page state resolution, draft seeding and
  rendering run for real, for auto/manual/detached/unlinked passkeys,
  unknown ids and standalone-passkey navigation.
- RelayProviderDispatchTest drives every RelayPasswordProvider CRUD
  route to the vault boundary and asserts the cursor builders and the
  relay content hash (identity-stripped, deletion-sensitive, SHA-256)
  on their actual output.
- PasswordRepositoryDelegationTest asserts every repository method
  delegates to its DAO (surfacing the SQLCipher boundary under
  Robolectric) and exercises SnapshotStore for real against an
  in-memory SyncSnapshotDao.
- AutofillServiceDispatchTest builds a real AssistStructure tree
  reflectively and runs PasswordAutofillService.StructureParser,
  onFillRequest and onSaveRequest through recording framework
  callbacks, plus the matchesContext and createPresentations helpers.
- PasswordsViewModelCsvInternalsTest pins the CSV import stages:
  parseCsv quoting/escapes/CRLF/multiline, buildPassword mapping,
  otpauth secret extraction, per-source website splitting and the
  non-login type prefix.
- KdbxSyncEngineRepoAdapterTest invokes every repository DAO adapter
  the repository-backed sync engine builds, and
  KdbxBackupFormatVaultPathTest takes KDBX import/export (real native
  codec) to the first repository upsert/read.

Skipped, with reasons: CableSession/CableTunnel (websocket to the
caBLE tunnel server plus BLE advertising; its run() would need a live
network peer), the PasskeyEntries repository DAO adapters beyond the
options its public function actually calls, PasskeyAuthActivity flows
past the vault lookup, and PasswordsViewModel upsert/delete coroutines
(their SQLCipher Error escapes on a background dispatcher under
Robolectric). No production code changed and no dead code removed.

Verified without the CI ignore file:
./gradlew :passwords:testDevUnitTest :passwords:detekt :passwords:lint
all green (432 tests, 0 failures).

Diff

passwords/src/test/java/com/vayunmathur/passwords/data/PasswordRepositoryDelegationTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordRepositoryDelegationTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordRepositoryDelegationTest.ktnew file mode 100644index 0000000000..7bb36d5b21--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordRepositoryDelegationTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.passwords.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import kotlinx.coroutines.runBlocking+import org.junit.Before+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.assertFailsWith+import kotlin.test.assertTrue++/**+ * [PasswordRepository] persistence delegation.+ *+ * Every repository method is a one-line delegation to a Room DAO over the+ * SQLCipher database. That database's native library is unavailable under+ * Robolectric, so each delegation surfaces [UnsatisfiedLinkError] when it+ * first opens the vault — which still proves the method reaches its DAO+ * (rather than, say, returning a stub or swallowing the call), and pins the+ * documented on-device-only boundary. [SnapshotStore] is exercised for real+ * against an in-memory [SyncSnapshotDao].+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordRepositoryDelegationTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private fun repo() = PasswordRepository.get(ctx)++    @Test fun passwordReadsAndWritesDelegateToDao() {+        val repo = repo()+        val password = Password(id = 1, name = "A", syncId = "s-1")+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getAllPasswords() } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasswordById(1) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasswordBySyncId("s-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasswordsUpdatedSince(0) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.upsertPassword(password) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.upsertPasswordRaw(password) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deletePassword(password) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deletePasswordBySyncId("s-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deleteAllPasswords() } }+    }++    @Test fun passkeyReadsAndWritesDelegateToDao() {+        val repo = repo()+        val passkey = Passkey(id = 2, rpId = "example.com", syncId = "pk-1")+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getAllPasskeys() } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasskeyBySyncId("pk-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasskeysUpdatedSince(0) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasskeysByRpId("example.com") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.getPasskeyByCredentialId("cred") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.upsertPasskey(passkey) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.upsertPasskeyRaw(passkey) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deletePasskey(passkey) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deletePasskeyBySyncId("pk-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { repo.deleteAllPasskeys() } }+    }++    @Test fun transactionDelegatesToDatabase() {+        assertFailsWith<UnsatisfiedLinkError> {+            runBlocking { repo().withTransaction { "inside" } }+        }+    }++    // ---- SnapshotStore against an in-memory DAO (real behaviour) ----++    private class FakeSnapshotDao : SyncSnapshotDao {+        val store = linkedMapOf<String, SyncSnapshot>()+        override suspend fun getAll(): List<SyncSnapshot> = store.values.toList()+        override suspend fun upsert(snapshot: SyncSnapshot) { store[snapshot.syncId] = snapshot }+        override suspend fun deleteBySyncId(syncId: String) { store.remove(syncId) }+        override suspend fun deleteByKind(kind: String) {+            store.values.removeAll { it.kind == kind }+        }+        override suspend fun deleteAll() = store.clear()+    }++    @Test fun snapshotStoreCrudAndKindDeletes() = runBlocking {+        val dao = FakeSnapshotDao()+        val store = SnapshotStore(dao)+        assertTrue(store.getAll().isEmpty())++        store.upsert(SyncSnapshot("a", SyncSnapshot.KIND_PASSWORD, "h1", 1, 2, 3))+        store.upsert(SyncSnapshot("b", SyncSnapshot.KIND_PASSKEY, "h2", 4, 5, 6))+        store.upsert(SyncSnapshot("c", SyncSnapshot.KIND_PASSWORD, "h3", 7, 8, 9))+        assertEquals(listOf("a", "b", "c"), store.getAll().map { it.syncId })++        // Upsert replaces by primary key.+        store.upsert(SyncSnapshot("a", SyncSnapshot.KIND_PASSWORD, "h1b", 10, 2, 3))+        assertEquals("h1b", store.getAll().first { it.syncId == "a" }.contentHash)+        assertEquals(3, store.getAll().size)++        store.deleteByKind(SyncSnapshot.KIND_PASSWORD)+        assertEquals(listOf("b"), store.getAll().map { it.syncId })++        store.deleteBySyncId("b")+        assertTrue(store.getAll().isEmpty())++        store.upsert(SyncSnapshot("z", SyncSnapshot.KIND_PASSKEY, "hz", 0, 0, 0))+        store.deleteAll()+        assertTrue(store.getAll().isEmpty())+        // Deleting a missing id is a no-op.+        store.deleteBySyncId("missing")+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.ktnew file mode 100644index 0000000000..426e3f4462--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/AutofillServiceDispatchTest.kt@@ -0,0 +1,287 @@+package com.vayunmathur.passwords.platform++import android.app.assist.AssistStructure+import android.content.ComponentName+import android.os.Bundle+import android.os.CancellationSignal+import android.service.autofill.FillCallback+import android.service.autofill.FillContext+import android.service.autofill.FillRequest+import android.service.autofill.Presentations+import android.service.autofill.SaveCallback+import android.service.autofill.SaveRequest+import android.view.autofill.AutofillId+import android.view.autofill.AutofillValue+import com.vayunmathur.library.util.DatabaseHelper+import com.vayunmathur.passwords.FakeAndroidKeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.RuntimeEnvironment+import org.robolectric.annotation.Config+import java.lang.reflect.Proxy+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [PasswordAutofillService] and its structure parser.+ *+ * The autofill framework classes have no public constructors, so requests,+ * contexts and view nodes are assembled reflectively from the framework's+ * own classes (the same technique the credential-provider guard tests use):+ * a [AssistStructure] tree carrying a username node, a password node and a+ * web domain, driven through the real parser and service entry points.+ * Callbacks are the framework callbacks backed by a recording AIDL proxy,+ * so "the service answered with no datasets" is asserted, not assumed.+ * Matching itself needs the SQLCipher vault (unavailable under+ * Robolectric), so the fill/save paths that reach the vault surface its+ * [UnsatisfiedLinkError] after the parser has run.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class AutofillServiceDispatchTest {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val app get() = RuntimeEnvironment.getApplication()++    // ---- framework object assembly ----++    private fun <T> construct(className: String, types: List<Class<*>>, args: List<Any?>): T {+        val ctor = Class.forName(className).getDeclaredConstructor(*types.toTypedArray())+        ctor.isAccessible = true+        @Suppress("UNCHECKED_CAST")+        return ctor.newInstance(*args.toTypedArray()) as T+    }++    private fun setField(target: Any, name: String, value: Any?) {+        val field = target.javaClass.getDeclaredField(name)+        field.isAccessible = true+        field.set(target, value)+    }++    private fun autofillId(id: Int): AutofillId = construct(+        "android.view.autofill.AutofillId", listOf(Integer.TYPE), listOf(id),+    )++    private fun viewNode(+        id: Int,+        hints: Array<String>? = null,+        idEntry: String? = null,+        inputType: Int = 0,+        text: String? = null,+        webDomain: String? = null,+        children: List<Any> = emptyList(),+    ): Any {+        val node: Any = construct("android.app.assist.AssistStructure\$ViewNode", emptyList(), emptyList())+        setField(node, "mAutofillId", autofillId(id))+        if (hints != null) setField(node, "mAutofillHints", hints)+        if (idEntry != null) setField(node, "mIdEntry", idEntry)+        setField(node, "mInputType", inputType)+        // The parser reads the autofill value first, so that alone carries the text.+        if (text != null) setField(node, "mAutofillValue", AutofillValue.forText(text))+        if (webDomain != null) setField(node, "mWebDomain", webDomain)+        val nodeArray = java.lang.reflect.Array.newInstance(node.javaClass, children.size)+        children.forEachIndexed { index, child -> java.lang.reflect.Array.set(nodeArray, index, child) }+        setField(node, "mChildren", nodeArray)+        return node+    }++    private fun fillContext(root: Any): FillContext {+        val window: Any = construct(+            "android.app.assist.AssistStructure\$WindowNode", emptyList(), emptyList(),+        )+        setField(window, "mRoot", root)+        val structure: AssistStructure = construct(+            "android.app.assist.AssistStructure", emptyList(), emptyList(),+        )+        setField(structure, "mWindowNodes", arrayListOf(window))+        setField(structure, "mActivityComponent", ComponentName("com.example.app", "LoginActivity"))+        return construct(+            "android.service.autofill.FillContext",+            listOf(Integer.TYPE, AssistStructure::class.java, AutofillId::class.java),+            listOf(1, structure, autofillId(10)),+        )+    }++    private fun loginContext(): FillContext {+        val username = viewNode(11, hints = arrayOf("username"), text = "alice")+        val password = viewNode(12, hints = arrayOf("password"), text = "s3cret", inputType = 0x81)+        val root = viewNode(10, webDomain = "login.example.com", children = listOf(username, password))+        return fillContext(root)+    }++    private class CallbackLog {+        val calls = mutableListOf<Pair<String, Any?>>()+        fun proxy(interfaceName: String): Any {+            val iface = Class.forName(interfaceName)+            return Proxy.newProxyInstance(iface.classLoader, arrayOf(iface)) { _, method, args ->+                calls += method.name to args?.firstOrNull()+                null+            }+        }+    }++    private fun fillCallback(log: CallbackLog): FillCallback = construct(+        "android.service.autofill.FillCallback",+        listOf(Class.forName("android.service.autofill.IFillCallback"), Integer.TYPE),+        listOf(log.proxy("android.service.autofill.IFillCallback"), 1),+    )++    private fun saveCallback(log: CallbackLog): SaveCallback = construct(+        "android.service.autofill.SaveCallback",+        listOf(Class.forName("android.service.autofill.ISaveCallback")),+        listOf(log.proxy("android.service.autofill.ISaveCallback")),+    )++    private fun fillRequest(contexts: List<FillContext>): FillRequest = construct(+        "android.service.autofill.FillRequest",+        listOf(+            Integer.TYPE, List::class.java, List::class.java, Bundle::class.java,+            Integer.TYPE, Class.forName("android.view.inputmethod.InlineSuggestionsRequest"),+            android.content.IntentSender::class.java,+        ),+        listOf(1, contexts, emptyList<String>(), Bundle(), 0, null, null),+    )++    private fun saveRequest(contexts: List<FillContext>): SaveRequest = construct(+        "android.service.autofill.SaveRequest",+        listOf(ArrayList::class.java, Bundle::class.java, ArrayList::class.java),+        listOf(ArrayList(contexts), null, null),+    )++    private fun service() =+        Robolectric.buildService(PasswordAutofillService::class.java).create().get()++    // ---- StructureParser (private; invoked on the real framework tree) ----++    @Test fun structureParserExtractsCredentialsAndDomain() {+        val parserClass = Class.forName(+            "com.vayunmathur.passwords.platform.PasswordAutofillService\$StructureParser",+        )+        val ctor = parserClass.getDeclaredConstructor(List::class.java)+        ctor.isAccessible = true+        val parser = ctor.newInstance(listOf(loginContext()))++        fun field(name: String): Any? {+            val f = parserClass.getDeclaredField(name)+            f.isAccessible = true+            return f.get(parser)+        }+        assertEquals(autofillId(11), field("usernameId"))+        assertEquals(autofillId(12), field("passwordId"))+        assertEquals("alice", field("usernameText"))+        assertEquals("s3cret", field("passwordText"))+        assertEquals("login.example.com", field("webDomain"))+    }++    @Test fun structureParserEmptyAndPasswordOnlyTrees() {+        val parserClass = Class.forName(+            "com.vayunmathur.passwords.platform.PasswordAutofillService\$StructureParser",+        )+        val ctor = parserClass.getDeclaredConstructor(List::class.java)+        ctor.isAccessible = true++        val empty = ctor.newInstance(emptyList<FillContext>())+        fun field(target: Any, name: String): Any? {+            val f = parserClass.getDeclaredField(name)+            f.isAccessible = true+            return f.get(target)+        }+        assertNull(field(empty, "usernameId"))+        assertNull(field(empty, "passwordId"))+        assertNull(field(empty, "webDomain"))++        // Password detection by input type alone (no hints), nested one level down,+        // and a username detected by its idEntry rather than hints.+        val password = viewNode(22, text = "pw", inputType = 0x81)+        val username = viewNode(21, idEntry = "login_email", text = "[email protected]")+        val mid = viewNode(20, children = listOf(username, password))+        val root = viewNode(19, children = listOf(mid))+        val parsed = ctor.newInstance(listOf(fillContext(root)))+        assertEquals(autofillId(21), field(parsed, "usernameId"))+        assertEquals("[email protected]", field(parsed, "usernameText"))+        assertEquals(autofillId(22), field(parsed, "passwordId"))+        assertEquals("pw", field(parsed, "passwordText"))+    }++    // ---- Service entry points ----++    @Test fun fillRequestWithoutVaultKeyAnswersNull() {+        val log = CallbackLog()+        service().onFillRequest(fillRequest(listOf(loginContext())), CancellationSignal(), fillCallback(log))+        assertEquals(listOf("onSuccess" to null), log.calls.map { it.first to it.second })+    }++    @Test fun fillRequestWithVaultKeyButNoPasswordFieldAnswersNull() {+        DatabaseHelper(app).storePassphrase("vault-pw")+        val log = CallbackLog()+        // A tree with only a username field: nothing to fill into.+        val root = viewNode(30, children = listOf(viewNode(31, hints = arrayOf("username"), text = "alice")))+        service().onFillRequest(fillRequest(listOf(fillContext(root))), CancellationSignal(), fillCallback(log))+        assertEquals(1, log.calls.size)+        assertEquals("onSuccess", log.calls.single().first)+        assertNull(log.calls.single().second)+    }++    @Test fun fillRequestWithPasswordFieldReachesVault() {+        DatabaseHelper(app).storePassphrase("vault-pw")+        val log = CallbackLog()+        assertFailsWith<UnsatisfiedLinkError> {+            service().onFillRequest(fillRequest(listOf(loginContext())), CancellationSignal(), fillCallback(log))+        }+    }++    @Test fun saveRequestWithBlankCredentialsAnswersWithoutVault() {+        val log = CallbackLog()+        service().onSaveRequest(saveRequest(emptyList()), saveCallback(log))+        assertEquals(listOf("onSuccess"), log.calls.map { it.first })+    }++    @Test fun saveRequestWithCredentialsReachesVault() {+        assertFailsWith<UnsatisfiedLinkError> {+            service().onSaveRequest(saveRequest(listOf(loginContext())), saveCallback(CallbackLog()))+        }+    }++    // ---- matchesContext / createPresentations (private helpers) ----++    @Test fun matchesContextPackageAndWebRules() {+        val svc = service()+        val method = PasswordAutofillService::class.java.getDeclaredMethod(+            "matchesContext", String::class.java, String::class.java, String::class.java,+        )+        method.isAccessible = true+        fun matches(site: String, pkg: String?, web: String?): Boolean =+            method.invoke(svc, site, pkg, web) as Boolean++        // Package matching: exact, android-app:// spelling, case/space tolerant.+        assertTrue(matches("com.example.app", "com.example.app", null))+        assertTrue(matches("android-app://com.example.app", "COM.EXAMPLE.APP", null))+        assertTrue(matches(" com.example.app/ ", "com.example.app", null))+        // Web matching: a stored parent fills on subdomains, not vice versa.+        assertTrue(matches("example.com", null, "login.example.com"))+        assertTrue(matches("example.com", null, "https://example.com/login"))+        assertEquals(false, matches("login.example.com", null, "example.com"))+        assertEquals(false, matches("other.com", null, "example.com"))+        assertEquals(false, matches("example.com", "com.other.app", null))+        assertEquals(false, matches("example.com", null, null))+    }++    @Test fun createPresentationsWithoutInlineSpecBuildsMenuPresentation() {+        val svc = service()+        val method = PasswordAutofillService::class.java.getDeclaredMethod(+            "createPresentations", String::class.java,+            Class.forName("android.widget.inline.InlinePresentationSpec"),+        )+        method.isAccessible = true+        val presentations = method.invoke(svc, "GitHub", null) as Presentations+        assertNotNull(presentations)+        assertNotNull(presentations.menuPresentation)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatVaultPathTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatVaultPathTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatVaultPathTest.ktnew file mode 100644index 0000000000..57a9f06b25--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatVaultPathTest.kt@@ -0,0 +1,67 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.sync.EntryMapper+import com.vayunmathur.passwords.sync.NativeKdbxCodec+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertFailsWith++/**+ * [KdbxBackupFormat] paths that reach the vault. The KDBX codec is native+ * and runs for real in these tests (it is the same Rust library the unit+ * tests for the sync codec use), so an import file carrying entries is+ * genuinely decoded and mapped through [EntryMapper] before the first+ * repository upsert — which is where the SQLCipher boundary (unavailable+ * under Robolectric) surfaces. Export likewise reads the vault first.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxBackupFormatVaultPathTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private fun format() = KdbxBackupFormat(PasswordRepository.get(app))++    @Test fun exportWithPasswordReadsVaultFirst() {+        assertFailsWith<UnsatisfiedLinkError> {+            runBlocking { format().export(app, "pw", ByteArrayOutputStream()) }+        }+    }++    @Test fun importWithPasswordEntryReachesRepositoryUpsert() {+        val entry = EntryMapper.toFields(+            Password(name = "Mail", username = "alice", password = "secret", syncId = "pw-1"),+        )+        val bytes = NativeKdbxCodec.write("pw", listOf(entry))!!+        assertFailsWith<UnsatisfiedLinkError> {+            runBlocking { format().import(app, "pw", ByteArrayInputStream(bytes)) }+        }+    }++    @Test fun importWithPasskeyEntryReachesRepositoryUpsert() {+        val entry = EntryMapper.toFields(+            Passkey(+                rpId = "example.com", rpName = "Example", credentialId = "cred-1",+                userName = "alice", privateKeyBytes = byteArrayOf(1, 2, 3), syncId = "pk-1",+            ),+        )+        val bytes = NativeKdbxCodec.write("pw", listOf(entry))!!+        assertFailsWith<UnsatisfiedLinkError> {+            runBlocking { format().import(app, "pw", ByteArrayInputStream(bytes)) }+        }+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelCsvInternalsTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelCsvInternalsTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelCsvInternalsTest.ktnew file mode 100644index 0000000000..cab458d8bd--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelCsvInternalsTest.kt@@ -0,0 +1,152 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.domain.ImportSource+import org.junit.Before+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.assertNull+import kotlin.test.assertTrue++/**+ * The CSV-import internals of [PasswordsViewModel] that the public import+ * flow is built from. End-to-end row imports cannot run under Robolectric+ * (the upsert opens SQLCipher), so these pure stages — CSV parsing, column+ * mapping into a [Password], TOTP extraction, website splitting and the+ * type-prefix naming rule — are pinned directly at the private functions+ * the flow calls, with the same inputs the flow would feed them.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordsViewModelCsvInternalsTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private fun vm() = PasswordsViewModel(app, PasswordRepository.get(app))++    @Suppress("UNCHECKED_CAST")+    private fun <T> call(name: String, vararg args: Any?): T {+        val method = PasswordsViewModel::class.java.declaredMethods+            .first { it.name == name && it.parameterCount == args.size }+        method.isAccessible = true+        return method.invoke(vm(), *args) as T+    }++    private fun columns(+        name: Int = 0, username: Int = 1, password: Int = 2, url: Int = 3,+        totp: Int = 4, email: Int = 5, note: Int = 6, type: Int = 7,+    ) = PasswordsViewModel.ImportColumns(name, username, password, url, totp, email, note, type)++    // ---- parseCsv ----++    @Test fun parseCsvHandlesQuotingEscapesAndLineEndings() {+        val text = "name,user,pass\r\n" ++            "\"Git, Hub\",\"octo\",\"p\"\"w\"\n" ++            "\"multi\nline\",u2,p2\n" ++            "trailing,u3,p3"+        val rows: List<List<String>> = call("parseCsv", text)+        assertEquals(4, rows.size)+        assertEquals(listOf("name", "user", "pass"), rows[0])+        assertEquals(listOf("Git, Hub", "octo", "p\"w"), rows[1])+        assertEquals(listOf("multi\nline", "u2", "p2"), rows[2])+        // A final row without a trailing newline is still flushed.+        assertEquals(listOf("trailing", "u3", "p3"), rows[3])+    }++    @Test fun parseCsvEmptyAndNewlineOnlyInputs() {+        assertEquals(emptyList(), call<List<List<String>>>("parseCsv", ""))+        assertEquals(listOf(listOf("a")), call<List<List<String>>>("parseCsv", "a\n"))+        assertEquals(listOf(listOf("a", "b")), call<List<List<String>>>("parseCsv", "a,b\r\n"))+    }++    // ---- buildPassword / its helpers ----++    @Test fun buildPasswordMapsColumnsAndExtractsTotpUri() {+        val row = listOf(+            "Mail", "alice", "secret",+            "https://mail.example, https://webmail.example",+            "otpauth://totp/Mail:alice?secret=JBSWY3DP&issuer=Mail",+            "[email protected]", "a note", "login",+        )+        val built: Password = call("buildPassword", row, columns(), ImportSource.PROTON_PASS)+        assertEquals("Mail", built.name)+        assertEquals("alice", built.username)+        assertEquals("[email protected]", built.email)+        assertEquals("secret", built.password)+        assertEquals("a note", built.note)+        assertEquals("JBSWY3DP", built.totpSecret)+        // Proton Pass is the source that splits websites on commas.+        assertEquals("https://mail.example|https://webmail.example", built.websites.joinToString("|"))+    }++    @Test fun buildPasswordToleratesShortRowsAndPrefixesNonLoginTypes() {+        val sparse: Password = call(+            "buildPassword", listOf("Only Name"), columns(), ImportSource.BITWARDEN,+        )+        assertEquals("Only Name", sparse.name)+        assertEquals("", sparse.username)+        assertEquals("", sparse.password)+        assertNull(sparse.totpSecret)+        assertEquals(emptyList(), sparse.websites)++        // Non-login rows are prefixed with their type; a missing name falls+        // back to the URL and is prefixed the same way.+        val ssh: Password = call(+            "buildPassword",+            listOf("Tyche", "", "key", "", "", "", "", "sshKey"),+            columns(), ImportSource.BITWARDEN,+        )+        assertEquals("sshKey: Tyche", ssh.name)+        val unnamed: Password = call(+            "buildPassword",+            listOf("", "", "", "https://host.example", "", "", "", "card"),+            columns(), ImportSource.BITWARDEN,+        )+        assertEquals("card: https://host.example", unnamed.name)+        // "login" (any case) is never prefixed.+        val login: Password = call(+            "buildPassword",+            listOf("Plain", "", "", "", "", "", "", "LOGIN"),+            columns(), ImportSource.BITWARDEN,+        )+        assertEquals("Plain", login.name)+    }++    @Test fun totpExtractionVariants() {+        assertNull(call<String?>("extractTotpSecret", ""))+        assertEquals("PLAINSEED", call<String?>("extractTotpSecret", "PLAINSEED"))+        assertEquals(+            "ABC123",+            call<String?>("extractTotpSecret", "otpauth://totp/x?issuer=Y&secret=ABC123&digits=6"),+        )+        // An otpauth URI without a secret parameter is kept verbatim.+        assertEquals(+            "otpauth://totp/x?issuer=Y",+            call<String?>("extractTotpSecret", "otpauth://totp/x?issuer=Y"),+        )+    }++    @Test fun websiteSplittingRespectsSourceSeparators() {+        val commaSource: List<String> = call(+            "splitWebsites", "a.com, b.com; c.com\nd.com", ImportSource.PROTON_PASS,+        )+        assertEquals("a.com|b.com|c.com|d.com", commaSource.joinToString("|"))+        // Other sources keep a comma inside one site, and blank fragments are dropped.+        val noComma: List<String> = call(+            "splitWebsites", "a.com, b.com; ; c.com", ImportSource.BITWARDEN,+        )+        assertEquals("a.com, b.com|c.com", noComma.joinToString("|"))+        assertEquals(emptyList(), call<List<String>>("splitWebsites", " ; ", ImportSource.CHROME))+        assertTrue(call<List<String>>("splitWebsites", "  spaced.com  ", ImportSource.FIREFOX)+            == listOf("spaced.com"))+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineRepoAdapterTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineRepoAdapterTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineRepoAdapterTest.ktnew file mode 100644index 0000000000..36c947851b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncEngineRepoAdapterTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasskeyDao+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordDao+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.data.SyncSnapshot+import com.vayunmathur.passwords.data.SyncSnapshotDao+import kotlinx.coroutines.runBlocking+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertFailsWith++/**+ * The repository-backed [KdbxSyncEngine] constructor wraps the repository+ * in anonymous DAO adapters (the same shape [com.vayunmathur.passwords+ * .platform.buildGetCredentialResponse] uses). Each adapter method is a+ * delegation to the repository, so under Robolectric — where the SQLCipher+ * vault cannot open — every one surfaces [UnsatisfiedLinkError] from the+ * repository call it forwards to. Extracting the adapters from the engine+ * and invoking each method pins that none of them stubs, caches or+ * swallows the call.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxSyncEngineRepoAdapterTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val codec = object : KdbxCodec {+        override fun read(password: String, bytes: ByteArray): List<Map<String, String>>? = emptyList()+        override fun write(password: String, entries: List<Map<String, String>>): ByteArray = byteArrayOf(1)+    }++    private fun engine() = KdbxSyncEngine(PasswordRepository.get(ctx), codec)++    @Suppress("UNCHECKED_CAST")+    private fun <T> adapterField(name: String): T {+        val field = KdbxSyncEngine::class.java.getDeclaredField(name)+        field.isAccessible = true+        return field.get(engine()) as T+    }++    @Test fun passwordDaoAdapterDelegatesEveryMethod() {+        val dao = adapterField<PasswordDao>("passwordDao")+        val password = Password(id = 1, name = "A", syncId = "s-1")+        // Flow getters are cold: obtaining one does not open the vault, but+        // the adapter must hand back the repository's flow.+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getAll() } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getById(1) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getBySyncId("s-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getUpdatedSince(0) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.upsertRaw(password) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.delete(password) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteBySyncId("s-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteAll() } }+    }++    @Test fun passkeyDaoAdapterDelegatesEveryMethod() {+        val dao = adapterField<PasskeyDao>("passkeyDao")+        val passkey = Passkey(id = 2, rpId = "example.com", syncId = "pk-1")+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getAll() } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getByRpId("example.com") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getByCredentialId("cred") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getBySyncId("pk-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getUpdatedSince(0) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.upsertRaw(passkey) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.delete(passkey) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteBySyncId("pk-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteAll() } }+    }++    @Test fun snapshotDaoAdapterDelegatesEveryMethod() {+        val dao = adapterField<SyncSnapshotDao>("snapshotDao")+        val snapshot = SyncSnapshot("s-1", SyncSnapshot.KIND_PASSWORD, "h", 1, 2, 3)+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.getAll() } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.upsert(snapshot) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteBySyncId("s-1") } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteByKind(SyncSnapshot.KIND_PASSWORD) } }+        assertFailsWith<UnsatisfiedLinkError> { runBlocking { dao.deleteAll() } }+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderDispatchTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderDispatchTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderDispatchTest.ktnew file mode 100644index 0000000000..e8514c4fd8--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderDispatchTest.kt@@ -0,0 +1,224 @@+package com.vayunmathur.passwords.sync++import android.content.ContentValues+import android.database.MatrixCursor+import android.net.Uri+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.SyncSnapshot+import kotlinx.serialization.json.Json+import org.junit.Before+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.assertFailsWith+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++/**+ * [RelayPasswordProvider] dispatch beyond the inert routes.+ *+ * Valid routes reach the SQLCipher vault, whose native library is+ * unavailable under Robolectric: each CRUD verb therefore surfaces+ * [UnsatisfiedLinkError] from the DAO call it dispatches to. That pins the+ * routing (URI match, envelope decoding, sync-id extraction) as executing+ * before the vault is touched. The cursor builders and the content hash —+ * the exact bytes the relay merge hashes — are invoked directly and+ * asserted on their output.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RelayProviderDispatchTest {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val provider: RelayPasswordProvider by lazy {+        Robolectric.buildContentProvider(RelayPasswordProvider::class.java)+            .create(RelayPasswordProvider.AUTHORITY).get()+    }++    private fun uri(path: String) = Uri.parse("content://${RelayPasswordProvider.AUTHORITY}/$path")++    private fun envelope(uid: String, passkey: Boolean = false, deleted: Boolean = false): ContentValues =+        ContentValues().apply {+            put(+                RelayPasswordProvider.COL_PAYLOAD_JSON,+                """{"uid":"$uid","isPasskey":$passkey,"deleted":$deleted,"name":"Mail",""" ++                    """"username":"alice","password":"pw","rpId":"example.com",""" ++                    """"credentialId":"cred-1","userName":"alice","updatedAt":1234}""",+            )+        }++    // ---- CRUD dispatch reaches the vault ----++    @Test fun queryRoutesReachVault() {+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/passwords"), null, null, null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/passkeys"), null, null, null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/snapshots"), null, null, null, null)+        }+        // querySince takes `since` from the query parameter, then selectionArgs.+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/passwords/querySince?since=500"), null, null, null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/passkeys/querySince"), null, null, arrayOf("250"), null)+        }+        // A non-numeric since falls back to 0 and still dispatches.+        assertFailsWith<UnsatisfiedLinkError> {+            provider.query(uri("vault/v/passwords/querySince?since=abc"), null, null, null, null)+        }+    }++    @Test fun insertAndUpdateRoutesReachVault() {+        assertFailsWith<UnsatisfiedLinkError> {+            provider.insert(uri("vault/v/passwords"), envelope("pw-1"))+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.insert(uri("vault/v/passwords/upsertRaw"), envelope("pw-2"))+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.insert(uri("vault/v/passkeys"), envelope("pk-1", passkey = true))+        }+        // A deleted envelope still has to look the row up before deleting it.+        assertFailsWith<UnsatisfiedLinkError> {+            provider.insert(uri("vault/v/passkeys/upsertRaw"), envelope("pk-2", passkey = true, deleted = true))+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.update(uri("vault/v/passwords"), envelope("pw-3"), null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.update(uri("vault/v/passkeys/upsertRaw"), envelope("pk-3", passkey = true), null, null)+        }+        // Snapshot upserts carry their columns directly, not an envelope.+        val snapshot = ContentValues().apply {+            put(RelayPasswordProvider.COL_SYNC_ID, "snap-1")+            put("kind", SyncSnapshot.KIND_PASSWORD)+            put(RelayPasswordProvider.COL_CONTENT_HASH, "hash-1")+            put(RelayPasswordProvider.COL_UPDATED_AT, 99L)+            put("remoteModified", 55L)+        }+        assertFailsWith<UnsatisfiedLinkError> { provider.insert(uri("vault/v/snapshots"), snapshot) }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.update(uri("vault/v/snapshots/upsertRaw"), snapshot, null, null)+        }+    }++    @Test fun deleteRoutesReachVault() {+        // Single delete by sync id.+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/passwords"), "syncId = ?", arrayOf("pw-1"))+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/passkeys"), "syncId = ?", arrayOf("pk-1"))+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/snapshots"), null, arrayOf("snap-1"))+        }+        // Purge routes and selection-less base deletes.+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/passwords/deleteByVault"), null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/passkeys/deleteByVault"), null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/snapshots/deleteByVault"), null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/passwords"), null, null)+        }+        assertFailsWith<UnsatisfiedLinkError> {+            provider.delete(uri("vault/v/snapshots"), null, null)+        }+    }++    // ---- Cursor builders + content hash (pure, asserted on output) ----++    @Suppress("UNCHECKED_CAST")+    private fun <T> invokePrivate(name: String, vararg args: Any?): T {+        val method = RelayPasswordProvider::class.java.declaredMethods+            .first { it.name == name && it.parameterCount == args.size }+        method.isAccessible = true+        return method.invoke(provider, *args) as T+    }++    @Test fun cursorBuildersEmitRelayColumnsAndPayloads() {+        val passwordsCursor: MatrixCursor = invokePrivate(+            "cursorFromPasswords",+            listOf(+                Password(id = 1, name = "Mail", username = "alice", password = "pw", syncId = "pw-1", updatedAt = 111),+                Password(id = 2, name = "Bank", username = "bob", password = "pw2", syncId = "pw-2", updatedAt = 222),+            ),+        )+        assertEquals(RelayPasswordProvider.COLUMNS.toList(), passwordsCursor.columnNames.toList())+        assertEquals(2, passwordsCursor.count)+        assertTrue(passwordsCursor.moveToFirst())+        assertEquals("pw-1", passwordsCursor.getString(0))+        assertEquals(111L, passwordsCursor.getLong(1))+        assertEquals(0, passwordsCursor.getInt(2))+        val payload = Json { ignoreUnknownKeys = true }+            .decodeFromString(RelayPasswordJson.serializer(), passwordsCursor.getString(3))+        assertEquals("Mail", payload.name)+        assertEquals("alice", payload.username)+        assertEquals(64, passwordsCursor.getString(4).length)++        val passkeysCursor: MatrixCursor = invokePrivate(+            "cursorFromPasskeys",+            listOf(+                Passkey(id = 3, rpId = "example.com", rpName = "Key", userName = "carol", syncId = "pk-1", updatedAt = 333),+            ),+        )+        assertEquals(1, passkeysCursor.count)+        assertTrue(passkeysCursor.moveToFirst())+        assertEquals("pk-1", passkeysCursor.getString(0))+        val pkPayload = Json { ignoreUnknownKeys = true }+            .decodeFromString(RelayPasswordJson.serializer(), passkeysCursor.getString(3))+        assertTrue(pkPayload.isPasskey)+        assertEquals("example.com", pkPayload.rpId)++        val snapshotsCursor: MatrixCursor = invokePrivate(+            "cursorFromSnapshots",+            listOf(SyncSnapshot("snap-1", SyncSnapshot.KIND_PASSWORD, "hash-9", 44, 55, 66)),+        )+        assertEquals(1, snapshotsCursor.count)+        assertTrue(snapshotsCursor.moveToFirst())+        assertEquals("snap-1", snapshotsCursor.getString(0))+        assertEquals(44L, snapshotsCursor.getLong(1))+        assertEquals("", snapshotsCursor.getString(3))+        assertEquals("hash-9", snapshotsCursor.getString(4))++        val emptyCursor: MatrixCursor = invokePrivate("cursorFromPasswords", emptyList<Password>())+        assertEquals(0, emptyCursor.count)+    }++    @Test fun contentHashIgnoresIdentityButNotContentOrDeletion() {+        val base = RelayPasswordJson(uid = "a", name = "Mail", password = "pw", updatedAt = 100)+        val reidentified = base.copy(uid = "b", updatedAt = 999)+        val hashA: String = invokePrivate("relayContentHash", base)+        val hashB: String = invokePrivate("relayContentHash", reidentified)+        // uid/updatedAt are stripped for the hash, so a re-identified copy hashes the same.+        assertEquals(hashA, hashB)+        assertEquals(64, hashA.length)+        // Content and the deleted flag both feed the hash.+        val changed: String = invokePrivate("relayContentHash", base.copy(password = "other"))+        val deleted: String = invokePrivate("relayContentHash", base.copy(deleted = true))+        assertNotEquals(hashA, changed)+        assertNotEquals(hashA, deleted)++        // SHA-256 of the empty string is a well-known constant.+        val emptyHash: String = invokePrivate("sha256Hex", "")+        assertEquals(+            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",+            emptyHash,+        )+    }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/PageWrappersComposeTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PageWrappersComposeTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PageWrappersComposeTest.ktnew file mode 100644index 0000000000..a62643f126--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PageWrappersComposeTest.kt@@ -0,0 +1,247 @@+package com.vayunmathur.passwords.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollToNode+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.Navigation+import com.vayunmathur.passwords.R+import com.vayunmathur.passwords.Route+import com.vayunmathur.passwords.data.PASSKEY_LINK_DETACHED+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.platform.PasswordsViewModel+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import org.junit.Before+import org.junit.Rule+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.assertTrue++/**+ * The ViewModel-backed page wrappers ([PasskeyPage], [PasswordPage],+ * [PasswordEditPage], [MenuPage], [Navigation]).+ *+ * The vault itself cannot be opened under Robolectric (SQLCipher's native+ * library is unavailable there), so the ViewModel's cold Room flows never+ * emit. These tests seed the value held inside each `stateIn` StateFlow+ * directly — the composables under test, their state resolution+ * (`passwordState`, `mergeCredentials`, draft seeding) and their rendering+ * all run for real.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PageWrappersComposeTest {++    @get:Rule val rule = createComposeRule()++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val app: Application get() = ApplicationProvider.getApplicationContext()++    private fun vm(+        passwords: List<Password> = emptyList(),+        passkeys: List<Passkey> = emptyList(),+        loaded: Boolean = true,+    ): PasswordsViewModel {+        val viewModel = PasswordsViewModel(app, PasswordRepository.get(app))+        // Replace the Room-backed stateIn flows with plain MutableStateFlows:+        // collecting the real ones would open SQLCipher (native library+        // unavailable under Robolectric) inside viewModelScope and the Error+        // would escape the sharing coroutine and fail the test. The pages,+        // their derived state and rendering all run against these flows+        // exactly as they would against the database-backed ones.+        replaceFlow(viewModel, "passwords", MutableStateFlow(passwords))+        replaceFlow(viewModel, "passkeys", MutableStateFlow(passkeys))+        replaceFlow(viewModel, "tickerFlow", MutableStateFlow(60_000L))+        if (loaded) setLoaded(viewModel)+        return viewModel+    }++    private fun replaceFlow(viewModel: PasswordsViewModel, name: String, flow: MutableStateFlow<*>) {+        val field = PasswordsViewModel::class.java.getDeclaredField(name)+        field.isAccessible = true+        field.set(viewModel, flow)+    }++    private fun setLoaded(viewModel: PasswordsViewModel) {+        val field = PasswordsViewModel::class.java.getDeclaredField("_loaded")+        field.isAccessible = true+        @Suppress("UNCHECKED_CAST")+        (field.get(viewModel) as MutableStateFlow<Boolean>).value = true+    }++    private val github = Password(+        id = 1, name = "GitHub", username = "octocat", email = "[email protected]",+        password = "hunter2secret", note = "work account",+        websites = listOf("github.com"), syncId = "sync-a",+    )+    private val passkey = Passkey(+        id = 7, rpId = "github.com", rpName = "GitHub Key", credentialId = "cred-1234567890-abcdefghij",+        userId = "uid-1", userName = "octocat", userDisplayName = "Octo Cat",+        creationTime = 1_700_000_000_000, lastUsedTime = 1_700_100_000_000,+        signCount = 3, syncId = "pk-7",+    )++    // ---- PasskeyPage ----++    @Test fun passkeyPageAutoLinkedShowsLinkedPasswordAndDetails() {+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(passkey))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(7)))+        rule.setContent { PasskeyPage(backStack, 7, viewModel) }++        // Title comes from rpName; the auto-matched password is the link target.+        rule.onAllNodesWithText("GitHub Key")[0].assertIsDisplayed()+        rule.onNodeWithText("GitHub").assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_link_auto)).assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_disconnect)).assertIsDisplayed()+        // Detail cards below the link section.+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("github.com"))+        rule.onNodeWithText("github.com").assertExists()+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("Octo Cat"))+        rule.onNodeWithText("Octo Cat").assertExists()+        // A credential id longer than 20 chars is truncated with an ellipsis.+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("cred-1234567890-abcd…"))+        rule.onNodeWithText("cred-1234567890-abcd…").assertExists()+    }++    @Test fun passkeyPageDetachedShowsDetachedTextAndAutoOption() {+        val detached = passkey.copy(+            rpName = "", userName = "", userDisplayName = "",+            linkedPasswordSyncId = PASSKEY_LINK_DETACHED,+        )+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(detached))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(7)))+        rule.setContent { PasskeyPage(backStack, 7, viewModel) }++        // Blank rpName falls back to the generic title in the app bar.+        rule.onNodeWithText(app.getString(R.string.passkey_detail_title)).assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_link_detached)).assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_link_use_auto)).assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_link_dialog_title)).assertIsDisplayed()+        // Blank detail values render as an em dash.+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("—"))+        assertTrue(rule.onAllNodesWithText("—").fetchSemanticsNodes().isNotEmpty())+    }++    @Test fun passkeyPageManualLinkShowsManualLabel() {+        val manual = passkey.copy(linkedPasswordSyncId = "sync-a")+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(manual))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(7)))+        rule.setContent { PasskeyPage(backStack, 7, viewModel) }+        rule.onNodeWithText(app.getString(R.string.passkey_link_manual)).assertIsDisplayed()+    }++    @Test fun passkeyPageUnlinkedShowsNoneAndLinkAffordance() {+        val viewModel = vm(passwords = emptyList(), passkeys = listOf(passkey))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(7)))+        rule.setContent { PasskeyPage(backStack, 7, viewModel) }+        rule.onNodeWithText(app.getString(R.string.passkey_link_none)).assertIsDisplayed()+        rule.onNodeWithText(app.getString(R.string.passkey_link_dialog_title)).assertIsDisplayed()+    }++    @Test fun passkeyPageLinkPickerListsPasswords() {+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(passkey.copy(userName = "nobody")))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(7)))+        rule.setContent { PasskeyPage(backStack, 7, viewModel) }+        // "nobody" does not auto-match GitHub's octocat, so the picker can open.+        rule.onNodeWithText(app.getString(R.string.passkey_link_dialog_title)).performClick()+        rule.onNodeWithText("GitHub").assertIsDisplayed()+    }++    @Test fun passkeyPageForUnknownIdRendersNothing() {+        val viewModel = vm(passkeys = listOf(passkey))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasskeyPage(99)))+        rule.setContent { PasskeyPage(backStack, 99, viewModel) }+        assertEquals(+            0,+            rule.onAllNodesWithText("GitHub Key").fetchSemanticsNodes().size,+        )+    }++    // ---- PasswordPage wrapper ----++    @Test fun passwordPageWrapperRendersResolvedPasswordAndPasskeys() {+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(passkey))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasswordPage(1)))+        rule.setContent { PasswordPage(backStack, 1, viewModel) }+        rule.onAllNodesWithText("GitHub")[0].assertIsDisplayed()+        rule.onAllNodesWithText("octocat")[0].assertIsDisplayed()+        // The passkey merged into this password is listed on its detail page.+        rule.onNode(hasScrollAction()).performScrollToNode(hasText("GitHub Key"))+        rule.onNodeWithText("GitHub Key").assertExists()+    }++    @Test fun passwordPageWrapperForUnknownIdRendersDefaultEntry() {+        val viewModel = vm(passwords = listOf(github))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasswordPage(42)))+        rule.setContent { PasswordPage(backStack, 42, viewModel) }+        // passwordState falls back to a blank Password() for an absent id.+        rule.onNodeWithText(app.getString(R.string.no_name)).assertIsDisplayed()+    }++    // ---- PasswordEditPage wrapper ----++    @Test fun passwordEditPageWrapperSeedsDraftFromStoredPassword() {+        val viewModel = vm(passwords = listOf(github))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasswordEditPage(1)))+        rule.setContent { PasswordEditPage(backStack, 1, viewModel) }+        rule.onNodeWithText("GitHub").assertIsDisplayed()+        // LaunchedEffect(id, pass) seeds the draft exactly once from the row.+        rule.waitUntil(timeoutMillis = 5_000) { viewModel.draft.value?.id == 1L }+        assertEquals("GitHub", viewModel.draft.value?.name)+        assertEquals(listOf("github.com"), viewModel.draft.value?.websites)+    }++    @Test fun passwordEditPageWrapperForNewEntrySeedsBlankDraft() {+        val viewModel = vm(passwords = emptyList())+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu, Route.PasswordEditPage(0)))+        rule.setContent { PasswordEditPage(backStack, 0, viewModel) }+        rule.waitUntil(timeoutMillis = 5_000) { viewModel.draft.value != null }+        assertEquals(0L, viewModel.draft.value?.id)+        assertEquals("", viewModel.draft.value?.name)+    }++    // ---- MenuPage wrapper ----++    @Test fun menuPageWrapperRendersVaultRows() {+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(passkey))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu))+        rule.setContent { MenuPage(backStack, viewModel) }+        rule.onNodeWithText("GitHub").assertIsDisplayed()+        // The passkey is merged into GitHub (not a standalone row).+        assertEquals(0, rule.onAllNodesWithText("GitHub Key").fetchSemanticsNodes().size)+    }++    @Test fun menuPageWrapperStandalonePasskeyRowNavigates() {+        val solo = passkey.copy(id = 8, rpId = "solo.example", rpName = "Solo Key", userName = "dave")+        val viewModel = vm(passkeys = listOf(solo))+        val backStack = NavBackStack<Route>(arrayOf(Route.Menu))+        rule.setContent { MenuPage(backStack, viewModel) }+        rule.onNodeWithText("Solo Key").assertIsDisplayed()+        rule.onNodeWithText("Solo Key").performClick()+        assertEquals(Route.PasskeyPage(8), backStack.last())+    }++    // ---- Navigation ----++    @Test fun navigationStartsOnMenuWithVaultRows() {+        val viewModel = vm(passwords = listOf(github), passkeys = listOf(passkey))+        rule.setContent { Navigation(viewModel) }+        rule.onNodeWithText("GitHub").assertIsDisplayed()+        rule.onAllNodesWithText("octocat")[0].assertIsDisplayed()+    }+}