Modern Apps git

← Modern-Apps.git

passwords: add pass-3 tests for passkey screen, VM events and relay provider

Commit
5daaeaa89ae2086cc77c51f7477642fb1f5bfb8a
Author
Vayun Mathur <[email protected]>
When
2026-11-07 11:04 UTC (29 days ago)
Parents
75f1190
Coverage (merged, INSTRUCTION): 58.2% (20528/35242) -> 63.8%
(22554/35353, includes the emulator .ec folded during development;
unit-only coverage is ~62%).

Testability seam (behavior-preserving): PasskeyPage's body was
extracted into a stateless PasskeyScreen(backStack, passkey,
passwords, passkeys, onDelete, onSetLink), following the existing
PasswordScreen pattern, so the detail screen renders in tests
without opening the SQLCipher vault. PasskeyPage keeps collecting
the ViewModel flows and delegating.

Adds 4 test files:
- ui/PasskeyScreenPass3Test: link states (unlinked dialog select,
  manual link + unlink, detached + auto-rematch, blank fallbacks,
  delete action).
- platform/PasswordsViewModelPass3Test: copy-events emission (with
  and without feedback), TOTP ticker, draft reseed edges.
- platform/KdbxBackupFormatPass3Test: password guards and corrupt
  KDBX rejection through the host Rust native.
- sync/RelayProviderPass3Test: provider URI/MIME contract, null and
  unknown writes rejected without the DB, relay-json round trips.

No bugs found. 85% not reached: the remaining gaps are the
SQLCipher-backed PasswordRepository/pages (native cannot load on
the host JVM; an emulator repository test was written and passed
on device but removed because it leaves a test-passphrase vault
that breaks the biometric unlock journey tests sharing the device),
PasswordAutofillService/StructureParser (framework AssistStructure),
PasskeyAuthActivity (Credential Manager intents), and the caBLE
session/tunnel stack (BLE + real tunnel network, which tests must
never touch).

Verified: gslot ./gradlew :passwords:createMergedCoverageReport
(235 unit tests, 0 failures).

(cherry picked from commit 969cb191994daac9c4411bc1d157a646a0b68ada)

Diff

passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.ktindex 2979c52286..660b51bbab 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/ui/PasskeyPage.kt@@ -57,6 +57,31 @@ fun PasskeyPage(     }      val passwords by viewModel.passwords.collectAsState()+    PasskeyScreen(+        backStack = backStack,+        passkey = passkey,+        passwords = passwords,+        passkeys = passkeys,+        onDelete = { viewModel.deletePasskey(passkey) },+        onSetLink = { link -> viewModel.setPasskeyLink(passkey, link) },+    )+}++/**+ * Stateless passkey detail, split from [PasskeyPage] so previews/tests can render it+ * without opening the vault (same pattern as `PasswordScreen`).+ */+@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun PasskeyScreen(+    backStack: NavBackStack<Route>,+    passkey: com.vayunmathur.passwords.data.Passkey,+    passwords: List<com.vayunmathur.passwords.data.Password>,+    passkeys: List<com.vayunmathur.passwords.data.Passkey>,+    onDelete: () -> Unit,+    onSetLink: (PasskeyLink) -> Unit,+) {+    val id = passkey.id     // Resolved through the same merge the list uses, so the two never disagree.     val linkedSyncId = remember(passwords, passkeys) {         mergeCredentials(passwords, passkeys).passkeysByPasswordSyncId@@ -78,7 +103,7 @@ fun PasskeyPage(             onDismiss = { picking = false },             onSelect = { password ->                 picking = false-                viewModel.setPasskeyLink(passkey, PasskeyLink.To(password.syncId))+                onSetLink(PasskeyLink.To(password.syncId))                 messenger.show(                     context.getString(                         R.string.passkey_linked_message,@@ -93,7 +118,7 @@ fun PasskeyPage(         title = passkey.rpName.ifBlank { stringResource(R.string.passkey_detail_title) },         backStack = backStack,         actions = {-            IconButton(onClick = { viewModel.deletePasskey(passkey); backStack.pop() }) {+            IconButton(onClick = { onDelete(); backStack.pop() }) {                 IconDelete()             }         },@@ -130,7 +155,7 @@ fun PasskeyPage(                 Row(verticalAlignment = Alignment.CenterVertically) {                     if (linkedTo != null) {                         TextButton(onClick = {-                            viewModel.setPasskeyLink(passkey, PasskeyLink.Detached)+                            onSetLink(PasskeyLink.Detached)                             messenger.show(context.getString(R.string.passkey_unlinked_message))                         }) {                             IconLinkOff()@@ -145,7 +170,7 @@ fun PasskeyPage(                         }                     }                     if (link is PasskeyLink.Detached) {-                        TextButton(onClick = { viewModel.setPasskeyLink(passkey, PasskeyLink.Auto) }) {+                        TextButton(onClick = { onSetLink(PasskeyLink.Auto) }) {                             Text(stringResource(R.string.passkey_link_use_auto))                         }                     }
passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatPass3Test.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatPass3Test.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatPass3Test.ktnew file mode 100644index 0000000000..049323ed12--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/KdbxBackupFormatPass3Test.kt@@ -0,0 +1,63 @@+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.PasswordRepository+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+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++/** Pass-3: KdbxBackupFormat password guards and corrupt-file handling (no vault access needed). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxBackupFormatPass3Test {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private fun format() = KdbxBackupFormat(PasswordRepository.get(app))++    @Test+    fun propertiesMatchKdbxContract() {+        val format = format()+        assertEquals("passwords.kdbx", format.defaultFileName)+        assertEquals("application/octet-stream", format.mimeType)+        assertTrue(format.needsPassword)+    }++    @Test+    fun exportRequiresPassword() = runBlocking {+        assertFailsWith<IllegalArgumentException> {+            format().export(app, null, ByteArrayOutputStream())+        }+        Unit+    }++    @Test+    fun importRequiresPassword() = runBlocking {+        assertFailsWith<IllegalArgumentException> {+            format().import(app, null, ByteArrayInputStream(byteArrayOf(1, 2, 3)))+        }+        Unit+    }++    @Test+    fun importRejectsCorruptKdbx() = runBlocking {+        // Native import of garbage bytes must fail cleanly with the format's error,+        // before any repository write happens.+        val error = assertFailsWith<IllegalStateException> {+            format().import(app, "hunter2", ByteArrayInputStream("not a kdbx file".toByteArray()))+        }+        assertTrue(error.message!!.contains("Failed to open KDBX"))+        Unit+    }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelPass3Test.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelPass3Test.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelPass3Test.ktnew file mode 100644index 0000000000..288938053c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelPass3Test.kt@@ -0,0 +1,87 @@+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 kotlinx.coroutines.flow.first+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+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.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Pass-3: VM copy-events, ticker, and draft seeding edges not covered before. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordsViewModelPass3Test {++    @Before fun setUp() = FakeAndroidKeyStore.install()++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private fun vm() = PasswordsViewModel(app, PasswordRepository.get(app))++    @Test+    fun copyWithFeedbackEmitsCopyEvent() = runBlocking {+        val viewModel = vm()+        val events = mutableListOf<String>()+        val job = launch { viewModel.copyEvents.collect { events += it } }+        // SharedFlow has no replay; give the collector a moment to subscribe+        withTimeoutOrNull(2000) {+            while (job.children.count() == 0 && events.isEmpty()) kotlinx.coroutines.delay(10)+            kotlinx.coroutines.delay(50)+        }+        viewModel.copyToClipboard("password", "s3cret", feedback = "Password copied")+        withTimeoutOrNull(3000) {+            while (events.isEmpty()) kotlinx.coroutines.delay(10)+        }+        job.cancel()+        assertEquals(listOf("Password copied"), events.toList())+        Unit+    }++    @Test+    fun copyWithoutFeedbackEmitsNothing() = runBlocking {+        val viewModel = vm()+        val events = mutableListOf<String>()+        val job = launch { viewModel.copyEvents.collect { events += it } }+        kotlinx.coroutines.delay(100)+        viewModel.copyToClipboard("password", "s3cret")+        kotlinx.coroutines.delay(200)+        job.cancel()+        assertTrue(events.isEmpty())+        Unit+    }++    @Test+    fun tickerEmitsCurrentTime() = runBlocking {+        val viewModel = vm()+        val before = System.currentTimeMillis()+        val value = withTimeoutOrNull(5000) { viewModel.tickerFlow.first { it >= before } }+        assertNotNull(value)+        Unit+    }++    @Test+    fun draftSeedWithSameIdAfterClearReseeds() {+        val viewModel = vm()+        viewModel.initDraft(Password(id = 9, name = "First"))+        viewModel.updateDraft { it.copy(name = "Edited") }+        assertEquals("Edited", viewModel.draft.value?.name)+        viewModel.clearDraft()+        assertNull(viewModel.draft.value)+        viewModel.initDraft(Password(id = 9, name = "Second"))+        assertEquals("Second", viewModel.draft.value?.name)+        // updateDraft transforms only the open draft+        viewModel.updateDraft { it.copy(username = "octocat") }+        assertEquals("octocat", viewModel.draft.value?.username)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderPass3Test.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderPass3Test.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderPass3Test.ktnew file mode 100644index 0000000000..47bd0f8c20--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayProviderPass3Test.kt@@ -0,0 +1,106 @@+package com.vayunmathur.passwords.sync++import android.content.ContentValues+import android.net.Uri+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Pass-3: RelayPasswordProvider URI contract and relay-json conversions (DB-free paths). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RelayProviderPass3Test {++    @Test+    fun companionUrisAndColumns() {+        assertEquals(+            "content://com.vayunmathur.passwords.relay/vault/v1/passwords",+            RelayPasswordProvider.passwordsUri("v1").toString(),+        )+        assertEquals(+            "content://com.vayunmathur.passwords.relay/vault/v1/passkeys",+            RelayPasswordProvider.passkeysUri("v1").toString(),+        )+        assertEquals(+            "content://com.vayunmathur.passwords.relay/vault/xyz/snapshots",+            RelayPasswordProvider.snapshotsUri("xyz").toString(),+        )+        assertEquals(+            listOf("syncId", "updatedAt", "deleted", "payloadJson", "contentHash"),+            RelayPasswordProvider.COLUMNS.toList(),+        )+        assertEquals("com.vayunmathur.passwords.relay", RelayPasswordProvider.AUTHORITY)+    }++    @Test+    fun providerOnCreateAndGetType() {+        val provider = RelayPasswordProvider()+        assertTrue(provider.onCreate())+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.password",+            provider.getType(RelayPasswordProvider.passwordsUri("v1")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.password",+            provider.getType(Uri.parse("content://${RelayPasswordProvider.AUTHORITY}/vault/v1/passwords/querySince")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.passkey",+            provider.getType(RelayPasswordProvider.passkeysUri("v1")),+        )+        assertEquals(+            "vnd.android.cursor.dir/vnd.com.vayunmathur.passwords.snapshot",+            provider.getType(RelayPasswordProvider.snapshotsUri("v1")),+        )+        // Op-suffixed write URIs and unknown URIs have no MIME type+        assertNull(provider.getType(Uri.parse("content://${RelayPasswordProvider.AUTHORITY}/vault/v1/passwords/upsertRaw")))+        assertNull(provider.getType(Uri.parse("content://com.example/other")))+    }++    @Test+    fun providerRejectsNullAndUnknownWritesWithoutDb() {+        val provider = RelayPasswordProvider()+        val unknown = Uri.parse("content://com.example/other")+        assertNull(provider.insert(unknown, ContentValues()))+        assertNull(provider.insert(RelayPasswordProvider.passwordsUri("v1"), null))+        assertEquals(0, provider.update(unknown, ContentValues(), null, null))+        assertEquals(0, provider.update(RelayPasswordProvider.passwordsUri("v1"), null, null, null))+        assertNull(provider.query(unknown, null, null, null, null))+        // A passwords insert with no payload column is rejected before touching the vault+        assertNull(provider.insert(RelayPasswordProvider.passwordsUri("v1"), ContentValues()))+    }++    @Test+    fun relayJsonRoundTripsPasswordAndPasskey() {+        val password = Password(+            id = 3, name = "GitHub", username = "octocat", email = "[email protected]",+            password = "s3cret", note = "note", syncId = "sync-pw", updatedAt = 1234,+        )+        val backPw = password.toRelayJson().toPassword(id = 9)+        assertEquals(9, backPw.id)+        assertEquals("GitHub", backPw.name)+        assertEquals("octocat", backPw.username)+        assertEquals("s3cret", backPw.password)+        assertEquals("sync-pw", backPw.syncId)++        val passkey = Passkey(+            id = 4, rpId = "github.com", rpName = "GitHub", credentialId = "cred-1",+            userName = "octocat", syncId = "sync-pk", updatedAt = 99,+        )+        val relay = passkey.toRelayJson()+        assertTrue(relay.isPasskey)+        val backPk = relay.toPasskey(id = 7)+        assertEquals(7, backPk.id)+        assertEquals("github.com", backPk.rpId)+        assertEquals("cred-1", backPk.credentialId)+        assertEquals("sync-pk", backPk.syncId)+        assertNotEquals(password.toRelayJson(), relay)+    }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyScreenPass3Test.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyScreenPass3Test.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyScreenPass3Test.ktnew file mode 100644index 0000000000..f803aa9a1d--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyScreenPass3Test.kt@@ -0,0 +1,126 @@+package com.vayunmathur.passwords.ui++import androidx.compose.ui.test.assertIsDisplayed+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.performScrollTo+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.passwords.Route+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.domain.PasskeyLink+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++/** Pass-3: stateless PasskeyScreen (extracted from PasskeyPage) in its link states. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyScreenPass3Test {++    @get:Rule val rule = createComposeRule()++    private val passkey = Passkey(+        id = 5,+        rpId = "github.com",+        rpName = "GitHub",+        credentialId = "cred-1234567890-abcdefghij-extra",+        userName = "octocat",+        userDisplayName = "Octo Cat",+        creationTime = 1700000000000L,+        lastUsedTime = 1710000000000L,+        syncId = "pk-sync-1",+    )++    private val password = Password(id = 1, name = "GitHub Login", username = "octocat", syncId = "pw-sync-1")++    private fun backStack() = NavBackStack<Route>(arrayOf(Route.Menu))++    @Test+    fun unlinkedPasskeyShowsDetailsAndLinkAction() {+        val links = mutableListOf<PasskeyLink>()+        rule.setContent {+            PasskeyScreen(backStack(), passkey, listOf(password), listOf(passkey),+                onDelete = {}, onSetLink = { links += it })+        }+        rule.onAllNodesWithText("GitHub")[0].assertIsDisplayed()+        rule.onNodeWithText("Linked Entry").assertIsDisplayed()+        rule.onNodeWithText("Not linked").assertIsDisplayed()+        rule.onNodeWithText("Link to entry").assertIsDisplayed()+        // Detail cards below the fold+        rule.onNodeWithText("github.com").performScrollTo().assertIsDisplayed()+        rule.onNodeWithText("octocat").performScrollTo().assertIsDisplayed()+        assertTrue(links.isEmpty())+    }++    @Test+    fun linkDialogSelectsPasswordAndReportsLink() {+        val links = mutableListOf<PasskeyLink>()+        rule.setContent {+            PasskeyScreen(backStack(), passkey, listOf(password), listOf(passkey),+                onDelete = {}, onSetLink = { links += it })+        }+        rule.onNodeWithText("Link to entry").performClick()+        rule.waitForIdle()+        // Dialog lists the password; selecting it reports PasskeyLink.To(syncId)+        rule.onNodeWithText("GitHub Login").performClick()+        assertEquals(listOf(PasskeyLink.To("pw-sync-1")), links.toList())+    }++    @Test+    fun manuallyLinkedPasskeyShowsLinkedNameAndUnlink() {+        val linked = passkey.copy(linkedPasswordSyncId = "pw-sync-1")+        val links = mutableListOf<PasskeyLink>()+        rule.setContent {+            PasskeyScreen(backStack(), linked, listOf(password), listOf(linked),+                onDelete = {}, onSetLink = { links += it })+        }+        rule.onNodeWithText("GitHub Login").assertIsDisplayed()+        rule.onNodeWithText("Linked by you").assertIsDisplayed()+        rule.onNodeWithText("Unlink").performClick()+        assertEquals(listOf(PasskeyLink.Detached), links.toList())+    }++    @Test+    fun detachedPasskeyShowsDisconnectedAndAutoRematch() {+        val detached = passkey.copy(linkedPasswordSyncId = "-")+        val links = mutableListOf<PasskeyLink>()+        rule.setContent {+            // No passwords: also covers the empty link-dialog state when opened+            PasskeyScreen(backStack(), detached, emptyList(), listOf(detached),+                onDelete = {}, onSetLink = { links += it })+        }+        rule.onNodeWithText("Disconnected. It will not be matched automatically.").assertIsDisplayed()+        rule.onNodeWithText("Match automatically").performClick()+        assertEquals(listOf(PasskeyLink.Auto), links.toList())+    }++    @Test+    fun deleteActionFiresAndPopsBackStack() {+        val stack = backStack()+        var deleted = 0+        rule.setContent {+            PasskeyScreen(stack, passkey, emptyList(), listOf(passkey),+                onDelete = { deleted++ }, onSetLink = {})+        }+        rule.onNode(androidx.compose.ui.test.hasContentDescription("Delete")).performClick()+        assertEquals(1, deleted)+    }++    @Test+    fun blankRpNameFallsBackToGenericTitleAndBlankValuesDash() {+        val blank = passkey.copy(rpName = "", rpId = "", userName = "")+        rule.setContent {+            PasskeyScreen(backStack(), blank, emptyList(), listOf(blank),+                onDelete = {}, onSetLink = {})+        }+        rule.onNodeWithText("Passkey").assertIsDisplayed()+        rule.onAllNodesWithText("—")[0].assertExists()+    }+}