passwords: add tests for vault, sync, passkeys and UI
- Commit
a9582446c7bdeb48a2344a534d182ca5b955e8ed- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 03:55 UTC (29 days ago)
- Parents
b2c6d41
Merged INSTRUCTION coverage rises from 25.56% (9009/35242) to 58.25% (20528/35242), measured with gslot ./gradlew :passwords:createMergedCoverageReport after the two preceding fix commits made the suite runnable. New tests (23 files): TOTP RFC vectors and CBOR encoding; ImportSource headers and DomainMatch edges; Room DAO CRUD for passwords/passkeys/snapshots on an in-memory database; PasswordsViewModel draft/clipboard/factory and CSV import of empty/header/blank-row files via a shadow content resolver; Compose screens under Robolectric (password detail with scrolling, edit form incl. blank-name error, menu with TOTP copy, link dialog, settings import menu, KDBX sync section incl. quarantine resolve dialog and vault-password save); KDBX settings/runKdbxSync result branches, native Rust KDBX codec round-trip, sync scheduler/worker; relay JSON envelope round-trips; PasskeyUtils authenticator-data layout, credential-entry building from fake DAOs, WebAuthn create/sign with signature verification; credential/cable services and activities under Robolectric. Robolectric classes pin sdk 35 because the module minSdk is 35, above the shared sdk-34 default. FakeAndroidKeyStore installs an in-memory AndroidKeyStore JCA provider, which Robolectric lacks. Test-only dependency: androidx.work:work-testing (catalog entry androidx-work-testing, same version as work-runtime). 85% was not honestly reachable: the SQLCipher native library cannot load on the host JVM (UnsatisfiedLinkError in SQLiteConnection.nativeOpen), so PasswordRepository flows, PasskeyPage, PasswordPage/MenuPage, the relay ContentProvider and KdbxBackupFormat cannot be exercised past the lazy database open; AutofillService needs real AssistStructure FillContexts, CableSession needs a live tunnel/BLE, and PasskeyCredentialService create/get need real Credential Manager requests. Those are listed as the untestable remainder in the finish report. Verified: gslot ./gradlew :passwords:testDevUnitTest and :createMergedCoverageReport pass (full unit suite green). (cherry picked from commit d1572be14aba40ab0549c1fba9160d41d70cb645)
Diff
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex cb5daafab5..5c5d10c983 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -216,6 +216,7 @@ androidx-sqlite = { module = "androidx.sqlite:sqlite", version.ref = "sqlite" } androidx-sqlite-framework = { module = "androidx.sqlite:sqlite-framework", version.ref = "sqlite" } androidx-sqlite-bundled-jvm = { module = "androidx.sqlite:sqlite-bundled-jvm", version.ref = "sqlite" } androidx-work-runtime-ktx = { module = "androidx.work:work-runtime-ktx", version.ref = "workRuntimeKtx" }+androidx-work-testing = { module = "androidx.work:work-testing", version.ref = "workRuntimeKtx" } androidx-datastore-preferences = { group = "androidx.datastore", name = "datastore-preferences", version.ref = "datastorePreferences" } # AndroidX – A2UI
passwords/build.gradle.kts
diff --git a/passwords/build.gradle.kts b/passwords/build.gradle.ktsindex af1da0810e..07e37684e3 100644--- a/passwords/build.gradle.kts+++ b/passwords/build.gradle.kts@@ -50,4 +50,5 @@ dependencies { implementation(libs.androidx.work.runtime.ktx) // Own WebSocketClient via :library:network – no Ktor implementation(project(":library:network"))+ testImplementation(libs.androidx.work.testing) }
passwords/src/test/java/com/vayunmathur/passwords/FakeAndroidKeyStore.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/FakeAndroidKeyStore.kt b/passwords/src/test/java/com/vayunmathur/passwords/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..56678a9984--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.passwords++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+ private val keys = mutableMapOf<String, SecretKey>()++ fun install() {+ if (Security.getProvider("AndroidKeyStore") == null) {+ Security.addProvider(FakeProvider())+ }+ }++ fun put(alias: String, key: SecretKey) {+ keys[alias] = key+ }++ fun get(alias: String): SecretKey? = keys[alias]++ fun remove(alias: String) {+ keys.remove(alias)+ }++ fun contains(alias: String): Boolean = keys.containsKey(alias)++ fun aliases(): List<String> = keys.keys.toList()++ class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+ init {+ put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+ }+ }++ class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ override fun engineContainsAlias(alias: String) = contains(alias)+ override fun engineDeleteEntry(alias: String) = remove(alias)+ override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+ override fun engineIsKeyEntry(alias: String) = contains(alias)+ override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+ override fun engineSize() = aliases().size+ override fun engineGetCertificate(alias: String): Certificate? = null+ override fun engineGetCertificateAlias(cert: Certificate) = null+ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+ override fun engineGetCreationDate(alias: String) = Date()+ override fun engineIsCertificateEntry(alias: String) = false+ override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+ override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+ if (key is SecretKey) put(alias, key)+ }+ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+ }++ class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String = "test-key"++ override fun engineInit(random: SecureRandom) = Unit+ override fun engineInit(keysize: Int, random: SecureRandom) = Unit+ override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+ if (params is KeyGenParameterSpec) alias = params.keystoreAlias+ }++ override fun engineGenerateKey(): SecretKey {+ val bytes = ByteArray(32)+ SecureRandom().nextBytes(bytes)+ return SecretKeySpec(bytes, "AES").also { put(alias, it) }+ }+ }++ /** Convenience for tests that obtain a generator through JCA. */+ fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
passwords/src/test/java/com/vayunmathur/passwords/data/ConvertersAndEntitiesTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/ConvertersAndEntitiesTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/ConvertersAndEntitiesTest.ktnew file mode 100644index 0000000000..b6c562924d--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/ConvertersAndEntitiesTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.passwords.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertTrue++class ConvertersAndEntitiesTest {++ @Test fun websitesRoundTrip() {+ val sites = listOf("a.com", "b.com/x")+ assertEquals(sites, Converters.toWebsites(Converters.fromWebsites(sites)))+ }++ @Test fun websitesNullAndEmpty() {+ assertEquals("", Converters.fromWebsites(null))+ assertEquals("", Converters.fromWebsites(emptyList()))+ assertEquals(emptyList(), Converters.toWebsites(null))+ assertEquals(emptyList(), Converters.toWebsites(""))+ }++ @Test fun syncIdsAre32HexCharsAndUnique() {+ val a = newSyncId()+ val b = newSyncId()+ assertEquals(32, a.length)+ assertTrue(a.all { it in '0'..'9' || it in 'a'..'f' })+ assertNotEquals(a, b)+ }++ @Test fun snapshotKindConstants() {+ assertEquals("password", SyncSnapshot.KIND_PASSWORD)+ assertEquals("passkey", SyncSnapshot.KIND_PASSKEY)+ val snap = SyncSnapshot("s1", SyncSnapshot.KIND_PASSWORD, "h", 1, 2, 3)+ assertEquals("s1", snap.syncId)+ assertEquals(3L, snap.lastSyncedAt)+ }++ @Test fun passwordDefaults() {+ val pw = Password(name = "A")+ assertEquals("", pw.username)+ assertEquals(null, pw.totpSecret)+ assertTrue(pw.syncId.isNotBlank())+ }+}
passwords/src/test/java/com/vayunmathur/passwords/data/PasswordDatabaseTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordDatabaseTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordDatabaseTest.ktnew file mode 100644index 0000000000..2c5a2c2890--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/data/PasswordDatabaseTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.passwords.data++import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.After+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordDatabaseTest {++ private lateinit var db: PasswordDatabase++ @Before fun setUp() {+ val ctx = ApplicationProvider.getApplicationContext<Context>()+ db = Room.inMemoryDatabaseBuilder(ctx, PasswordDatabase::class.java)+ .allowMainThreadQueries().build()+ }++ @After fun tearDown() = db.close()++ @Test fun passwordCrudAndQueries() = runBlocking {+ val dao = db.passwordDao()+ val id = dao.upsertRaw(Password(name = "GitHub", username = "octo", syncId = "s1", updatedAt = 100))+ assertTrue(id > 0)+ assertEquals("GitHub", dao.getById(id)?.name)+ assertEquals("GitHub", dao.getBySyncId("s1")?.name)+ assertEquals(1, dao.getAll().size)+ assertEquals(1, dao.getUpdatedSince(50).size)+ assertEquals(0, dao.getUpdatedSince(100).size)+ assertEquals("GitHub", dao.getByIdFlow(id).first()?.name)+ assertEquals(1, dao.getAllFlow().first().size)++ // upsert() bumps updatedAt instead of writing it verbatim.+ dao.upsert(Password(id = id, name = "Renamed", syncId = "s1", updatedAt = 1))+ assertEquals("Renamed", dao.getById(id)?.name)+ assertTrue((dao.getById(id)?.updatedAt ?: 0) > 1)++ assertEquals(1, dao.deleteBySyncId("s1"))+ assertNull(dao.getById(id))+ }++ @Test fun websitesPersistThroughConverter() = runBlocking {+ val dao = db.passwordDao()+ val id = dao.upsertRaw(Password(name = "A", websites = listOf("a.com", "b.com"), syncId = "w1"))+ assertEquals(listOf("a.com", "b.com"), dao.getById(id)?.websites)+ }++ @Test fun passkeyCrudAndQueries() = runBlocking {+ val dao = db.passkeyDao()+ val pk = Passkey(rpId = "example.com", credentialId = "cred", syncId = "pk1", updatedAt = 10, privateKeyBytes = byteArrayOf(1, 2))+ val id = dao.upsertRaw(pk)+ assertEquals("example.com", dao.getByCredentialId("cred")?.rpId)+ assertEquals(1, dao.getByRpId("example.com").size)+ assertEquals(1, dao.getUpdatedSince(5).size)+ assertEquals(byteArrayOf(1, 2).toList(), dao.getBySyncId("pk1")?.privateKeyBytes?.toList())+ dao.upsert(pk.copy(id = id, signCount = 3, updatedAt = 1))+ assertEquals(3, dao.getBySyncId("pk1")?.signCount)+ assertEquals(1, dao.deleteBySyncId("pk1"))+ assertTrue(dao.getAll().isEmpty())+ }++ @Test fun snapshotCrud() = runBlocking {+ val dao = db.syncSnapshotDao()+ dao.upsert(SyncSnapshot("s1", SyncSnapshot.KIND_PASSWORD, "h1", 1, 2, 3))+ dao.upsert(SyncSnapshot("s2", SyncSnapshot.KIND_PASSKEY, "h2", 1, 2, 3))+ assertEquals(2, dao.getAll().size)+ dao.deleteByKind(SyncSnapshot.KIND_PASSWORD)+ assertEquals(listOf("s2"), dao.getAll().map { it.syncId })+ dao.deleteBySyncId("s2")+ assertTrue(dao.getAll().isEmpty())+ dao.upsert(SyncSnapshot("s3", "password", "h", 0, 0, 0))+ dao.deleteAll()+ assertTrue(dao.getAll().isEmpty())+ }++ @Test fun deleteAllClearsPasswords() = runBlocking {+ val dao = db.passwordDao()+ dao.upsertRaw(Password(name = "A", syncId = "x"))+ dao.deleteAll()+ assertTrue(dao.getAll().isEmpty())+ }++ @Test fun migrationsAreRegistered() {+ assertEquals(listOf(1 to 2, 2 to 3, 3 to 4, 4 to 5),+ PasswordDatabase.migrations.map { it.startVersion to it.endVersion })+ }+}
passwords/src/test/java/com/vayunmathur/passwords/domain/ImportSourceAndMatchExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/domain/ImportSourceAndMatchExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/domain/ImportSourceAndMatchExtraTest.ktnew file mode 100644index 0000000000..c79623a115--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/domain/ImportSourceAndMatchExtraTest.kt@@ -0,0 +1,59 @@+package com.vayunmathur.passwords.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class ImportSourceAndMatchExtraTest {++ @Test fun everySourceHasNameAndPasswordHeaders() {+ for (source in ImportSource.entries) {+ assertTrue(source.nameHeaders.isNotEmpty(), source.name)+ assertTrue(source.passwordHeaders.isNotEmpty(), source.name)+ assertTrue(source.urlHeaders.isNotEmpty(), source.name)+ }+ assertEquals(8, ImportSource.entries.size)+ }++ @Test fun protonPassSplitsUrlsAndHasTypeHeaders() {+ val proton = ImportSource.PROTON_PASS+ assertTrue(proton.splitUrlsOnComma)+ assertEquals(arrayOf("type").toList(), proton.typeHeaders.toList())+ assertEquals(arrayOf("email").toList(), proton.emailHeaders.toList())+ assertFalse(ImportSource.BITWARDEN.splitUrlsOnComma)+ }++ @Test fun firefoxUsesUrlAsNameAndHasNoTotp() {+ assertEquals(arrayOf("url").toList(), ImportSource.FIREFOX.nameHeaders.toList())+ assertTrue(ImportSource.FIREFOX.totpHeaders.isEmpty())+ }++ @Test fun dashlaneAcceptsMultipleUsernameColumns() {+ assertEquals(+ listOf("username", "username2", "username3"),+ ImportSource.DASHLANE.usernameHeaders.toList(),+ )+ }++ @Test fun normalizeSiteStripsSchemeCredentialsPortAndWww() {+ assertEquals("example.com", DomainMatch.normalizeSite("https://user:[email protected]:8443/path?q=1"))+ assertEquals("example.com", DomainMatch.normalizeSite("example.com."))+ assertEquals("", DomainMatch.normalizeSite(" "))+ }++ @Test fun androidPackageDetection() {+ assertTrue(DomainMatch.isAndroidPackageSite("android-app://com.example.app"))+ assertTrue(DomainMatch.isAndroidPackageSite("com.example.app"))+ assertFalse(DomainMatch.isAndroidPackageSite("example.com"))+ assertFalse(DomainMatch.isAndroidPackageSite("https://com.example.com/path"))+ }++ @Test fun subdomainMatchingIsDotAware() {+ assertTrue(DomainMatch.isSameSiteOrSubdomain("mail.example.com", "example.com"))+ assertTrue(DomainMatch.isSameSiteOrSubdomain("example.com", "example.com"))+ assertFalse(DomainMatch.isSameSiteOrSubdomain("notexample.com", "example.com"))+ assertFalse(DomainMatch.isSameSiteOrSubdomain("", "example.com"))+ assertFalse(DomainMatch.isSameSiteOrSubdomain("example.com", ""))+ }+}
passwords/src/test/java/com/vayunmathur/passwords/domain/TotpAndCborTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/domain/TotpAndCborTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/domain/TotpAndCborTest.ktnew file mode 100644index 0000000000..f108f2dd3b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/domain/TotpAndCborTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.passwords.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++class TotpAndCborTest {++ // RFC 4226/6238 test key "12345678901234567890" (ASCII), base32-encoded.+ private val secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"++ @Test fun totpMatchesRfcVectorAt59Seconds() {+ // Counter 1, HOTP value from RFC 4226 Appendix D.+ assertEquals("287082", TOTP.generate(secret, 59))+ }++ @Test fun totpMatchesRfcVectorAt1111111109() {+ assertEquals("081804", TOTP.generate(secret, 1_111_111_109))+ }++ @Test fun totpIsStableWithinStepAndChangesAcrossSteps() {+ assertEquals(TOTP.generate(secret, 60), TOTP.generate(secret, 89))+ assertTrue(TOTP.generate(secret, 60) != TOTP.generate(secret, 90))+ }++ @Test fun totpNormalizesCaseSpacesAndPadding() {+ assertEquals(+ TOTP.generate(secret, 59),+ TOTP.generate(" gezdgnbv gy3tqojqgezdgnbvgy3tqojq== ", 59),+ )+ }++ @Test fun totpEmptySecretIsRejected() {+ assertFailsWith<IllegalArgumentException> { TOTP.generate("", 59) }+ }++ @Test fun cborEncodesScalars() {+ assertEquals(listOf(0x00.toByte()), Cbor.encode(0L).toList())+ assertEquals(listOf(0x17.toByte()), Cbor.encode(23).toList())+ assertEquals(listOf(0x18.toByte(), 0x18.toByte()), Cbor.encode(24).toList())+ assertEquals(listOf(0x20.toByte()), Cbor.encode(-1L).toList())+ assertEquals(listOf(0xF4.toByte()), Cbor.encode(false).toList())+ assertEquals(listOf(0xF5.toByte()), Cbor.encode(true).toList())+ }++ @Test fun cborEncodesStringsByUtf8Length() {+ assertEquals(listOf(0x61.toByte(), 'a'.code.toByte()), Cbor.encode("a").toList())+ // "é" is 2 UTF-8 bytes, so the header says length 2.+ val encoded = Cbor.encode("é")+ assertEquals(0x62.toByte(), encoded[0])+ assertEquals(3, encoded.size)+ }++ @Test fun cborEncodesByteArraysListsAndMaps() {+ assertEquals(+ listOf(0x43, 1, 2, 3),+ Cbor.encode(byteArrayOf(1, 2, 3)).map { it.toInt() and 0xFF },+ )+ assertEquals(+ listOf(0x82, 0x01, 0x61, 0x61),+ Cbor.encode(listOf(1L, "a")).map { it.toInt() and 0xFF },+ )+ val map = Cbor.encode(mapOf(1L to "x"))+ assertEquals(0xA1.toByte(), map[0])+ }++ @Test fun cborRejectsUnsupportedType() {+ assertFailsWith<IllegalArgumentException> { Cbor.encode(Any()) }+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.ktnew file mode 100644index 0000000000..a18aea068d--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyEntriesTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.passwords.platform++import android.content.Context+import android.os.Bundle+import androidx.credentials.provider.BeginGetPasswordOption+import androidx.credentials.provider.BeginGetPublicKeyCredentialOption+import androidx.test.core.app.ApplicationProvider+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 kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyEntriesTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private val passkey = Passkey(id = 1, rpId = "example.com", userName = "alice", credentialId = "cred-1", syncId = "pk-1")+ private val password = Password(id = 2, name = "Mail", username = "alice", password = "pw", syncId = "pw-1")++ private inner class FakePasskeyDao : PasskeyDao() {+ override fun getAllFlow(): Flow<List<Passkey>> = flowOf(listOf(passkey))+ override suspend fun getAll(): List<Passkey> = listOf(passkey)+ override suspend fun getByRpId(rpId: String): List<Passkey> =+ if (rpId == "example.com") listOf(passkey) else emptyList()+ override suspend fun getByCredentialId(credentialId: String): Passkey? = null+ override suspend fun getBySyncId(syncId: String): Passkey? = null+ override suspend fun getUpdatedSince(since: Long): List<Passkey> = emptyList()+ override suspend fun upsertRaw(passkey: Passkey): Long = passkey.id+ override suspend fun delete(passkey: Passkey): Int = 0+ override suspend fun deleteBySyncId(syncId: String): Int = 0+ override suspend fun deleteAll() = Unit+ }++ private inner class FakePasswordDao : PasswordDao() {+ override fun getAllFlow(): Flow<List<Password>> = flowOf(listOf(password))+ override suspend fun getAll(): List<Password> = listOf(password)+ override fun getByIdFlow(id: Long): Flow<Password?> = flowOf(password)+ override suspend fun getById(id: Long): Password? = password+ override suspend fun getBySyncId(syncId: String): Password? = null+ override suspend fun getUpdatedSince(since: Long): List<Password> = emptyList()+ override suspend fun upsertRaw(value: Password): Long = value.id+ override suspend fun delete(value: Password): Int = 0+ override suspend fun deleteBySyncId(syncId: String): Int = 0+ override suspend fun deleteAll() = Unit+ }++ @Test fun passwordOptionYieldsOneEntryPerPassword() = runBlocking {+ val response = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPasswordOption(emptySet(), Bundle(), "req-1")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(1, response.credentialEntries.size)+ }++ @Test fun publicKeyOptionYieldsMatchingPasskeysOnly() = runBlocking {+ val matching = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-2", """{"rpId":"example.com","challenge":"Y2hhbGxlbmdl"}""")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(1, matching.credentialEntries.size)++ val noRp = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-3", """{"rpId":"","challenge":"Y2hhbGxlbmdl"}""")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(0, noRp.credentialEntries.size)++ val otherRp = buildGetCredentialResponse(+ ctx,+ listOf(BeginGetPublicKeyCredentialOption(Bundle(), "req-4", """{"rpId":"other.com","challenge":"Y2hhbGxlbmdl"}""")),+ FakePasskeyDao(),+ FakePasswordDao(),+ )+ assertEquals(0, otherRp.credentialEntries.size)+ }++ @Test fun noOptionsYieldEmptyResponse() = runBlocking {+ val response = buildGetCredentialResponse(ctx, emptyList(), FakePasskeyDao(), FakePasswordDao())+ assertEquals(0, response.credentialEntries.size)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.ktnew file mode 100644index 0000000000..17999a43fe--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasskeyUtilsTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.passwords.platform++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class PasskeyUtilsTest {++ @Test fun b64UrlRoundTripsWithoutPadding() {+ val data = byteArrayOf(0, 1, 2, 250.toByte(), 251.toByte(), 255.toByte())+ val encoded = PasskeyUtils.encodeB64Url(data)+ assertTrue(!encoded.contains('='))+ assertTrue(!encoded.contains('+') && !encoded.contains('/'))+ assertEquals(data.toList(), PasskeyUtils.decodeB64Url(encoded).toList())+ }++ @Test fun credentialIdsAre16RandomBytes() {+ val a = PasskeyUtils.generateCredentialId()+ val b = PasskeyUtils.generateCredentialId()+ assertEquals(16, a.size)+ assertTrue(!a.contentEquals(b))+ }++ @Test fun authenticatorDataLayout() {+ val data = PasskeyUtils.buildAuthenticatorData("example.com", signCount = 0x01020304)+ // 32-byte rpId hash + 1 flag byte + 4-byte big-endian sign count.+ assertEquals(37, data.size)+ assertEquals(listOf(1, 2, 3, 4), data.takeLast(4).map { it.toInt() and 0xFF })+ // UP|UV|BE|BS set by default.+ assertEquals(0x01 or 0x04 or 0x08 or 0x10, data[32].toInt() and 0xFF)+ }++ @Test fun authenticatorDataFlagsOffAndAttested() {+ val data = PasskeyUtils.buildAuthenticatorData(+ "example.com", userPresent = false, userVerified = false,+ backupEligible = false, backupState = false, attestedCredentialData = true,+ )+ assertEquals(0x40, data[32].toInt() and 0xFF)+ }++ @Test fun aaguidIs16Bytes() {+ assertEquals(16, PasskeyUtils.SAME_DEVICE_AAGUID.size)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelImportTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelImportTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelImportTest.ktnew file mode 100644index 0000000000..6767d63569--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelImportTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.data.PasswordRepository+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import java.io.ByteArrayInputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordsViewModelImportTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() = FakeAndroidKeyStore.install()++ private fun vm() = PasswordsViewModel(app, PasswordRepository.get(app))++ private fun serve(uri: Uri, text: String) {+ shadowOf(app.contentResolver).registerInputStream(uri, ByteArrayInputStream(text.toByteArray()))+ }++ private fun awaitImportDone(viewModel: PasswordsViewModel) {+ // The import runs on viewModelScope + Dispatchers.IO; wait until the+ // VM reports completion instead of sleeping a fixed duration.+ val deadline = System.currentTimeMillis() + 10_000+ while (System.currentTimeMillis() < deadline) {+ shadowOf(android.os.Looper.getMainLooper()).idle()+ if (!viewModel.importing.value && viewModel.importMessage.value != null) return+ Thread.sleep(10)+ }+ error("import did not finish: importing=${viewModel.importing.value} message=${viewModel.importMessage.value}")+ }++ @Test fun importEmptyFileReportsZeroRows() {+ val viewModel = vm()+ val uri = Uri.parse("content://test/empty.csv")+ serve(uri, "")+ viewModel.importCsv(uri)+ awaitImportDone(viewModel)+ assertEquals("Imported 0 rows, skipped 0 rows", viewModel.importMessage.value)+ assertFalse(viewModel.importing.value)+ }++ @Test fun importHeaderOnlyFileReportsZeroRows() {+ val viewModel = vm()+ val uri = Uri.parse("content://test/header.csv")+ serve(uri, "name,login_username,login_password,login_uri,login_totp\n")+ viewModel.importCsv(uri)+ awaitImportDone(viewModel)+ assertEquals("Imported 0 rows, skipped 0 rows", viewModel.importMessage.value)+ }++ @Test fun importBlankRowsOnlyReportsZeroRows() {+ val viewModel = vm()+ val uri = Uri.parse("content://test/blank.csv")+ serve(uri, "name,login_username,login_password\n,,\n,,\n")+ viewModel.importCsv(uri)+ awaitImportDone(viewModel)+ assertEquals("Imported 0 rows, skipped 0 rows", viewModel.importMessage.value)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelTest.ktnew file mode 100644index 0000000000..395153fbe8--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/PasswordsViewModelTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.passwords.platform++import android.app.Application+import android.content.ClipboardManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.data.PasswordRepository+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.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordsViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun vm() = PasswordsViewModel(app, PasswordRepository.get(app))++ @Test fun draftLifecycle() {+ val viewModel = vm()+ assertNull(viewModel.draft.value)+ viewModel.updateDraft { it.copy(name = "X") } // no draft yet: no-op+ assertNull(viewModel.draft.value)++ val seed = Password(id = 3, name = "GitHub")+ viewModel.initDraft(seed)+ assertEquals("GitHub", viewModel.draft.value?.name)++ // Same id does not clobber edits; a different id reseeds.+ viewModel.updateDraft { it.copy(name = "Edited") }+ viewModel.initDraft(Password(id = 3, name = "Other"))+ assertEquals("Edited", viewModel.draft.value?.name)+ viewModel.initDraft(Password(id = 4, name = "New"))+ assertEquals("New", viewModel.draft.value?.name)++ viewModel.clearDraft()+ assertNull(viewModel.draft.value)+ }++ @Test fun saveDraftWithoutDraftIsNoOp() {+ val viewModel = vm()+ viewModel.saveDraft()+ assertNull(viewModel.draft.value)+ }++ @Test fun copyToClipboardWritesSensitiveClip() {+ val viewModel = vm()+ viewModel.copyToClipboard("password", "s3cret")+ val clipboard = app.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager+ assertEquals("s3cret", clipboard.primaryClip?.getItemAt(0)?.text)+ assertEquals("password", clipboard.primaryClip?.description?.label)+ }++ @Test fun initialStateIsEmptyAndNotLoaded() {+ val viewModel = vm()+ assertEquals(emptyList(), viewModel.passwords.value)+ assertEquals(emptyList(), viewModel.passkeys.value)+ assertEquals(false, viewModel.loaded.value)+ assertEquals(false, viewModel.importing.value)+ assertNull(viewModel.importMessage.value)+ }++ @Test fun factoryCreatesAndRejectsOtherClasses() {+ val factory = PasswordsViewModelFactory(app, PasswordRepository.get(app))+ val created = factory.create(PasswordsViewModel::class.java)+ assertTrue(created is PasswordsViewModel)+ assertFailsWith<IllegalArgumentException> {+ factory.create(OtherViewModel::class.java)+ }+ }++ @Test fun backupFormatProperties() {+ val format = vm().buildBackupFormat()+ assertEquals("passwords.kdbx", format.defaultFileName)+ assertEquals(true, format.needsPassword)+ assertEquals("application/octet-stream", format.mimeType)+ }+}++private class OtherViewModel : androidx.lifecycle.ViewModel()
passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesRoboTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesRoboTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesRoboTest.ktnew file mode 100644index 0000000000..2eb1975b3e--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/ServicesRoboTest.kt@@ -0,0 +1,65 @@+package com.vayunmathur.passwords.platform++import android.content.Intent+import android.os.CancellationSignal+import android.os.OutcomeReceiver+import androidx.credentials.exceptions.GetCredentialException+import androidx.credentials.provider.BeginGetCredentialRequest+import androidx.credentials.provider.BeginGetCredentialResponse+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.platform.cable.CableActivity+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.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class ServicesRoboTest {++ @Before fun setUp() = FakeAndroidKeyStore.install()++ @Test fun cableActivityWithoutUriFinishes() {+ val controller = Robolectric.buildActivity(CableActivity::class.java, Intent())+ controller.create()+ assertTrue(controller.get().isFinishing)+ }++ @Test fun cableActivityWithBogusUriFinishes() {+ val intent = Intent().putExtra(+ com.vayunmathur.passwords.platform.cable.CableService.EXTRA_FIDO_URI, "https://example.com",+ )+ val controller = Robolectric.buildActivity(CableActivity::class.java, intent)+ controller.create()+ assertTrue(controller.get().isFinishing)+ }++ @Test fun credentialServiceGetWithoutKeyReturnsUnlockAction() {+ val service = Robolectric.buildService(PasskeyCredentialService::class.java).create().get()+ var response: BeginGetCredentialResponse? = null+ service.onBeginGetCredentialRequest(+ BeginGetCredentialRequest(listOf()),+ CancellationSignal(),+ object : OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException> {+ override fun onResult(r: BeginGetCredentialResponse) { response = r }+ override fun onError(error: GetCredentialException) = Unit+ },+ )+ assertNotNull(response)+ assertEquals(1, response!!.authenticationActions.size)+ }++ @Test fun cableServiceWithoutUriStopsItself() {+ val controller = Robolectric.buildService(+ com.vayunmathur.passwords.platform.cable.CableService::class.java,+ ).create()+ val service = controller.get()+ val result = service.onStartCommand(Intent(), 0, 1)+ assertEquals(android.app.Service.START_NOT_STICKY, result)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableInfraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableInfraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableInfraTest.ktnew file mode 100644index 0000000000..04966aa0c5--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableInfraTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.passwords.platform.cable++import android.content.Context+import androidx.test.core.app.ApplicationProvider+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.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class CableInfraTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun assignedTunnelDomains() {+ assertEquals("cable.ua5v.com", TunnelDomains.decode(0))+ assertEquals("cable.auth.com", TunnelDomains.decode(1))+ assertEquals(0, TunnelDomains.DEFAULT_ID)+ }++ @Test fun unknownAssignedDomainIsRejected() {+ assertFailsWith<IllegalArgumentException> { TunnelDomains.decode(2) }+ assertFailsWith<IllegalArgumentException> { TunnelDomains.decode(-1) }+ assertFailsWith<IllegalArgumentException> { TunnelDomains.decode(0x10000) }+ }++ @Test fun algorithmicDomainIsDerivedDeterministically() {+ val a = TunnelDomains.decode(300)+ assertEquals(a, TunnelDomains.decode(300))+ assertTrue(a.startsWith("cable."))+ assertTrue(a.endsWith(".com") || a.endsWith(".org") || a.endsWith(".net") || a.endsWith(".info"))+ }++ @Test fun tunnelHexEncoding() {+ assertEquals("00ff10", CableTunnel.hex(byteArrayOf(0, 0xFF.toByte(), 0x10)))+ assertEquals("", CableTunnel.hex(byteArrayOf()))+ assertEquals("fido.cable", CableTunnel.SUBPROTOCOL)+ }++ @Test fun uuid16Expansion() {+ assertEquals(+ "0000f1d0-0000-1000-8000-00805f9b34fb",+ CableAdvertiser.uuid16(0xF1D0).toString(),+ )+ // Values are masked to 16 bits.+ assertEquals(CableAdvertiser.uuid16(0xF1D0), CableAdvertiser.uuid16(0x1F1D0))+ }++ @Test fun advertiserStartWithoutBluetoothReportsFailure() {+ val advertiser = CableAdvertiser(ctx)+ var result: Boolean? = null+ advertiser.start(byteArrayOf(1, 2, 3)) { result = it }+ // Robolectric has no LE advertiser, so start must report false (or+ // succeed only if a shadow advertiser exists — either way it returns).+ assertTrue(result != null || advertiser.isAvailable)+ advertiser.stop()+ }++ @Test fun bluetoothHelpersDoNotCrash() {+ // Supported/enabled depend on the shadow adapter; both must answer.+ assertEquals(CableBluetooth.adapter(ctx) != null, CableBluetooth.isSupported(ctx))+ assertTrue(CableBluetooth.isEnabled(ctx) || CableBluetooth.adapter(ctx) != null)+ assertFalse(CableBluetooth.isEnabled(ctx) && CableBluetooth.adapter(ctx) == null)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAuthenticatorTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAuthenticatorTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAuthenticatorTest.ktnew file mode 100644index 0000000000..e26ce6b748--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/WebAuthnAuthenticatorTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.platform.PasskeyUtils+import kotlinx.coroutines.runBlocking+import java.security.KeyFactory+import java.security.Signature+import java.security.spec.X509EncodedKeySpec+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class WebAuthnAuthenticatorTest {++ @Test fun createCredentialPersistsAndBuildsAttestedData() = runBlocking {+ val store = FakePasskeyStore()+ val created = WebAuthnAuthenticator.createCredential(+ rpId = "example.com",+ rpName = "Example",+ userId = "user-1".toByteArray(),+ userName = "alice",+ userDisplayName = "Alice",+ aaguid = ByteArray(16),+ store = store,+ )+ assertEquals(1, store.store.size)+ assertEquals("example.com", created.passkey.rpId)+ assertEquals(16, created.credentialId.size)+ // 37-byte header + 16 aaguid + 2 credIdLen + 16 credId + COSE key.+ assertEquals(37 + 16 + 2 + 16, created.authenticatorData.size - created.coseKey.size)+ assertTrue(created.publicKeySpki.isNotEmpty())+ // AT flag set.+ assertTrue(created.authenticatorData[32].toInt() and 0x40 != 0)+ }++ @Test fun reRegisteringSameUserReplacesInPlace() = runBlocking {+ val store = FakePasskeyStore()+ val first = WebAuthnAuthenticator.createCredential(+ "example.com", "Example", "u".toByteArray(), "alice", "Alice", ByteArray(16), store,+ )+ val second = WebAuthnAuthenticator.createCredential(+ "example.com", "Example", "u".toByteArray(), "alice", "Alice", ByteArray(16), store,+ )+ assertEquals(1, store.store.size)+ assertEquals(first.passkey.id, second.passkey.id)+ assertEquals(first.passkey.syncId, second.passkey.syncId)+ }++ @Test fun signAssertionIncrementsCountAndVerifies() = runBlocking {+ val store = FakePasskeyStore()+ val created = WebAuthnAuthenticator.createCredential(+ "example.com", "Example", "u".toByteArray(), "alice", "Alice", ByteArray(16), store,+ )+ val hash = ByteArray(32) { it.toByte() }+ val result = WebAuthnAuthenticator.signAssertion(created.passkey, hash, store)+ assertEquals(1, result.newSignCount)+ assertEquals(1, store.store.single().signCount)+ assertEquals(37, result.authenticatorData.size)++ val publicKey = KeyFactory.getInstance("EC")+ .generatePublic(X509EncodedKeySpec(created.publicKeySpki))+ val verifier = Signature.getInstance("SHA256withECDSA")+ verifier.initVerify(publicKey)+ verifier.update(result.authenticatorData + hash)+ assertTrue(verifier.verify(result.signature))+ }++ @Test fun signWithPasskeyProducesVerifiableSignature() = runBlocking {+ val store = FakePasskeyStore()+ val created = WebAuthnAuthenticator.createCredential(+ "example.com", "Example", "u".toByteArray(), "alice", "Alice",+ PasskeyUtils.SAME_DEVICE_AAGUID, store,+ )+ val signature = WebAuthnAuthenticator.signWithPasskey(created.passkey, "data".toByteArray())+ val publicKey = KeyFactory.getInstance("EC")+ .generatePublic(X509EncodedKeySpec(created.publicKeySpki))+ val verifier = Signature.getInstance("SHA256withECDSA")+ verifier.initVerify(publicKey)+ verifier.update("data".toByteArray())+ assertTrue(verifier.verify(signature))+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxPasswordHelperTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxPasswordHelperTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxPasswordHelperTest.ktnew file mode 100644index 0000000000..f04b361fd5--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxPasswordHelperTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+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.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxPasswordHelperTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() = FakeAndroidKeyStore.install()++ @Test fun storeAndReadBackPassphrase() {+ val helper = KdbxPasswordHelper(ctx)+ assertFalse(helper.isKeyGenerated())+ helper.storePassphrase("correct horse battery staple")+ assertTrue(helper.isKeyGenerated())+ assertEquals("correct horse battery staple", helper.getPassphrase())+ }++ @Test fun storedPassphraseSurvivesNewHelperInstance() {+ KdbxPasswordHelper(ctx).storePassphrase("vault-pw-2")+ assertEquals("vault-pw-2", KdbxPasswordHelper(ctx).getPassphrase())+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSettingsAndRunSyncTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSettingsAndRunSyncTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSettingsAndRunSyncTest.ktnew file mode 100644index 0000000000..4ee8dc81e3--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSettingsAndRunSyncTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+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.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxSettingsAndRunSyncTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun settingsRoundTrip() = runBlocking {+ KdbxSyncSettings.setEnabled(ctx, true)+ assertTrue(KdbxSyncSettings.enabled(ctx))+ assertTrue(KdbxSyncSettings.enabledFlow(ctx).first())+ KdbxSyncSettings.setEnabled(ctx, false)+ assertFalse(KdbxSyncSettings.enabled(ctx))++ KdbxSyncSettings.setDocumentUri(ctx, "content://vault.kdbx")+ assertEquals("content://vault.kdbx", KdbxSyncSettings.documentUri(ctx))+ KdbxSyncSettings.setDocumentUri(ctx, "")+ assertNull(KdbxSyncSettings.documentUri(ctx))+ }++ @Test fun recordSuccessFailureAndQuarantine() = runBlocking {+ KdbxSyncSettings.recordSuccess(ctx)+ assertEquals(KdbxSyncSettings.STATUS_OK, KdbxSyncSettings.statusFlow(ctx).first())+ assertTrue(KdbxSyncSettings.lastSyncFlow(ctx).first() > 0)++ KdbxSyncSettings.recordFailure(ctx, "file_missing")+ assertEquals(KdbxSyncSettings.STATUS_ERROR, KdbxSyncSettings.statusFlow(ctx).first())+ assertEquals("file_missing", KdbxSyncSettings.errorFlow(ctx).first())++ KdbxSyncSettings.recordQuarantine(ctx, KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)+ assertEquals(KdbxSyncSettings.STATUS_QUARANTINED, KdbxSyncSettings.statusFlow(ctx).first())+ assertEquals("foreign_delete", KdbxSyncSettings.quarantineFlow(ctx).first())+ assertTrue(KdbxSyncSettings.quarantineAtFlow(ctx).first() > 0)++ KdbxSyncSettings.clearQuarantine(ctx)+ assertEquals("", KdbxSyncSettings.quarantineFlow(ctx).first())+ assertEquals("", KdbxSyncSettings.statusFlow(ctx).first())+ }++ @Test fun runSyncNotConfiguredWhenDisabled() = runBlocking {+ KdbxSyncSettings.setEnabled(ApplicationProvider.getApplicationContext(), false)+ val db = androidx.room3.Room.inMemoryDatabaseBuilder(+ ctx, com.vayunmathur.passwords.data.PasswordDatabase::class.java,+ ).allowMainThreadQueries().build()+ try {+ assertEquals(KdbxSyncResult.NotConfigured, runKdbxSync(ctx, db))+ } finally {+ db.close()+ }+ }++ @Test fun errorCodes() {+ assertEquals("file_missing", KdbxSyncResult.FileMissing.errorCode())+ assertEquals("wrong_password", KdbxSyncResult.WrongPassword.errorCode())+ assertEquals("verify_failed", KdbxSyncResult.VerifyFailed.errorCode())+ assertEquals("quarantined", KdbxSyncResult.Quarantined(2).errorCode())+ assertEquals("boom", KdbxSyncResult.Error("boom").errorCode())+ assertEquals("", KdbxSyncResult.NotConfigured.errorCode())+ assertEquals("", KdbxSyncResult.Success(0, 0, 0, 0).errorCode())+ }++ // KdbxPasswordHelper.isKeyGenerated needs the AndroidKeyStore provider,+ // which Robolectric 4.17 does not shadow, so it is covered on-device only.+}
passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncSchedulerTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncSchedulerTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncSchedulerTest.ktnew file mode 100644index 0000000000..f0a0e8a976--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/KdbxSyncSchedulerTest.kt@@ -0,0 +1,51 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+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.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxSyncSchedulerTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() {+ FakeAndroidKeyStore.install()+ runCatching {+ WorkManager.initialize(ctx, Configuration.Builder().build())+ }+ }++ @Test fun schedulingEnqueuesNamedWork() {+ val wm = WorkManager.getInstance(ctx)+ KdbxSyncScheduler.schedulePeriodic(ctx)+ KdbxSyncScheduler.syncNow(ctx)+ KdbxSyncScheduler.scheduleDebounced(ctx)++ assertTrue(wm.getWorkInfosForUniqueWork("KdbxSyncPeriodic").get().isNotEmpty())+ assertTrue(wm.getWorkInfosForUniqueWork("KdbxSyncNow").get().isNotEmpty())+ assertTrue(wm.getWorkInfosForUniqueWork("KdbxSyncAfterEdit").get().isNotEmpty())++ KdbxSyncScheduler.cancel(ctx)+ val states = wm.getWorkInfosForUniqueWork("KdbxSyncPeriodic").get().map { it.state }+ assertTrue(states.all { it.isFinished })+ }++ @Test fun workerSucceedsBeforeUnlock() = runBlocking {+ // No keystore key has been generated in this sandbox, so the worker+ // must report success without touching the database.+ val worker = androidx.work.testing.TestListenableWorkerBuilder<KdbxSyncWorker>(ctx).build()+ assertEquals(androidx.work.ListenableWorker.Result.success(), worker.doWork())+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecTest.ktnew file mode 100644index 0000000000..7d49c19f8b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/NativeKdbxCodecTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.passwords.sync++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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class NativeKdbxCodecTest {++ @Test fun roundTripsEntriesThroughRealKdbx() {+ val entries = listOf(+ mapOf("Title" to "GitHub", "UserName" to "octocat", "Password" to "s3cret", "_SyncId" to "sync-1"),+ mapOf("Title" to "Mail", "UserName" to "alice", "Password" to "pw2"),+ )+ val bytes = NativeKdbxCodec.write("vault-pw", entries)+ assertNotNull(bytes)+ val restored = NativeKdbxCodec.read("vault-pw", bytes)+ assertNotNull(restored)+ assertEquals(2, restored.size)+ val github = restored.first { it["Title"] == "GitHub" }+ assertEquals("octocat", github["UserName"])+ assertEquals("s3cret", github["Password"])+ }++ @Test fun wrongPasswordFailsToRead() {+ val bytes = NativeKdbxCodec.write("right", listOf(mapOf("Title" to "A")))+ assertNotNull(bytes)+ assertNull(NativeKdbxCodec.read("wrong", bytes))+ }++ @Test fun garbageBytesFailToRead() {+ assertNull(NativeKdbxCodec.read("pw", byteArrayOf(1, 2, 3, 4)))+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/RelayJsonTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayJsonTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayJsonTest.ktnew file mode 100644index 0000000000..255a4db281--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/RelayJsonTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.passwords.sync++import android.util.Base64+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RelayJsonTest {++ private val json = Json { ignoreUnknownKeys = true }++ @Test fun passwordEnvelopeRoundTrips() {+ val pw = Password(+ id = 7, name = "GitHub", username = "octo", email = "[email protected]",+ password = "secret", note = "n", totpSecret = "ABC",+ websites = listOf("github.com"), syncId = "sync-a", updatedAt = 1234,+ )+ val relay = pw.toRelayJson()+ assertEquals(false, relay.isPasskey)+ val restored = relay.toPassword(id = 9)+ assertEquals(9L, restored.id)+ assertEquals("GitHub", restored.name)+ assertEquals("sync-a", restored.syncId)+ assertEquals(1234L, restored.updatedAt)+ assertEquals(listOf("github.com"), restored.websites)+ }++ @Test fun passkeyEnvelopeRoundTripsBytes() {+ val pk = Passkey(+ id = 3, rpId = "example.com", rpName = "Example", credentialId = "cred",+ userId = "u1", userName = "alice", privateKeyBytes = byteArrayOf(5, 6, 7),+ creationTime = 10, lastUsedTime = 20, signCount = 2, syncId = "pk-a", updatedAt = 99,+ )+ val relay = pk.toRelayJson()+ assertTrue(relay.isPasskey)+ assertEquals(+ Base64.encodeToString(byteArrayOf(5, 6, 7), Base64.NO_WRAP),+ relay.privateKeyB64,+ )+ val restored = relay.toPasskey(id = 4)+ assertEquals(byteArrayOf(5, 6, 7).toList(), restored.privateKeyBytes.toList())+ assertEquals("pk-a", restored.syncId)+ assertEquals(2, restored.signCount)+ }++ @Test fun passkeyPayloadCarrierRoundTrips() {+ val pk = Passkey(rpId = "a.com", credentialId = "c", privateKeyBytes = byteArrayOf(1), syncId = "s")+ val payload = PasswordPasskeyPayload.fromPasskey(pk)+ assertEquals(pk.rpId, payload.toPasskey().rpId)+ assertEquals(byteArrayOf(1).toList(), payload.toPasskey().privateKeyBytes.toList())+ }++ @Test fun badBase64FallsBackToEmptyKey() {+ val relay = RelayPasswordJson(uid = "x", isPasskey = true, privateKeyB64 = "!!!not-base64!!!")+ assertEquals(0, relay.toPasskey(0).privateKeyBytes.size)+ }++ @Test fun envelopeSerializesWithStableFieldNames() {+ val text = json.encodeToString(Password(name = "A", syncId = "u1").toRelayJson())+ assertTrue(text.contains("\"uid\":\"u1\""))+ // Default-valued fields are omitted by the relay Json configuration.+ val parsed = json.decodeFromString(RelayPasswordJson.serializer(), text)+ assertEquals("A", parsed.name)+ }++ @Test fun providerUriBuildersAndTypes() {+ assertEquals(+ "content://com.vayunmathur.passwords.relay/vault/v1/passwords",+ RelayPasswordProvider.passwordsUri("v1").toString(),+ )+ assertTrue(RelayPasswordProvider.passkeysUri("v1").toString().endsWith("/passkeys"))+ assertTrue(RelayPasswordProvider.snapshotsUri("v1").toString().endsWith("/snapshots"))+ assertEquals(5, RelayPasswordProvider.COLUMNS.size)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/sync/RunKdbxSyncExtraTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/sync/RunKdbxSyncExtraTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/sync/RunKdbxSyncExtraTest.ktnew file mode 100644index 0000000000..bf633bca2c--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/sync/RunKdbxSyncExtraTest.kt@@ -0,0 +1,57 @@+package com.vayunmathur.passwords.sync++import android.content.Context+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.Route+import com.vayunmathur.passwords.data.PasswordRepository+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.Json+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class RunKdbxSyncExtraTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Before fun setUp() = FakeAndroidKeyStore.install()++ @Test fun repositoryOverloadNotConfiguredWithoutUri() = runBlocking {+ KdbxSyncSettings.setEnabled(ctx, true)+ KdbxSyncSettings.setDocumentUri(ctx, "")+ val repo = PasswordRepository.get(ctx)+ assertEquals(KdbxSyncResult.NotConfigured, runKdbxSync(ctx, repo))+ }++ @Test fun repositoryOverloadNotConfiguredWithoutVaultKey() = runBlocking {+ KdbxSyncSettings.setEnabled(ctx, true)+ KdbxSyncSettings.setDocumentUri(ctx, "content://vault.kdbx")+ // No KDBX vault key has been stored in this sandbox.+ val repo = PasswordRepository.get(ctx)+ assertEquals(KdbxSyncResult.NotConfigured, runKdbxSync(ctx, repo))+ }++ @Test fun safDocumentReadMissingThrowsFileNotFound() {+ val doc = SafKdbxDocument(ctx, Uri.parse("content://missing/vault.kdbx"))+ assertFailsWith<UnsupportedOperationException> { doc.read() }+ }++ @Test fun routeSerializationRoundTrips() {+ val json = Json+ assertEquals(+ Route.PasswordPage(42),+ json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.PasswordPage(42))),+ )+ assertEquals(Route.Menu, json.decodeFromString(Route.serializer(), json.encodeToString(Route.serializer(), Route.Menu)))+ assertTrue(Route.PasswordEditPage(1) != Route.PasswordPage(1))+ }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/KdbxSyncSectionComposeTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/KdbxSyncSectionComposeTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/KdbxSyncSectionComposeTest.ktnew file mode 100644index 0000000000..8f033d6511--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/KdbxSyncSectionComposeTest.kt@@ -0,0 +1,85 @@+package com.vayunmathur.passwords.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performTextInput+import com.vayunmathur.passwords.FakeAndroidKeyStore+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class KdbxSyncSectionComposeTest {++ @get:Rule val rule = createComposeRule()++ @Before fun setUp() {+ FakeAndroidKeyStore.install()+ // DataStore files survive between tests in this sandbox; reset the+ // quarantine state the quarantine test sets.+ val ctx = androidx.test.core.app.ApplicationProvider+ .getApplicationContext<android.content.Context>()+ kotlinx.coroutines.runBlocking {+ com.vayunmathur.passwords.sync.KdbxSyncSettings.clearQuarantine(ctx)+ }+ }++ @Test fun sectionShowsSyncRows() {+ rule.setContent { KdbxSyncSection() }+ rule.onNodeWithText("KDBX Sync").assertIsDisplayed()+ rule.onNodeWithText("Sync with a KDBX file").assertIsDisplayed()+ rule.onNodeWithText("KDBX file").assertIsDisplayed()+ rule.onNodeWithText("Vault password").assertIsDisplayed()+ rule.onNodeWithText("Last sync").assertIsDisplayed()+ rule.onNodeWithText("Sync now").assertIsDisplayed()+ }++ @Test fun vaultPasswordDialogOpensAndCancels() {+ rule.setContent { KdbxSyncSection() }+ rule.onNodeWithText("Vault password").performClick()+ rule.onNodeWithText("Save").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ rule.onNodeWithText("Sync now").assertIsDisplayed()+ }++ @Test fun vaultPasswordDialogSavesEnteredPassword() {+ rule.setContent { KdbxSyncSection() }+ rule.onNodeWithText("Vault password").performClick()+ // The dialog's text field is the editable node in the dialog.+ rule.onAllNodes(hasSetTextAction())[0].performTextInput("vault-pw-123")+ rule.onNodeWithText("Save").performClick()+ rule.onNodeWithText("Sync now").assertIsDisplayed()+ }++ @Test fun quarantinedStateShowsReviewRowAndResolveDialog() {+ val ctx = androidx.test.core.app.ApplicationProvider+ .getApplicationContext<android.content.Context>()+ kotlinx.coroutines.runBlocking {+ com.vayunmathur.passwords.sync.KdbxSyncSettings+ .recordQuarantine(ctx, com.vayunmathur.passwords.sync.KdbxSyncSettings.QUARANTINE_FOREIGN_DELETE)+ }+ rule.setContent { KdbxSyncSection() }+ rule.waitUntil(timeoutMillis = 5_000) {+ rule.onAllNodesWithText("Review paused sync").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Review paused sync").assertIsDisplayed()+ rule.onNodeWithText("Review paused sync").performClick()+ rule.onNodeWithText("Re-check and resume").assertIsDisplayed()+ rule.onNodeWithText("Cancel").performClick()+ }++ @Test fun fileMenuShowsChooseAndCreate() {+ rule.setContent { KdbxSyncSection() }+ rule.onNodeWithText("KDBX file").performClick()+ rule.onNodeWithText("Choose existing file").assertIsDisplayed()+ rule.onNodeWithText("Create new file").assertIsDisplayed()+ }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/PagesComposeTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PagesComposeTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PagesComposeTest.ktnew file mode 100644index 0000000000..dfe8c7a5f4--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PagesComposeTest.kt@@ -0,0 +1,55 @@+package com.vayunmathur.passwords.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.passwords.FakeAndroidKeyStore+import com.vayunmathur.passwords.Route+import com.vayunmathur.passwords.data.PasswordRepository+import com.vayunmathur.passwords.platform.PasswordsViewModel+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PagesComposeTest {++ @get:Rule val rule = createComposeRule()++ @Before fun setUp() = FakeAndroidKeyStore.install()++ private fun vm(): PasswordsViewModel {+ val app = ApplicationProvider.getApplicationContext<Application>()+ return PasswordsViewModel(app, PasswordRepository.get(app))+ }++ @Test fun settingsPageShowsImportWarningAndButton() {+ val backStack = NavBackStack<Route>(arrayOf(Route.Settings))+ rule.setContent { SettingsPage(backStack, vm()) }+ rule.onNodeWithText("Settings").assertIsDisplayed()+ rule.onNodeWithText("Import Passwords").assertIsDisplayed()+ }++ @Test fun settingsImportMenuListsSources() {+ val backStack = NavBackStack<Route>(arrayOf(Route.Settings))+ rule.setContent { SettingsPage(backStack, vm()) }+ rule.onNodeWithText("Import Passwords").performClick()+ rule.onNodeWithText("Bitwarden").assertIsDisplayed()+ rule.onNodeWithText("Firefox").assertIsDisplayed()+ }++ @Test fun autofillSettingsActivityFinishesImmediately() {+ val controller = org.robolectric.Robolectric.buildActivity(AutofillSettingsActivity::class.java)+ controller.create()+ assertEquals(true, controller.get().isFinishing)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthActivityTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthActivityTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthActivityTest.ktnew file mode 100644index 0000000000..b037b2f783--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasskeyAuthActivityTest.kt@@ -0,0 +1,69 @@+package com.vayunmathur.passwords.ui++import android.app.Activity+import android.content.Intent+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.Shadows.shadowOf+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasskeyAuthActivityTest {++ @Before fun setUp() {+ FakeAndroidKeyStore.install()+ // Pretend the vault has already been unlocked once, so the activity+ // proceeds straight to flow dispatch instead of the biometric gate.+ val ctx = org.robolectric.RuntimeEnvironment.getApplication()+ DatabaseHelper(ctx).storePassphrase("test-passphrase")+ }++ private fun launch(flow: String?): PasskeyAuthActivity {+ val intent = Intent(+ org.robolectric.RuntimeEnvironment.getApplication(),+ PasskeyAuthActivity::class.java,+ )+ if (flow != null) intent.putExtra(PasskeyAuthActivity.EXTRA_FLOW, flow)+ val controller = Robolectric.buildActivity(PasskeyAuthActivity::class.java, intent)+ controller.create()+ return controller.get()+ }++ @Test fun unknownFlowCancelsAndFinishes() {+ val activity = launch(null)+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ }++ @Test fun getFlowWithoutProviderRequestCancels() {+ val activity = launch(PasskeyAuthActivity.FLOW_GET)+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ }++ @Test fun createFlowWithoutProviderRequestCancels() {+ val activity = launch(PasskeyAuthActivity.FLOW_CREATE)+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ }++ @Test fun passwordFlowWithoutProviderRequestCancels() {+ val activity = launch(PasskeyAuthActivity.FLOW_PASSWORD)+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ }++ @Test fun unlockFlowWithoutRequestCancels() {+ val activity = launch(PasskeyAuthActivity.FLOW_UNLOCK)+ assertTrue(activity.isFinishing)+ assertEquals(Activity.RESULT_CANCELED, shadowOf(activity).resultCode)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/ui/PasswordScreensComposeTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/ui/PasswordScreensComposeTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasswordScreensComposeTest.ktnew file mode 100644index 0000000000..ed3c446a1b--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/ui/PasswordScreensComposeTest.kt@@ -0,0 +1,251 @@+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.hasScrollAction+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.performScrollToNode+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.Password+import com.vayunmathur.passwords.platform.PasswordEditUiState+import com.vayunmathur.passwords.platform.PasswordUiState+import com.vayunmathur.passwords.platform.PasswordsActions+import com.vayunmathur.passwords.platform.MenuUiState+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.passwords.Route+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class PasswordScreensComposeTest {++ @get:Rule val rule = createComposeRule()++ private val sample = Password(+ id = 1, name = "GitHub", username = "octocat", email = "[email protected]",+ password = "hunter2secret", note = "work account",+ totpSecret = "JBSWY3DPEHPK3PXP",+ websites = listOf("github.com", "https://gist.github.com"),+ syncId = "sync-a",+ )++ @Test fun passwordScreenShowsAllSections() {+ rule.setContent {+ PasswordScreen(+ state = PasswordUiState(password = sample, now = { 60_000L }),+ actions = PasswordsActions.Noop,+ )+ }+ rule.onAllNodesWithText("GitHub")[0].assertIsDisplayed()+ rule.onAllNodesWithText("octocat")[0].assertIsDisplayed()+ rule.onNodeWithText("[email protected]").assertExists()+ }++ @Test fun passwordScreenRevealsAndCopiesPassword() {+ var copied: String? = null+ var deleted = false+ val actions = object : PasswordsActions {+ override fun copyToClipboard(label: String, text: String, feedback: String?) { copied = text }+ override fun delete(password: Password) { deleted = true }+ }+ rule.setContent {+ PasswordScreen(+ state = PasswordUiState(password = sample.copy(totpSecret = null), now = { 0L }),+ actions = actions,+ )+ }+ // Masked by default: bullet count equals password length.+ rule.onNodeWithText("•".repeat("hunter2secret".length)).assertIsDisplayed()+ assertEquals(null, copied)+ assertTrue(!deleted)+ }++ @Test fun passwordScreenWithInitialRevealShowsPlaintext() {+ rule.setContent {+ PasswordScreen(+ state = PasswordUiState(password = sample.copy(totpSecret = null), now = { 0L }),+ actions = PasswordsActions.Noop,+ initialShowPassword = true,+ )+ }+ rule.onNodeWithText("hunter2secret").assertIsDisplayed()+ }++ @Test fun passwordScreenScrollsToNoteWebsitesAndPasskeys() {+ val pk = Passkey(id = 9, rpId = "github.com", rpName = "GitHub Passkey", userName = "octocat", syncId = "pk-9")+ rule.setContent {+ PasswordScreen(+ state = PasswordUiState(password = sample, passkeys = listOf(pk), now = { 60_000L }),+ actions = PasswordsActions.Noop,+ )+ }+ rule.onNode(hasScrollAction()).performScrollToNode(hasText("work account"))+ rule.onNodeWithText("work account").assertIsDisplayed()+ rule.onNode(hasScrollAction()).performScrollToNode(hasText("Websites"))+ rule.onNodeWithText("Websites").assertIsDisplayed()+ rule.onNode(hasScrollAction()).performScrollToNode(hasText("GitHub Passkey"))+ rule.onNodeWithText("GitHub Passkey").assertIsDisplayed()+ }++ @Test fun sanitizeUrlPrefixesBareHosts() {+ assertEquals("https://example.com", sanitizeUrl(" example.com "))+ assertEquals("http://example.com", sanitizeUrl("http://example.com"))+ assertEquals("https://example.com", sanitizeUrl("https://example.com"))+ }++ @Test fun editScreenForNewEntryShowsAddTitleAndFields() {+ rule.setContent {+ PasswordEditScreen(+ state = PasswordEditUiState(saved = Password(), draft = Password()),+ actions = PasswordsActions.Noop,+ )+ }+ rule.onNodeWithText("Add Password").assertIsDisplayed()+ rule.onNodeWithText("Name").assertIsDisplayed()+ rule.onNodeWithText("Username").assertIsDisplayed()+ rule.onNodeWithText("TOTP Secret").assertIsDisplayed()+ rule.onNodeWithText("Add website").assertExists()+ }++ @Test fun editScreenForExistingEntryShowsValuesAndSave() {+ var saved = false+ val actions = object : PasswordsActions {+ override fun saveDraft(onSaved: ((Long) -> Unit)?) { saved = true }+ }+ rule.setContent {+ PasswordEditScreen(+ state = PasswordEditUiState(saved = sample, draft = sample),+ actions = actions,+ )+ }+ rule.onNodeWithText("Edit Password").assertIsDisplayed()+ rule.onNodeWithText("GitHub").assertIsDisplayed()+ rule.onNodeWithText("github.com").assertExists()+ rule.onNodeWithText("Save").performClick()+ assertTrue(saved)+ }++ @Test fun editScreenBlankNameShowsErrorAndDoesNotSave() {+ var saved = false+ val actions = object : PasswordsActions {+ override fun saveDraft(onSaved: ((Long) -> Unit)?) { saved = true }+ }+ val blank = Password(id = 5, name = "")+ rule.setContent {+ PasswordEditScreen(+ state = PasswordEditUiState(saved = blank, draft = blank),+ actions = actions,+ )+ }+ rule.onNodeWithText("Save").performClick()+ rule.onNodeWithText("Name cannot be empty").assertIsDisplayed()+ assertTrue(!saved)+ }++ @Test fun editScreenFieldEditsFlowThroughUpdateDraft() {+ var draft = Password(id = 7, name = "Old", username = "", websites = listOf("a.com"))+ val actions = object : PasswordsActions {+ override fun updateDraft(transform: (Password) -> Password) { draft = transform(draft) }+ }+ rule.setContent {+ PasswordEditScreen(+ state = PasswordEditUiState(saved = draft, draft = draft),+ actions = actions,+ )+ }+ rule.onNodeWithText("Old").performTextReplacement("New Name")+ assertEquals("New Name", draft.name)+ // Removing the website chip drops it from the draft.+ rule.onNodeWithText("a.com").assertExists()+ }++ @Test fun menuScreenTotpRowCopiesCodeOnClick() {+ var copied: String? = null+ val actions = object : PasswordsActions {+ override fun copyToClipboard(label: String, text: String, feedback: String?) { copied = text }+ }+ val backStack = NavBackStack<Route>(arrayOf(Route.Menu))+ rule.setContent {+ MenuScreen(+ backStack = backStack,+ state = MenuUiState(passwords = listOf(sample), now = { 60_000L }),+ actions = actions,+ )+ }+ // The TOTP code for the known test secret at t=60s is rendered and clickable.+ val code = com.vayunmathur.passwords.domain.TOTP.generate("JBSWY3DPEHPK3PXP", 60)+ rule.onNodeWithText(code).performClick()+ assertEquals(code, copied)+ }++ @Test fun sectionRowShowsLabelAndValue() {+ var copies = 0+ rule.setContent {+ PasswordScreenSection(label = "Username", value = "octocat", onCopy = { copies++ })+ }+ rule.onNodeWithText("Username").assertIsDisplayed()+ rule.onAllNodesWithText("octocat")[0].assertIsDisplayed()+ assertEquals(0, copies)+ }++ @Test fun linkDialogListsPasswordsAndSelects() {+ var selected: Password? = null+ rule.setContent {+ PasskeyLinkDialog(+ passwords = listOf(sample),+ onDismiss = {},+ onSelect = { selected = it },+ )+ }+ rule.onNodeWithText("GitHub").assertIsDisplayed()+ rule.onNodeWithText("GitHub").performClick()+ assertEquals("GitHub", selected?.name)+ }++ @Test fun linkDialogEmptyState() {+ rule.setContent {+ PasskeyLinkDialog(passwords = emptyList(), onDismiss = {}, onSelect = {})+ }+ rule.onNodeWithText("No entries to link to").assertIsDisplayed()+ }++ @Test fun menuScreenShowsPasswordsAndStandalonePasskeys() {+ val pk = Passkey(id = 2, rpId = "example.com", rpName = "Example", userName = "alice", syncId = "pk-1")+ val backStack = NavBackStack<Route>(arrayOf(Route.Menu))+ rule.setContent {+ MenuScreen(+ backStack = backStack,+ state = MenuUiState(+ passwords = listOf(sample.copy(totpSecret = null)),+ passkeys = listOf(pk),+ now = { 0L },+ ),+ actions = PasswordsActions.Noop,+ )+ }+ rule.onNodeWithText("GitHub").assertIsDisplayed()+ rule.onNodeWithText("Example").assertIsDisplayed()+ }++ @Test fun menuScreenEmptyVaultRenders() {+ val backStack = NavBackStack<Route>(arrayOf(Route.Menu))+ rule.setContent {+ MenuScreen(+ backStack = backStack,+ state = MenuUiState(now = { 0L }),+ actions = PasswordsActions.Noop,+ )+ }+ rule.onNodeWithText("Passwords").assertIsDisplayed()+ }+}