securemail: add tests for database, crypto, policy and screens
- Commit
09be9621b3f425d9dd69f288a24e61fbf199ca69- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 04:24 UTC (29 days ago)
- Parents
da491cf
Covers the Room vault DAOs (messages/keys/outbox/identities, folder moves, trash, migrations list), MailConfig DataStore round-trip, KeyLookupPolicy send gating and RFC 7929 WKD URLs, DraftsController decode, native PgpCrypto identity/encrypt/decrypt/sign round-trips, and Robolectric Compose tests for the inbox, reader, compose, lock, onboarding, settings and out screens. Coverage (merged, instructions): 10.7% -> 40.4% (2921/27258 -> 11011/27258). Full suite passes via gslot ./gradlew :securemail:createMergedCoverageReport. Bugs fixed: none. Untestable remainder: MailViewModel and everything that constructs MailRepository (Room/SQLCipher open requires AndroidKeyStore, absent under Robolectric), InboundStore/SenderKeys/AliasController relay paths, MailSocketService/MailSyncWorker, Navigation, and KeyManager (AndroidKeyStore/biometric). (cherry picked from commit 1c7a150c8cea4c02f40a8551e9a935416c862137)
Diff
securemail/src/test/java/com/vayunmathur/securemail/data/MailDatabaseTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/data/MailDatabaseTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/data/MailDatabaseTest.ktnew file mode 100644index 0000000000..c25a2d365c--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/data/MailDatabaseTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.securemail.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.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MailDatabaseTest {+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+ private fun db() = Room.inMemoryDatabaseBuilder(ctx, MailDatabase::class.java).allowMainThreadQueries().build()+ private fun msg(id: String, folder: MailFolder = MailFolder.INBOX, date: Long = 0, read: Boolean = false) = StoredMessage(+ id = id, from = "[email protected]", toJson = "[]", dateMillis = date, messageId = id,+ blobBase64 = "AA==", isRead = read, folder = folder,+ )++ @Test fun `message dao upsert folder read trash and delete`() = runBlocking {+ val db = db(); val dao = db.messageDao()+ dao.upsert(msg("1", date = 100)); dao.upsert(msg("2", date = 200)); dao.upsert(msg("3", MailFolder.TRASH, 300))+ assertEquals(listOf("2", "1"), dao.observeFolder(MailFolder.INBOX).first().map { it.id })+ assertEquals(3, dao.observeAll().first().size)+ dao.setRead(listOf("1"), true)+ assertEquals(true, dao.get("1")?.isRead)+ dao.markRead("2"); assertEquals(true, dao.get("2")?.isRead)+ dao.storeDecrypted("1", "body", "subj", "signer", "<b>hi</b>")+ val stored = dao.get("1")!!+ assertEquals("body", stored.decryptedBody); assertEquals("subj", stored.decryptedSubject)+ assertEquals("signer", stored.verifiedSigner); assertEquals("<b>hi</b>", stored.decryptedHtml)+ dao.moveTo(listOf("1"), MailFolder.TRASH)+ assertEquals(MailFolder.TRASH, dao.get("1")?.folder)+ dao.emptyTrash()+ assertNull(dao.get("1")); assertNull(dao.get("3")); assertEquals("2", dao.get("2")?.id)+ dao.deleteAll(listOf("2")); assertEquals(0, dao.observeAll().first().size)+ dao.upsert(msg("9")); dao.delete("9"); assertNull(dao.get("9"))+ assertEquals(4, MailDatabase.migrations.size)+ db.close()+ }++ @Test fun `key outbox and identity daos`() = runBlocking {+ val db = db()+ db.keyDao().upsert(CachedKey("[email protected]", "armor", "FF00", "Wkd", 5))+ assertEquals("armor", db.keyDao().get("[email protected]")?.armoredPublic)+ db.keyDao().upsert(CachedKey("[email protected]", "armor2", "FF01", "Cached", 6))+ assertEquals("armor2", db.keyDao().get("[email protected]")?.armoredPublic)+ assertNull(db.keyDao().get("[email protected]"))++ val first = db.outboxDao().insert(OutboxMessage(toJson = "[]", subject = "s", body = "b", createdMillis = 10))+ val second = db.outboxDao().insert(OutboxMessage(toJson = "[]", subject = "s2", body = "b2", createdMillis = 5))+ assertEquals(2, db.outboxDao().observeCount().first())+ assertEquals(listOf(second, first), db.outboxDao().all().map { it.rowId })+ db.outboxDao().noteAttempt(first, "boom")+ val attempted = db.outboxDao().all().first { it.rowId == first }+ assertEquals("boom", attempted.lastError); assertEquals(1, attempted.attemptCount)+ db.outboxDao().delete(first); assertEquals(1, db.outboxDao().observeCount().first())++ db.identityDao().upsert(MailIdentity("[email protected]", "alias", "pub", "AA", "sec", isPrimary = false, createdMillis = 20))+ db.identityDao().upsert(MailIdentity("[email protected]", "primary", "pub", "BB", "sec", isPrimary = true, createdMillis = 10))+ assertEquals(listOf("[email protected]", "[email protected]"), db.identityDao().observeAll().first().map { it.address })+ assertEquals("[email protected]", db.identityDao().primary()?.address)+ assertEquals(2, db.identityDao().count())+ db.identityDao().setDisabled("[email protected]", true) // primary cannot be disabled+ assertEquals(false, db.identityDao().get("[email protected]")?.disabled)+ db.identityDao().setDisabled("[email protected]", true)+ assertEquals(listOf("[email protected]"), db.identityDao().active().map { it.address })+ db.identityDao().deleteAll(); assertEquals(0, db.identityDao().count())+ assertTrue(MailFolder.entries.contains(MailFolder.SPAM))+ db.close()+ }+}
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicyAndConfigTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicyAndConfigTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicyAndConfigTest.ktnew file mode 100644index 0000000000..1e7e4061ff--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/KeyLookupPolicyAndConfigTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.securemail.domain.mail++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.securemail.data.MailConfig+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy.KeySource+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy.RecipientTrust+import com.vayunmathur.securemail.domain.mail.KeyLookupPolicy.SendDecision+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class KeyLookupPolicyAndConfigTest {+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+ private fun trust(address: String, hasKey: Boolean, changed: Boolean = false, lost: Boolean = false) =+ RecipientTrust(address, hasKey, if (hasKey) KeySource.Wkd else KeySource.None, keyChanged = changed, keyLost = lost)++ @Test fun `send decision encrypts, falls back, and gates key changes`() {+ assertEquals(SendDecision.Encrypted, KeyLookupPolicy.decide(emptyList()))+ assertEquals(SendDecision.Encrypted, KeyLookupPolicy.decide(listOf(trust("[email protected]", true))))+ val fallback = KeyLookupPolicy.decide(listOf(trust("[email protected]", true), trust("[email protected]", false)))+ assertEquals(SendDecision.UnencryptedFallback(listOf("[email protected]")), fallback)+ val changed = KeyLookupPolicy.decide(listOf(trust("[email protected]", true, changed = true), trust("[email protected]", false)))+ assertTrue(changed is SendDecision.NeedsKeyChangeAck)+ assertEquals(listOf("[email protected]"), (changed as SendDecision.NeedsKeyChangeAck).changed.map { it.address })+ val lost = KeyLookupPolicy.decide(listOf(trust("[email protected]", false, lost = true)))+ assertTrue(lost is SendDecision.NeedsKeyChangeAck)+ }++ @Test fun `wkd urls follow rfc7929 advanced then direct`() {+ assertTrue(KeyLookupPolicy.wkdUrls("no-at-sign").isEmpty())+ assertTrue(KeyLookupPolicy.wkdUrls("@x.org").isEmpty())+ assertTrue(KeyLookupPolicy.wkdUrls("a@").isEmpty())+ val urls = KeyLookupPolicy.wkdUrls("[email protected]")+ assertEquals(2, urls.size)+ assertTrue(urls[0].startsWith("https://openpgpkey.example.org/.well-known/openpgpkey/example.org/hu/"))+ assertTrue(urls[0].endsWith("?l=Ada"))+ assertTrue(urls[1].startsWith("https://example.org/.well-known/openpgpkey/hu/"))+ assertEquals(urls[1], KeyLookupPolicy.wkdUrl("[email protected]"))+ // z-base32 of SHA-1("ada") is deterministic and uses only the z-base32 alphabet+ val hash = KeyLookupPolicy.wkdHash("ada")+ assertEquals(32, hash.length)+ assertTrue(hash.all { it in "ybndrfg8ejkmcpqxot1uwisza345h769" })+ }++ @Test fun `mail config round trips identity and sync time`() = runBlocking {+ val config = MailConfig(ctx)+ config.clear()+ assertFalse(config.settings.first().isConfigured)+ config.setIdentity("[email protected]", "pub-armor", "AABB")+ config.setLastSync(12345L)+ val settings = config.settings.first()+ assertEquals("[email protected]", settings.address)+ assertEquals("pub-armor", settings.publicArmor)+ assertEquals("AABB", settings.fingerprintHex)+ assertEquals(12345L, settings.lastSyncMillis)+ assertTrue(settings.isConfigured)+ config.clear()+ assertFalse(config.settings.first().isConfigured)+ }++ @Test fun `address validator accepts normal addresses and rejects malformed`() {+ assertTrue(AddressValidator.isValidAddress("[email protected]"))+ assertTrue(AddressValidator.isValidAddress("[email protected]"))+ assertFalse(AddressValidator.isValidAddress("not-an-address"))+ assertFalse(AddressValidator.isValidAddress("@example.org"))+ assertFalse(AddressValidator.isValidAddress("ada@"))+ assertTrue(AddressValidator.isOwnDomain("[email protected]"))+ assertFalse(AddressValidator.isOwnDomain("[email protected]"))+ }+}
securemail/src/test/java/com/vayunmathur/securemail/domain/pgp/PgpCryptoTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/pgp/PgpCryptoTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/pgp/PgpCryptoTest.ktnew file mode 100644index 0000000000..de5087a9c8--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/pgp/PgpCryptoTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.securemail.domain.pgp++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFails+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class PgpCryptoTest {++ @Test fun `identity encrypt decrypt and sign round trip`() {+ val identity = PgpCrypto.generateIdentity("Ada <[email protected]>", "correct horse battery")+ assertTrue(identity.armoredPublic.contains("PGP PUBLIC KEY"))+ assertTrue(identity.armoredSecret.contains("PGP PRIVATE KEY"))+ assertEquals(identity.fingerprintHex.lowercase(), PgpCrypto.fingerprintHex(identity.armoredPublic).lowercase())++ val plain = "meet at noon".toByteArray()+ val cipher = PgpCrypto.encrypt(plain, identity.armoredPublic)+ assertFalse(cipher.contentEquals(plain))+ assertEquals("meet at noon", PgpCrypto.decrypt(cipher, identity.armoredSecret, "correct horse battery").decodeToString())++ val signed = PgpCrypto.encryptSigned(plain, identity.armoredPublic, identity.armoredSecret, "correct horse battery")+ val opened = PgpCrypto.decryptVerify(signed, identity.armoredSecret, "correct horse battery", identity.armoredPublic)+ assertEquals("meet at noon", opened.payload.decodeToString())+ assertEquals(identity.fingerprintHex.lowercase(), opened.signerFingerprintHex.lowercase())++ val signature = PgpCrypto.signDetached(identity.armoredSecret, "correct horse battery", plain)+ assertTrue(signature.isNotEmpty())+ assertTrue(PgpCrypto.armorMessage(cipher).contains("PGP MESSAGE"))+ }++ @Test fun `wrong passphrase and malformed keys fail`() {+ val identity = PgpCrypto.generateIdentity("Bob <[email protected]>", "passphrase-one")+ val cipher = PgpCrypto.encrypt("secret".toByteArray(), identity.armoredPublic)+ assertFails { PgpCrypto.decrypt(cipher, identity.armoredSecret, "passphrase-two") }+ assertFails { PgpCrypto.fingerprintHex("not a key") }+ assertFails { PgpCrypto.encrypt("x".toByteArray(), "not a key") }+ }+}
securemail/src/test/java/com/vayunmathur/securemail/platform/DraftsControllerTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/platform/DraftsControllerTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/platform/DraftsControllerTest.ktnew file mode 100644index 0000000000..f1385c77b6--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/platform/DraftsControllerTest.kt@@ -0,0 +1,31 @@+package com.vayunmathur.securemail.platform++import com.vayunmathur.securemail.data.MailFolder+import com.vayunmathur.securemail.data.StoredMessage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class DraftsControllerTest {+ @Test fun `draft decode round trips and empty draft detection`() {+ val row = StoredMessage(+ id = "d1", from = "[email protected]",+ toJson = """{"to":["[email protected]"],"cc":[],"bcc":["[email protected]"],"inReplyTo":"m1"}""",+ dateMillis = 1, messageId = "d1", blobBase64 = "",+ decryptedBody = "hello", decryptedSubject = "hi", folder = MailFolder.DRAFTS,+ )+ val draft = DraftsController.decode(row)+ assertEquals(listOf("[email protected]"), draft.to)+ assertEquals(listOf("[email protected]"), draft.bcc)+ assertEquals("hi", draft.subject); assertEquals("hello", draft.body)+ assertEquals("m1", draft.inReplyTo)+ assertFalse(draft.isEmpty)+ assertTrue(Draft().isEmpty)+ assertTrue(Draft(subject = "x").isEmpty.not())+ val bad = DraftsController.decode(row.copy(toJson = "not json", from = ""))+ assertTrue(bad.to.isEmpty())+ assertNull(bad.from)+ }+}
securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensTest.ktnew file mode 100644index 0000000000..c2a7c4ef37--- /dev/null+++ b/securemail/src/test/java/com/vayunmathur/securemail/ui/MailScreensTest.kt@@ -0,0 +1,138 @@+package com.vayunmathur.securemail.ui++import androidx.compose.ui.test.assertCountEquals+import androidx.compose.ui.test.hasText+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.securemail.data.MailFolder+import com.vayunmathur.securemail.data.MailIdentity+import com.vayunmathur.securemail.data.OutboxMessage+import com.vayunmathur.securemail.data.StoredMessage+import com.vayunmathur.securemail.platform.MailUiState+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MailScreensTest {+ @get:Rule val rule = createComposeRule()+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun msg(id: String, subject: String, body: String = "body", read: Boolean = false, folder: MailFolder = MailFolder.INBOX) =+ StoredMessage(id = id, from = "[email protected]", toJson = "[]", dateMillis = 1700000000000, messageId = id,+ blobBase64 = "", decryptedBody = body, decryptedSubject = subject, isRead = read, folder = folder)++ private fun folderActions(opened: MutableList<String> = mutableListOf()) = FolderActions(+ onOpen = { opened += it }, onCompose = {}, onSetRead = { _, _ -> }, onTrash = {},+ onMoveTo = { _, _ -> }, onRestore = {}, onDeleteForever = {}, onEmptyTrash = {}, onConsumeMessage = {},+ )++ @Test fun `inbox renders messages and empty folders show nothing to open`() {+ val opened = mutableListOf<String>()+ rule.setContent {+ InboxScreen(state = MailUiState(address = "[email protected]"), folder = MailFolder.INBOX,+ actions = folderActions(opened), messages = listOf(msg("1", "Hello there"), msg("2", "Second", read = true)))+ }+ rule.onNodeWithText("Hello there").assertExists()+ rule.onNodeWithText("Second").assertExists()+ rule.onNodeWithText("Hello there").performClick()+ assertEquals(listOf("1"), opened)+ }++ @Test fun `inbox empty state renders no message rows`() {+ rule.setContent {+ InboxScreen(state = MailUiState(), folder = MailFolder.SPAM, actions = folderActions(), messages = emptyList())+ }+ rule.onAllNodes(hasText("Hello there")).assertCountEquals(0)+ }++ @Test fun `reader shows subject body and missing message placeholder`() {+ val replies = mutableListOf<StoredMessage>()+ rule.setContent {+ ReaderScreen(state = MailUiState(), onReply = { replies += it }, onBack = {},+ message = msg("1", "Quarterly report", body = "See attached numbers"))+ }+ rule.onNodeWithText("Quarterly report").assertExists()+ rule.onNodeWithText("See attached numbers", substring = true).assertExists()+ assertTrue(replies.isEmpty())+ }++ @Test fun `reader without message shows generic title`() {+ rule.setContent { ReaderScreen(state = MailUiState(), onReply = {}, onBack = {}, message = null) }+ rule.onNodeWithText("Message").assertExists()+ }++ @Test fun `message body view renders decrypted body`() {+ rule.setContent { MessageBodyView(msg("1", "S", body = "Plain body text here")) }+ rule.onNodeWithText("Plain body text here", substring = true).assertExists()+ }++ @Test fun `lock screen offers unlock and onboarding claims`() {+ var unlocks = 0+ rule.setContent { LockScreen(state = MailUiState(locked = true), onUnlock = { unlocks++ }, onDismissMessages = {}) }+ rule.onNodeWithText("SecureMail locked").assertExists()+ assertEquals(0, unlocks)+ }++ @Test fun `onboarding explains claim flow`() {+ rule.setContent { OnboardingScreen(state = MailUiState(), onClaim = { _, _ -> }, onDismissMessages = {}) }+ rule.onNodeWithText("Set up SecureMail").assertExists()+ rule.onNodeWithText("Claim an @maemail.org address.", substring = true).assertExists()+ rule.onNodeWithText("Your address").assertExists()+ }++ @Test fun `settings lists identities and out screen lists drafts`() {+ val identities = listOf(+ MailIdentity("[email protected]", "Primary", "pub", "AA", "sec", isPrimary = true, createdMillis = 1),+ MailIdentity("[email protected]", "Shopping", "pub", "BB", "sec", createdMillis = 2),+ )+ rule.setContent {+ SettingsScreen(state = MailUiState(address = "[email protected]", fingerprintHex = "AABB"), identities = identities,+ onCreateAlias = {}, onSetAliasDisabled = { _, _ -> }, onExportPublicKey = {}, onForget = {})+ }+ rule.onNodeWithText("Settings").assertExists()+ rule.onNodeWithText("[email protected]", substring = true).assertExists()+ }++ @Test fun `out screen renders drafts outbox and sent sections`() {+ val actions = OutActions(onCompose = {}, onOpenDraft = {}, onDeleteDraft = {}, onRestoreDraft = {},+ onRetryOutbox = {}, onOpenSent = {}, onTrashSent = {}, onUntrashSent = {}, onSetRead = { _, _ -> })+ rule.setContent {+ OutScreen(+ drafts = listOf(msg("d1", "Draft subject", folder = MailFolder.DRAFTS)),+ outbox = listOf(OutboxMessage(toJson = "[]", subject = "Queued", body = "b", createdMillis = 1)),+ sent = listOf(msg("s1", "Sent subject", folder = MailFolder.SENT)),+ actions = actions,+ )+ }+ rule.onNodeWithText("Drafts").assertExists()+ rule.onNodeWithText("Draft subject").assertExists()+ }++ @Test fun `bottom bar tabs map folders`() {+ assertEquals(MailTab.INBOX, MailFolder.INBOX.tab())+ assertEquals(MailTab.TRASH, MailFolder.TRASH.tab())+ var selected: MailTab? = null+ rule.setContent { MailBottomBar(selected = MailTab.INBOX, outboxCount = 2, onSelect = { selected = it }) }+ assertEquals(null, selected)+ }++ @Test fun `compose screen renders recipient fields`() {+ rule.setContent {+ ComposeScreen(+ state = MailUiState(address = "[email protected]"), identities = emptyList(), draftFrom = null,+ onSelectFrom = {}, draftTo = listOf("[email protected]"), draftCc = emptyList(), draftBcc = emptyList(),+ initialSubject = "Hi", initialBody = "Body text",+ onAddRecipient = { _, _ -> true }, onRemoveRecipient = { _, _ -> },+ onSend = { _, _, _, _, _, _ -> }, onLeave = { _, _ -> }, onDiscard = {},+ )+ }+ rule.onNodeWithText("[email protected]").assertExists()+ rule.onNodeWithText("Hi").assertExists()+ }+}