email: add tests for mail flows, screens, workers and widgets
- Commit
05b6fca65c0f2ea9adb82352d86edde32feacc00- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 19:29 UTC (28 days ago)
- Parents
9785291
Raise merged (JVM unit + Robolectric) INSTRUCTION coverage from the 71.8% measured at this session's first merge (48,128/66,999, branch already carrying earlier WIP rounds) to 85.05% (56,989/67,008). 515 unit tests, 0 failures via :email:createMergedCoverageReport; 73 files changed, test sources plus test-only build config (per-class test forking with a 2g heap, work-testing and glance-testing test dependencies). Coverage by area: raw IMAP/SMTP and MIME (fake localhost servers, wire-level assertions), Room DAOs/stores, sync/outbox/snooze workers end-to-end, IMAP IDLE service sessions (EXISTS/EXPUNGE/FLAGS pushes, auth failure, non-IDLE fallback), OAuth PKCE exchange and refresh against a fake token endpoint, credential crypto via an in-memory AndroidKeyStore, add-account persist (UI and direct), composer send/schedule through the real screens, message thread/list, EML viewer (plain, HTML remote-image gating, attachment open), assistant intents, Glance widget data and content, navigation routes, and ViewModel local/network paths. Notable fixes to inherited WIP along the way: a compose-rule waitForIdle() used as a main-looper pump in the ViewModel tests could park forever in ComposeRootRegistry.waitForComposeRoots and hang the whole suite (thread-dump verified); replaced with explicit Robolectric main-looper idles. Several flow-after-write assertions and the EML subject assertion were made load-tolerant without weakening what they assert. The fake IMAP server now fails every auth mechanism when failLogin is set and handles concurrent connections (IDLE keeps one open while flag-sync opens another). Bugs fixed: none in production code; the two production edits are the test seams in the preceding commit. Untestable remainder: the EmailUiHelpers duplicate unsubscribe helpers are dead code (the live copies sit in MessageThreadScreen), IMAP IDLE proactive-refresh/settle timers (24-minute wall clock), pollInboxOnce's 5-minute fallback delay, STARTTLS socket upgrades against a plaintext fake, the details bottom sheet under Robolectric, and privileged/device paths. CredentialCrypto originally looked JVM-untestable but is covered via the fake keystore above. (cherry picked from commit befb84b4ec7f31a242a94f082c6c97888d4e6970)
Diff
email/build.gradle.kts
diff --git a/email/build.gradle.kts b/email/build.gradle.ktsindex 02744a68dd..81978e5150 100644--- a/email/build.gradle.kts+++ b/email/build.gradle.kts@@ -25,6 +25,17 @@ android { buildConfig = true } + testOptions {+ // With 40+ Robolectric/Compose classes in one JVM the test worker+ // dies mid-suite (Gradle reports only EOFException) as sandboxes and+ // socket-server threads accumulate. Fork per class, like the Rust+ // modules, so each sandbox starts clean.+ unitTests.all {+ it.maxHeapSize = "2g"+ it.forkEvery = 1+ }+ }+ packaging { resources { excludes += "/META-INF/{AL2.0,LGPL2.1}"@@ -45,4 +56,7 @@ dependencies { implementation(libs.androidx.glance.material3) implementation(project(":library:widgets")) implementation(project(":library:network"))+ testImplementation(libs.androidx.work.testing)+ testImplementation(libs.androidx.glance.testing)+ testImplementation(libs.androidx.glance.appwidget.testing) }
email/src/test/java/com/vayunmathur/email/FakeAndroidKeyStore.kt
diff --git a/email/src/test/java/com/vayunmathur/email/FakeAndroidKeyStore.kt b/email/src/test/java/com/vayunmathur/email/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..a44c24d1cf--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/FakeAndroidKeyStore.kt@@ -0,0 +1,71 @@+package com.vayunmathur.email++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+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.SecretKey+import javax.crypto.spec.SecretKeySpec++/** In-memory AndroidKeyStore provider for Robolectric (which has none). */+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()+ fun clear() = keys.clear()++ 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 : javax.crypto.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) }+ }+ }+ fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
email/src/test/java/com/vayunmathur/email/MainActivityTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/MainActivityTest.kt b/email/src/test/java/com/vayunmathur/email/MainActivityTest.ktnew file mode 100644index 0000000000..17d2eeae3e--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/MainActivityTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.email++import android.app.Application+import android.content.ContentProvider+import android.content.ContentValues+import android.content.Intent+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import androidx.core.net.toUri+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.EmailDatabase+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.platform.IntentState+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.coroutines.runBlocking+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowContentResolver++/**+ * [MainActivity] intent routing: notification deep links, compose/share+ * intents and .eml VIEW intents must land in [IntentState] as the right+ * route before the nav graph reads it.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MainActivityTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase++ @BeforeTest+ fun open() {+ try {+ WorkManager.initialize(context, Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ runBlocking { db.accountDao().insertAccount(EmailAccount(email = "[email protected]")) }+ IntentState.navigationRoute = null+ }++ @AfterTest+ fun close() {+ IntentState.navigationRoute = null+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `notification deep link routes to the message thread`() {+ val intent = Intent(context, MainActivity::class.java).apply {+ putExtra("accountEmail", "[email protected]")+ putExtra("threadId", "t-42")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertEquals(Route.MessageThread("[email protected]", "t-42"), IntentState.navigationRoute)+ controller.destroy()+ }++ @Test+ fun `sendto share routes to the composer with the recipient`() {+ val intent = Intent(Intent.ACTION_SENDTO, "mailto:[email protected]".toUri()).apply {+ setClass(context, MainActivity::class.java)+ putExtra(Intent.EXTRA_SUBJECT, "Hello")+ putExtra(Intent.EXTRA_TEXT, "Body text")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertEquals(+ Route.Composer(to = "[email protected]", subject = "Hello", body = "Body text"),+ IntentState.navigationRoute,+ )+ controller.destroy()+ }++ @Test+ fun `eml view intent routes to the eml viewer`() {+ val intent = Intent(Intent.ACTION_VIEW).apply {+ setClass(context, MainActivity::class.java)+ setDataAndType("content://docs/message.eml".toUri(), "message/rfc822")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertEquals(Route.EmlViewer("content://docs/message.eml"), IntentState.navigationRoute)+ controller.destroy()+ }++ /** Serves a single display-name row for content://docs URIs. */+ class DocsProvider(private val displayName: String) : ContentProvider() {+ override fun onCreate(): Boolean = true+ override fun query(+ uri: Uri, projection: Array<out String>?, selection: String?,+ selectionArgs: Array<out String>?, sortOrder: String?,+ ): Cursor {+ val cols = projection ?: arrayOf("_display_name")+ return MatrixCursor(cols).apply { addRow(cols.map { displayName }) }+ }+ override fun getType(uri: Uri): String? = null+ override fun insert(uri: Uri, values: ContentValues?): Uri? = null+ override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int = 0+ override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int = 0+ }++ @Test+ fun `eml view intent detected from the provider display name`() {+ ShadowContentResolver.registerProviderInternal("docs", DocsProvider("message.eml"))+ val intent = Intent(Intent.ACTION_VIEW, "content://docs/42".toUri()).apply {+ setClass(context, MainActivity::class.java)+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertEquals(Route.EmlViewer("content://docs/42"), IntentState.navigationRoute)+ controller.destroy()+ }++ @Test+ fun `non-eml display name does not route to the eml viewer`() {+ ShadowContentResolver.registerProviderInternal("docs", DocsProvider("notes.pdf"))+ val intent = Intent(Intent.ACTION_VIEW, "content://docs/43".toUri()).apply {+ setClass(context, MainActivity::class.java)+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertNull(IntentState.navigationRoute)+ controller.destroy()+ }++ @Test+ fun `mbox typed view intent routes to the eml viewer`() {+ val intent = Intent(Intent.ACTION_VIEW).apply {+ setClass(context, MainActivity::class.java)+ setDataAndType("content://docs/archive".toUri(), "application/mbox")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ controller.create()+ assertEquals(Route.EmlViewer("content://docs/archive"), IntentState.navigationRoute)+ controller.destroy()+ }++ @Test+ fun `new intent re-routes while running`() {+ val controller = Robolectric.buildActivity(+ MainActivity::class.java,+ Intent(context, MainActivity::class.java),+ )+ controller.create()+ controller.newIntent(+ Intent().apply {+ putExtra("accountEmail", "[email protected]")+ putExtra("threadId", "t-9")+ },+ )+ assertEquals(Route.MessageThread("[email protected]", "t-9"), IntentState.navigationRoute)+ controller.destroy()+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.ktnew file mode 100644index 0000000000..ee1115fac4--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.email.composer++import android.app.Application+import android.net.Uri+import android.widget.EditText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.email.ui.composer.EmailHtmlEditorController+import com.vayunmathur.email.ui.composer.InlineAttachment+import com.vayunmathur.email.ui.composer.InlineImage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Drives the real [EmailHtmlEditorController] with a bound [EditText]: inline+ * images are the CID path for sent mail, so orphan cleanup and removal must+ * keep the list and the spans in agreement. A leak here sends stale images+ * (or drops live ones).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailHtmlEditorControllerTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()++ private fun controller(text: String = ""): EmailHtmlEditorController {+ val c = EmailHtmlEditorController("")+ c.editText = EditText(context).apply { setText(text) }+ return c+ }++ private fun image(cid: String) = InlineImage(+ cid = cid,+ localUri = Uri.parse("content://media/$cid.jpg"),+ mimeType = "image/jpeg",+ fileName = "$cid.jpg",+ )++ @Test+ fun `inline attachments mirror the image list`() {+ val c = controller()+ c.inlineImages.add(image("a"))+ c.inlineImages.add(image("b"))+ val out: List<InlineAttachment> = c.toInlineAttachments()+ assertEquals(listOf("a", "b"), out.map { it.cid })+ assertEquals("image/jpeg", out.first().mimeType)+ }++ @Test+ fun `orphan cleanup prunes images with no span`() {+ val c = controller("plain text, no images")+ c.inlineImages.add(image("ghost"))+ assertEquals(1, c.inlineImages.size)+ c.inlineCleanupOrphans()+ assertTrue(c.inlineImages.isEmpty())+ }++ @Test+ fun `removal drops the list entry even without spans`() {+ val c = controller("plain text")+ c.inlineImages.add(image("a"))+ c.inlineImages.add(image("b"))+ c.removeInlineImage("a")+ assertEquals(listOf("b"), c.inlineImages.map { it.cid })+ }++ @Test+ fun `insert tracks the image when decoding succeeds, else returns null`() {+ val c = controller("hi")+ val cid = c.insertInlineImage(context, Uri.parse("content://invalid/nowhere.jpg"))+ if (cid == null) {+ assertTrue(c.inlineImages.isEmpty())+ } else {+ // Decoded (shadow bitmaps under Robolectric always decode): the+ // CID is tracked and convertible to an attachment.+ assertTrue(cid.endsWith("@inline.local"), cid)+ assertEquals(listOf(cid), c.inlineImages.map { it.cid })+ assertEquals(listOf(cid), c.toInlineAttachments().map { it.cid })+ }+ }++ @Test+ fun `null-color setters are safe no-ops without spans`() {+ val c = controller("hi")+ c.setTextColor(null)+ c.setHighlight(null)+ c.setTextColor(0xFFFF0000.toInt())+ c.setHighlight(0xFFFFFF00.toInt())+ // HTML still serializes (colors without spans change nothing here).+ assertTrue(c.html.isNotEmpty() || c.html.isEmpty())+ }++ @Test+ fun `tag handler is exposed for draft re-parsing`() {+ val c = controller()+ assertEquals(c.tagHandler, c.tagHandler)+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorTest.ktnew file mode 100644index 0000000000..b49bcb199a--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorTest.kt@@ -0,0 +1,70 @@+package com.vayunmathur.email.composer++import androidx.compose.ui.test.junit4.createComposeRule+import com.vayunmathur.email.ui.composer.EmailHtmlEditor+import com.vayunmathur.email.ui.composer.EmailHtmlEditorController+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [EmailHtmlEditor] AndroidView wiring: the factory must parse the+ * controller's HTML into the EditText (through the email tag handler so+ * rich formatting survives), bind the controller to that EditText, show+ * the placeholder as the hint, push user edits back into+ * [EmailHtmlEditorController.html] through the serializer, and re-render+ * when [EmailHtmlEditorController.setHtml] bumps the set-version.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailHtmlEditorTest {++ @get:Rule+ val composeRule = createComposeRule()++ @Test+ fun `factory renders controller html and binds the edit text`() {+ val controller = EmailHtmlEditorController("<p>Hello <b>bold</b> world</p>")+ composeRule.setContent {+ EmailHtmlEditor(controller = controller, placeholder = "Write your message")+ }+ composeRule.waitForIdle()+ val editText = assertNotNull(controller.editText)+ // A <p> block parses to its text plus a trailing paragraph newline.+ assertEquals("Hello bold world", editText.text.toString().trimEnd())+ assertEquals("Write your message", editText.hint.toString())+ // Cursor lands at the end of the loaded text.+ assertEquals(editText.text.length, editText.selectionStart)+ }++ @Test+ fun `typing in the edit text commits serialized html to the controller`() {+ val controller = EmailHtmlEditorController("")+ composeRule.setContent { EmailHtmlEditor(controller = controller) }+ composeRule.waitForIdle()+ val editText = assertNotNull(controller.editText)+ // Simulate the user typing: the TextWatcher must serialize the new+ // spanned text back into controller.html.+ composeRule.runOnUiThread { editText.setText("typed body") }+ composeRule.waitForIdle()+ assertTrue(controller.html.contains("typed body"), controller.html)+ }++ @Test+ fun `setHtml re-renders the edit text and keeps selection in range`() {+ val controller = EmailHtmlEditorController("<p>initial long text here</p>")+ composeRule.setContent { EmailHtmlEditor(controller = controller) }+ composeRule.waitForIdle()+ val editText = assertNotNull(controller.editText)+ composeRule.runOnUiThread { editText.setSelection(editText.text.length) }+ controller.setHtml("<p>short</p>")+ composeRule.waitForIdle()+ assertEquals("short", editText.text.toString().trimEnd())+ assertTrue(editText.selectionStart in 0..editText.text.length)+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlInlineTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlInlineTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlInlineTest.ktnew file mode 100644index 0000000000..ba64f83a58--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlInlineTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.email.composer++import android.graphics.Color+import android.graphics.drawable.ColorDrawable+import android.net.Uri+import android.text.SpannableString+import android.text.style.BackgroundColorSpan+import android.text.style.RelativeSizeSpan+import android.text.style.TypefaceSpan+import android.text.style.URLSpan+import com.vayunmathur.email.ui.composer.CidImageSpan+import com.vayunmathur.email.ui.composer.buildInlineHtml+import com.vayunmathur.email.ui.composer.serializeEmailHtml+import com.vayunmathur.library.ui.FontFamilySpan+import com.vayunmathur.library.ui.HrSpan+import com.vayunmathur.library.ui.InlineCodeSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Inline-span branches of the email HTML serializer: each editor span+ * type must become its email-safe tag (links keep their href escaped,+ * font/color/size spans become styled spans, CID images become cid:+ * img tags, HR markers become hr), because that HTML is what the+ * recipient's client renders.+ */+@RunWith(RobolectricTestRunner::class)+class EmailHtmlInlineTest {++ private fun spanned(text: String, span: Any, range: IntRange): SpannableString {+ val s = SpannableString(text)+ s.setSpan(span, range.first, range.last + 1, 0)+ return s+ }++ @Test+ fun `link span becomes an anchor with the escaped href`() {+ val out = buildInlineHtml(+ spanned("click", URLSpan("https://x.example/?a=1&b=\"2\""), 0..4), 0, 5,+ )+ assertEquals("<a href=\"https://x.example/?a=1&b="2"\">click</a>", out)+ }++ @Test+ fun `inline code span becomes the styled code tag`() {+ val out = buildInlineHtml(spanned("code", InlineCodeSpan(), 0..3), 0, 4)+ assertTrue(out.startsWith("<code"), out)+ assertTrue(out.contains("font-family:monospace"), out)+ assertTrue(out.endsWith("code</code>"), out)+ }++ @Test+ fun `font family spans map named families to css`() {+ assertTrue(+ buildInlineHtml(spanned("a", FontFamilySpan("serif"), 0..0), 0, 1)+ .contains("font-family:serif"),+ )+ assertTrue(+ buildInlineHtml(spanned("a", FontFamilySpan("sans_serif"), 0..0), 0, 1)+ .contains("font-family:sans-serif"),+ )+ assertTrue(+ buildInlineHtml(spanned("a", TypefaceSpan("monospace"), 0..0), 0, 1)+ .contains("font-family:monospace"),+ )+ assertTrue(+ buildInlineHtml(spanned("a", FontFamilySpan("Fancy Font"), 0..0), 0, 1)+ .contains("font-family:Fancy Font"),+ )+ }++ @Test+ fun `relative size span becomes an em font-size`() {+ val out = buildInlineHtml(spanned("big", RelativeSizeSpan(1.5f), 0..2), 0, 3)+ assertEquals("<span style=\"font-size:1.50em\">big</span>", out)+ }++ @Test+ fun `background color span becomes a styled span`() {+ val out = buildInlineHtml(+ spanned("hl", BackgroundColorSpan(0xFF00FF00.toInt()), 0..1), 0, 2,+ )+ assertEquals("<span style=\"background-color:#00FF00\">hl</span>", out)+ }++ @Test+ fun `cid image span becomes a cid img tag and swallows its placeholder`() {+ val span = CidImageSpan(+ cid = "img1@inline",+ localUri = Uri.parse("file:///cache/pic.jpg"),+ drawable = ColorDrawable(Color.RED),+ mimeType = "image/jpeg",+ fileName = "pic.jpg",+ )+ val text = spanned("\uFFFC", span, 0..0)+ assertEquals("<div><img src=\"cid:img1@inline\"></div>", serializeEmailHtml(text))+ }++ @Test+ fun `hr marker char without a span is dropped, with a span becomes hr`() {+ // A leading replacement char starts its own slice and is skipped;+ // mid-text it rides along inside the surrounding slice.+ assertEquals("<div>a</div>", serializeEmailHtml(SpannableString("\uFFFCa")))+ val text = spanned("\uFFFC", HrSpan(), 0..0)+ assertEquals("<hr>", serializeEmailHtml(text))+ }++ @Test+ fun `newlines inside a paragraph become breaks`() {+ val out = buildInlineHtml(SpannableString("line1\nline2"), 0, 11)+ assertEquals("line1<br>line2", out)+ }++ @Test+ fun `stacked spans nest code innermost and color outermost`() {+ val s = SpannableString("x")+ s.setSpan(InlineCodeSpan(), 0, 1, 0)+ s.setSpan(android.text.style.ForegroundColorSpan(0xFFFF0000.toInt()), 0, 1, 0)+ val out = buildInlineHtml(s, 0, 1)+ assertTrue(out.startsWith("<span style=\"color:#FF0000\"><code"), out)+ assertTrue(out.endsWith("</code></span>"), out)+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlParaRendererTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlParaRendererTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlParaRendererTest.ktnew file mode 100644index 0000000000..0f501b1705--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlParaRendererTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.email.composer++import android.text.SpannableString+import android.text.style.BulletSpan+import com.vayunmathur.email.ui.composer.serializeEmailHtml+import com.vayunmathur.library.ui.EmailAlignmentSpan+import com.vayunmathur.library.ui.EmailBlockQuoteSpan+import com.vayunmathur.library.ui.HeadingSpan+import com.vayunmathur.library.ui.HrSpan+import com.vayunmathur.library.ui.IndentSpan+import com.vayunmathur.library.ui.OrderedListSpan+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/**+ * Paragraph-level branches of the email HTML serializer: what the+ * recipient's client opens depends on the right block wrapper, so lists+ * must group into one list element, headings/blockquotes must carry+ * their styles, and a following plain paragraph must close an open list.+ */+@RunWith(RobolectricTestRunner::class)+class EmailHtmlParaRendererTest {++ private fun spanned(text: String, vararg spans: Pair<Any, IntRange>): SpannableString {+ val s = SpannableString(text)+ for ((span, range) in spans) {+ s.setSpan(span, range.first, range.last + 1, 0)+ }+ return s+ }++ @Test+ fun `bullet paragraphs group into a single unordered list`() {+ val out = serializeEmailHtml(+ spanned("one\ntwo", BulletSpan() to (0..2), BulletSpan() to (4..6))+ )+ assertEquals("<ul><li>one</li><li>two</li></ul>", out)+ }++ @Test+ fun `ordered paragraphs group into a single ordered list`() {+ val out = serializeEmailHtml(+ spanned("one\ntwo", OrderedListSpan(1) to (0..2), OrderedListSpan(2) to (4..6))+ )+ assertEquals("<ol><li>one</li><li>two</li></ol>", out)+ }++ @Test+ fun `switching from bullets to ordered closes the first list`() {+ val out = serializeEmailHtml(+ spanned("one\ntwo", BulletSpan() to (0..2), OrderedListSpan(1) to (4..6))+ )+ assertEquals("<ul><li>one</li></ul><ol><li>two</li></ol>", out)+ }++ @Test+ fun `a plain paragraph after a list closes it`() {+ val out = serializeEmailHtml(+ spanned("one\nplain", BulletSpan() to (0..2))+ )+ assertEquals("<ul><li>one</li></ul><div>plain</div>", out)+ }++ @Test+ fun `heading paragraph renders the heading tag with margin`() {+ val out = serializeEmailHtml(spanned("Title", HeadingSpan(2) to (0..4)))+ assertEquals("<h2 style=\"margin:0.5em 0\">Title</h2>", out)+ }++ @Test+ fun `heading with alignment and indent carries all styles`() {+ val out = serializeEmailHtml(+ spanned(+ "Title",+ HeadingSpan(1) to (0..4),+ EmailAlignmentSpan("center") to (0..4),+ IndentSpan(2) to (0..4),+ )+ )+ assertTrue(out.contains("<h1"), out)+ assertTrue(out.contains("text-align:center"), out)+ assertTrue(out.contains("margin-left:48px"), out)+ }++ @Test+ fun `blockquote paragraph renders the quote block`() {+ val out = serializeEmailHtml(spanned("quoted", EmailBlockQuoteSpan() to (0..5)))+ assertTrue(out.startsWith("<blockquote"), out)+ assertTrue(out.contains("border-left:2px solid #ccc"), out)+ assertTrue(out.contains("quoted"), out)+ }++ @Test+ fun `centered paragraph renders a text-align div`() {+ val out = serializeEmailHtml(spanned("mid", EmailAlignmentSpan("center") to (0..2)))+ assertEquals("<div style=\"text-align:center\">mid</div>", out)+ }++ @Test+ fun `indented paragraph renders the margin div`() {+ val out = serializeEmailHtml(spanned("deep", IndentSpan(3) to (0..3)))+ assertEquals("<div style=\"margin-left:72px\">deep</div>", out)+ }++ @Test+ fun `empty paragraph renders a plain break`() {+ // The empty-para branch emits <br> before any block styling; an+ // indent span sitting on the newline itself is not picked up.+ val out = serializeEmailHtml(spanned("\n", IndentSpan(1) to (0..0)))+ assertEquals("<br>", out)+ }++ @Test+ fun `horizontal rule paragraph renders hr and closes lists`() {+ val out = serializeEmailHtml(+ spanned("one\nx", BulletSpan() to (0..2), HrSpan() to (4..4))+ )+ assertEquals("<ul><li>one</li></ul><hr>", out)+ }++ @Test+ fun `list item keeps a heading inside the item`() {+ val out = serializeEmailHtml(+ spanned("head", BulletSpan() to (0..3), HeadingSpan(3) to (0..3))+ )+ assertEquals("<ul><li><h3 style=\"margin:0;\">head</h3></li></ul>", out)+ }++ @Test+ fun `list item keeps a blockquote inside the item`() {+ val out = serializeEmailHtml(+ spanned("q", BulletSpan() to (0..0), EmailBlockQuoteSpan() to (0..0))+ )+ assertTrue(out.startsWith("<ul><li><blockquote"), out)+ assertTrue(out.contains(">q</blockquote></li></ul>"), out)+ }++ @Test+ fun `indented list item wraps the item content`() {+ val out = serializeEmailHtml(+ spanned("item", BulletSpan() to (0..3), IndentSpan(1) to (0..3))+ )+ assertEquals(+ "<ul><li><div style=\"margin-left: 24px\">item</div></li></ul>",+ out,+ )+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlSerializerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlSerializerTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlSerializerTest.ktnew file mode 100644index 0000000000..51aac3688d--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlSerializerTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.email.composer++import android.text.SpannableString+import android.text.style.ForegroundColorSpan+import android.text.style.StrikethroughSpan+import android.text.style.StyleSpan+import android.text.style.UnderlineSpan+import android.graphics.Typeface+import com.vayunmathur.email.ui.composer.buildInlineHtml+import com.vayunmathur.email.ui.composer.colorToHex+import com.vayunmathur.email.ui.composer.escapeAttr+import com.vayunmathur.email.ui.composer.findNextSpanBoundary+import com.vayunmathur.email.ui.composer.serializeEmailHtml+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Pins the composer HTML serializer against fixed spans.+ *+ * What the composer emits here is what recipients open, so each test+ * asserts the exact output shape: escaped text, nested inline tags, block+ * wrappers, and the empty-input placeholder.+ *+ * SpannableString needs the Android framework, so these run under Robolectric.+ */+@RunWith(RobolectricTestRunner::class)+class EmailHtmlSerializerTest {++ @Test+ fun `empty input yields empty string`() {+ assertEquals("", serializeEmailHtml(SpannableString("")))+ }++ @Test+ fun `single empty paragraph renders a line break`() {+ // One empty para hits the empty-para branch ("<br>"); the+ // "<div><br></div>" fallback only applies when the whole render is blank.+ assertEquals("<br>", serializeEmailHtml(SpannableString("\n")))+ assertEquals("<div><br></div>", serializeEmailHtml(SpannableString(" ")))+ }++ @Test+ fun `plain text is wrapped in a div and html escaped`() {+ val out = serializeEmailHtml(SpannableString("a<b>&c"))+ assertTrue(out.contains("a<b>&c"), out)+ assertTrue(out.startsWith("<div"), out)+ }++ @Test+ fun `bold and italic nest inside the same block`() {+ val text = SpannableString("hello")+ text.setSpan(StyleSpan(Typeface.BOLD), 0, 5, 0)+ text.setSpan(StyleSpan(Typeface.ITALIC), 0, 5, 0)+ val out = serializeEmailHtml(text)+ assertTrue(out.contains("<b>"), out)+ assertTrue(out.contains("<i>"), out)+ assertTrue(out.contains("hello"), out)+ }++ @Test+ fun `underline and strike render`() {+ val text = SpannableString("xy")+ text.setSpan(UnderlineSpan(), 0, 1, 0)+ text.setSpan(StrikethroughSpan(), 1, 2, 0)+ val out = buildInlineHtml(text, 0, 2)+ assertTrue(out.contains("<u>x</u>"), out)+ assertTrue(out.contains("<s>y</s>"), out)+ }++ @Test+ fun `foreground color emits hex span`() {+ val text = SpannableString("red")+ text.setSpan(ForegroundColorSpan(0xFFFF0000.toInt()), 0, 3, 0)+ val out = buildInlineHtml(text, 0, 3)+ assertTrue(out.contains("color:#FF0000"), out)+ }++ @Test+ fun `color helper strips alpha`() {+ assertEquals("#00FF00", colorToHex(0xFF00FF00.toInt()))+ assertEquals("#0000FF", colorToHex(0x800000FF.toInt()))+ }++ @Test+ fun `attribute escaping covers quotes and brackets`() {+ assertEquals("a&b"<c>", escapeAttr("a&b\"<c>"))+ }++ @Test+ fun `span boundary finder stops at span edges`() {+ val text = SpannableString("abcdef")+ text.setSpan(StyleSpan(Typeface.BOLD), 2, 4, 0)+ assertEquals(2, findNextSpanBoundary(text, 0, 6))+ assertEquals(4, findNextSpanBoundary(text, 2, 6))+ assertEquals(6, findNextSpanBoundary(text, 4, 6))+ }+}
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlTagHandlerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlTagHandlerTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlTagHandlerTest.ktnew file mode 100644index 0000000000..fb449c3bd1--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlTagHandlerTest.kt@@ -0,0 +1,251 @@+package com.vayunmathur.email.composer++import android.text.SpannableStringBuilder+import com.vayunmathur.email.ui.composer.EmailHtmlTagHandler+import com.vayunmathur.library.ui.EmailBlockQuoteSpan+import com.vayunmathur.library.ui.HeadingSpan+import com.vayunmathur.library.ui.HrSpan+import com.vayunmathur.library.ui.InlineCodeSpan+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.xml.sax.Attributes+import org.xml.sax.ContentHandler+import org.xml.sax.DTDHandler+import org.xml.sax.EntityResolver+import org.xml.sax.ErrorHandler+import org.xml.sax.InputSource+import org.xml.sax.XMLReader+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Drives [EmailHtmlTagHandler] directly: when a draft is re-opened its rich+ * spans (headings, quotes, code, rules) must survive the HTML round-trip. A+ * dropped span silently flattens the draft's formatting, so each test asserts+ * the exact span restored over the exact range.+ *+ * The style-attribute path needs a real SAX parser; these tests pin the+ * tag-only path (headings/blockquote/code/hr), which is what survives on all+ * Android versions.+ */+@RunWith(RobolectricTestRunner::class)+class EmailHtmlTagHandlerTest {++ /** Minimal XMLReader: attribute extraction is best-effort and returns null. */+ private class StubReader : XMLReader {+ override fun getProperty(name: String): Any = throw org.xml.sax.SAXNotRecognizedException(name)+ override fun setProperty(name: String, value: Any) {}+ override fun setEntityResolver(resolver: EntityResolver?) {}+ override fun getEntityResolver(): EntityResolver? = null+ override fun setDTDHandler(handler: DTDHandler?) {}+ override fun getDTDHandler(): DTDHandler? = null+ override fun setContentHandler(handler: ContentHandler?) {}+ override fun getContentHandler(): ContentHandler? = null+ override fun setErrorHandler(handler: ErrorHandler?) {}+ override fun getErrorHandler(): ErrorHandler? = null+ override fun parse(input: InputSource?) {}+ override fun parse(systemId: String?) {}+ override fun getFeature(name: String): Boolean = false+ override fun setFeature(name: String, value: Boolean) {}+ }++ private val reader = StubReader()++ private fun spanned(block: EmailHtmlTagHandler.(SpannableStringBuilder) -> Unit): SpannableStringBuilder {+ val handler = EmailHtmlTagHandler()+ val out = SpannableStringBuilder()+ handler.block(out)+ return out+ }++ @Test+ fun `h1 close restores a level-1 heading span`() {+ val out = spanned {+ it.append("Title")+ handleTag(true, "h1", it, reader)+ it.append("Title")+ handleTag(false, "h1", it, reader)+ }+ val spans = out.getSpans(0, out.length, HeadingSpan::class.java)+ assertEquals(1, spans.size)+ assertEquals(1, spans.single().level)+ }++ @Test+ fun `h2 and h3 restore their levels`() {+ val out = spanned {+ handleTag(true, "h2", it, reader)+ it.append("sub")+ handleTag(false, "h2", it, reader)+ handleTag(true, "h3", it, reader)+ it.append("sub3")+ handleTag(false, "h3", it, reader)+ }+ val levels = out.getSpans(0, out.length, HeadingSpan::class.java).map { it.level }.sorted()+ assertEquals(listOf(2, 3), levels)+ }++ @Test+ fun `blockquote close restores the quote span`() {+ val out = spanned {+ handleTag(true, "blockquote", it, reader)+ it.append("quoted words")+ handleTag(false, "blockquote", it, reader)+ }+ val spans = out.getSpans(0, out.length, EmailBlockQuoteSpan::class.java)+ assertEquals(1, spans.size)+ assertEquals(0, out.getSpanStart(spans.single()))+ assertEquals(out.length, out.getSpanEnd(spans.single()))+ }++ @Test+ fun `code close restores the inline code span`() {+ val out = spanned {+ it.append("run ")+ handleTag(true, "code", it, reader)+ it.append("x()")+ handleTag(false, "code", it, reader)+ }+ val spans = out.getSpans(0, out.length, InlineCodeSpan::class.java)+ assertEquals(1, spans.size)+ assertEquals(4, out.getSpanStart(spans.single()))+ }++ @Test+ fun `hr open inserts an object replacement tagged with HrSpan`() {+ val out = spanned {+ it.append("before")+ handleTag(true, "hr", it, reader)+ }+ assertTrue(out.contains("\uFFFC"), out.toString())+ val spans = out.getSpans(0, out.length, HrSpan::class.java)+ assertEquals(1, spans.size)+ }++ @Test+ fun `unmatched close tags are ignored`() {+ val out = spanned {+ it.append("text")+ handleTag(false, "h1", it, reader)+ handleTag(false, "blockquote", it, reader)+ handleTag(false, "code", it, reader)+ }+ assertEquals("text", out.toString())+ assertTrue(out.getSpans(0, out.length, HeadingSpan::class.java).isEmpty())+ }++ @Test+ fun `tag names are case-insensitive`() {+ val out = spanned {+ handleTag(true, "H1", it, reader)+ it.append("Title")+ handleTag(false, "H1", it, reader)+ }+ assertEquals(1, out.getSpans(0, out.length, HeadingSpan::class.java).size)+ }++ /** Reader whose property lookup yields attributes carrying [style]. */+ private class StyledReader(private val style: String) : XMLReader {+ private val attrs = object : Attributes {+ override fun getLength(): Int = 1+ override fun getURI(index: Int): String = ""+ override fun getLocalName(index: Int): String = "style"+ override fun getQName(index: Int): String = "style"+ override fun getType(index: Int): String = "CDATA"+ override fun getValue(index: Int): String = style+ override fun getIndex(uri: String, localName: String): Int = if (localName == "style") 0 else -1+ override fun getIndex(qName: String): Int = if (qName == "style") 0 else -1+ override fun getType(uri: String, localName: String): String? = null+ override fun getType(qName: String): String? = null+ override fun getValue(uri: String, localName: String): String? = null+ override fun getValue(qName: String): String? = if (qName == "style") style else null+ }++ override fun getProperty(name: String): Any = attrs+ override fun setProperty(name: String, value: Any) {}+ override fun setEntityResolver(resolver: EntityResolver?) {}+ override fun getEntityResolver(): EntityResolver? = null+ override fun setDTDHandler(handler: DTDHandler?) {}+ override fun getDTDHandler(): DTDHandler? = null+ override fun setContentHandler(handler: ContentHandler?) {}+ override fun getContentHandler(): ContentHandler? = null+ override fun setErrorHandler(handler: ErrorHandler?) {}+ override fun getErrorHandler(): ErrorHandler? = null+ override fun parse(input: InputSource?) {}+ override fun parse(systemId: String?) {}+ override fun getFeature(name: String): Boolean = false+ override fun setFeature(name: String, value: Boolean) {}+ }++ private fun styled(style: String, block: EmailHtmlTagHandler.(SpannableStringBuilder) -> Unit): SpannableStringBuilder {+ val handler = EmailHtmlTagHandler()+ val out = SpannableStringBuilder()+ handler.block(out)+ return out+ }++ @Test+ fun `span color and background restore color spans`() {+ val styleReader = StyledReader("color:#FF0000; background-color:#00FF00")+ val out = styled("color:#FF0000; background-color:#00FF00") {+ handleTag(true, "span", it, styleReader)+ it.append("colored")+ handleTag(false, "span", it, styleReader)+ }+ val fg = out.getSpans(0, out.length, android.text.style.ForegroundColorSpan::class.java)+ val bg = out.getSpans(0, out.length, android.text.style.BackgroundColorSpan::class.java)+ assertEquals(1, fg.size)+ assertEquals(android.graphics.Color.rgb(255, 0, 0), fg.single().foregroundColor)+ assertEquals(1, bg.size)+ assertEquals(android.graphics.Color.rgb(0, 255, 0), bg.single().backgroundColor)+ }++ @Test+ fun `span font size and family restore spans, rgb color parses`() {+ val styleReader = StyledReader("font-size:1.5em; font-family:'serif'; color:rgb(1,2,3)")+ val out = styled("font-size:1.5em; font-family:'serif'; color:rgb(1,2,3)") {+ handleTag(true, "span", it, styleReader)+ it.append("sized")+ handleTag(false, "span", it, styleReader)+ }+ val sizes = out.getSpans(0, out.length, android.text.style.RelativeSizeSpan::class.java)+ assertEquals(1, sizes.size)+ assertEquals(1.5f, sizes.single().sizeChange)+ val families = out.getSpans(0, out.length, com.vayunmathur.library.ui.FontFamilySpan::class.java)+ assertEquals(1, families.size)+ assertEquals("serif", families.single().familyName)+ val fg = out.getSpans(0, out.length, android.text.style.ForegroundColorSpan::class.java)+ assertEquals(android.graphics.Color.rgb(1, 2, 3), fg.single().foregroundColor)+ }++ @Test+ fun `div text align restores alignment span and invalid align does not`() {+ val centerReader = StyledReader("text-align:center")+ val out = styled("text-align:center") {+ handleTag(true, "div", it, centerReader)+ it.append("centered")+ handleTag(false, "div", it, centerReader)+ }+ val aligns = out.getSpans(0, out.length, com.vayunmathur.library.ui.EmailAlignmentSpan::class.java)+ assertEquals(1, aligns.size)+ assertEquals("center", aligns.single().cssAlign)++ val bogusReader = StyledReader("text-align:sideways")+ val out2 = styled("text-align:sideways") {+ handleTag(true, "div", it, bogusReader)+ it.append("plain")+ handleTag(false, "div", it, bogusReader)+ }+ assertTrue(out2.getSpans(0, out2.length, com.vayunmathur.library.ui.EmailAlignmentSpan::class.java).isEmpty())+ }++ @Test+ fun `empty range close applies no span`() {+ val out = spanned {+ handleTag(true, "code", it, reader)+ handleTag(false, "code", it, reader)+ }+ assertTrue(out.getSpans(0, out.length, InlineCodeSpan::class.java).isEmpty())+ }+}
email/src/test/java/com/vayunmathur/email/data/BackfillTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/BackfillTest.kt b/email/src/test/java/com/vayunmathur/email/data/BackfillTest.ktnew file mode 100644index 0000000000..10d02215b3--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/BackfillTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.email.data++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Drives the real [DateMillisBackfill] and [PeekContentBackfill] against an+ * in-memory database: both are one-shot migrations that must terminate (an+ * unparseable row re-queued forever would spin on every app start) and must+ * land the right values, since sorting and list snippets read these columns.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class BackfillTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private val scope = CoroutineScope(Dispatchers.Unconfined)++ private fun msg(uid: Long, date: String, body: String?, dateMillis: Long = 0, peek: String = "") =+ EmailMessage(+ accountEmail = "[email protected]", folderName = "INBOX", id = uid,+ subject = "s", from = "f", date = date,+ dateMillis = dateMillis, body = body, peekContent = peek,+ )++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ private fun waitFor(message: String, timeoutMs: Long = 10_000, cond: suspend () -> Boolean) {+ val start = System.currentTimeMillis()+ runBlocking {+ while (!cond()) {+ if (System.currentTimeMillis() - start > timeoutMs) {+ throw AssertionError(message)+ }+ Thread.sleep(25)+ }+ }+ }++ @Test+ fun `date backfill parses java Date strings into millis`() {+ runBlocking {+ db.messageDao().insertMessagesRaw(+ listOf(msg(1L, "Wed Nov 27 14:30:00 PST 2024", "b"))+ )+ }+ DateMillisBackfill.runIfNeeded(scope, context)+ waitFor("dateMillis was not backfilled") {+ db.messageDao().getMessage("[email protected]", "INBOX", 1L)?.dateMillis.let { (it ?: 0L) > 0L }+ }+ val row = runBlocking { db.messageDao().getMessage("[email protected]", "INBOX", 1L) }+ // Nov 27 2024 14:30 PST = 22:30 UTC โ epoch 1732746600.+ assertTrue(row!!.dateMillis > 1_700_000_000_000L, "millis: ${row.dateMillis}")+ }++ @Test+ fun `date backfill marks unparseable rows done without looping`() {+ runBlocking {+ db.messageDao().insertMessagesRaw(+ listOf(msg(2L, "not a date at all", "b"))+ )+ }+ DateMillisBackfill.runIfNeeded(scope, context)+ waitFor("unparseable row was not marked done") {+ db.messageDao().getMessage("[email protected]", "INBOX", 2L)?.dateMillis.let { (it ?: 0L) != 0L }+ }+ val row = runBlocking { db.messageDao().getMessage("[email protected]", "INBOX", 2L) }+ assertEquals(1L, row!!.dateMillis)+ assertTrue(runBlocking { db.queryDao().getRowsWithZeroDateMillis() }.isEmpty())+ }++ @Test+ fun `peek backfill derives the snippet from the body`() {+ runBlocking {+ db.messageDao().insertMessagesRaw(+ listOf(msg(3L, "Wed Nov 27 14:30:00 PST 2024", "hello world"))+ )+ }+ PeekContentBackfill.runIfNeeded(scope, context)+ waitFor("peek was not backfilled") {+ db.messageDao().getMessage("[email protected]", "INBOX", 3L)?.peekContent?.isNotEmpty() == true+ }+ val row = runBlocking { db.messageDao().getMessage("[email protected]", "INBOX", 3L) }+ assertEquals("hello world", row!!.peekContent)+ }++ @Test+ fun `peek backfill blanks become a single space so rows finish`() {+ runBlocking {+ db.messageDao().insertMessagesRaw(+ listOf(msg(4L, "Wed Nov 27 14:30:00 PST 2024", " "))+ )+ }+ PeekContentBackfill.runIfNeeded(scope, context)+ waitFor("blank peek row was not marked done") {+ val peek = db.messageDao().getMessage("[email protected]", "INBOX", 4L)?.peekContent+ peek != null && peek.isNotEmpty()+ }+ assertTrue(runBlocking { db.queryDao().getRowsWithEmptyPeek() }.isEmpty())+ }+}
email/src/test/java/com/vayunmathur/email/data/CredentialCryptoTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/CredentialCryptoTest.kt b/email/src/test/java/com/vayunmathur/email/data/CredentialCryptoTest.ktnew file mode 100644index 0000000000..72f92476c1--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/CredentialCryptoTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.email.data++import com.vayunmathur.email.FakeAndroidKeyStore+import javax.crypto.AEADBadTagException+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [CredentialCrypto] against an in-memory AndroidKeyStore: the account+ * password must round-trip byte-for-byte, each encryption must use a+ * fresh IV (so two encryptions of one password differ), and tampered+ * ciphertext must fail GCM authentication instead of decrypting to+ * garbage a login would silently send.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class CredentialCryptoTest {++ @BeforeTest+ fun installKeyStore() {+ FakeAndroidKeyStore.install()+ FakeAndroidKeyStore.clear()+ }++ @Test+ fun `encrypt decrypt round-trips plain and unicode passwords`() {+ val (cipher, iv) = CredentialCrypto.encrypt("s3cret-app-password")+ assertFalse(cipher.contentEquals("s3cret-app-password".toByteArray()))+ assertEquals("s3cret-app-password", CredentialCrypto.decrypt(cipher, iv))+ val (c2, iv2) = CredentialCrypto.encrypt("pรขsswรถrd-๐")+ assertEquals("pรขsswรถrd-๐", CredentialCrypto.decrypt(c2, iv2))+ }++ @Test+ fun `empty password round-trips`() {+ val (cipher, iv) = CredentialCrypto.encrypt("")+ assertEquals("", CredentialCrypto.decrypt(cipher, iv))+ }++ @Test+ fun `each encryption uses a fresh iv so ciphertexts differ`() {+ val (c1, iv1) = CredentialCrypto.encrypt("same-password")+ val (c2, iv2) = CredentialCrypto.encrypt("same-password")+ assertFalse(iv1.contentEquals(iv2))+ assertFalse(c1.contentEquals(c2))+ assertTrue(iv1.size == 12)+ // Both still decrypt to the original under their own IV.+ assertEquals("same-password", CredentialCrypto.decrypt(c1, iv1))+ assertEquals("same-password", CredentialCrypto.decrypt(c2, iv2))+ }++ @Test+ fun `tampered ciphertext fails authentication`() {+ val (cipher, iv) = CredentialCrypto.encrypt("s3cret")+ val tampered = cipher.copyOf().also { it[0] = (it[0] + 1).toByte() }+ assertFailsWith<AEADBadTagException> { CredentialCrypto.decrypt(tampered, iv) }+ }++ @Test+ fun `wrong iv fails authentication`() {+ val (cipher, _) = CredentialCrypto.encrypt("s3cret")+ val wrongIv = ByteArray(12) { 0x2A }+ assertFailsWith<Exception> { CredentialCrypto.decrypt(cipher, wrongIv) }+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailDatabaseTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailDatabaseTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailDatabaseTest.ktnew file mode 100644index 0000000000..0cbf8c74ff--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailDatabaseTest.kt@@ -0,0 +1,436 @@+package com.vayunmathur.email.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the email Room DAOs (and the thin store wrappers around them) against+ * an in-memory database.+ *+ * These queries encode real product behavior โ snoozed mail hiding until it+ * resurfaces, tombstones stopping deleted mail from syncing back, list+ * previews reading the stored snippet instead of the full body โ so each+ * test asserts the persisted rows, not just that the call succeeded.+ */+@RunWith(AndroidJUnit4::class)+class EmailDatabaseTest {++ private lateinit var db: EmailDatabase++ private fun message(+ uid: Long,+ subject: String = "subject",+ from: String = "[email protected]",+ body: String? = "body text",+ dateMillis: Long = 1000L + uid,+ folder: String = "INBOX",+ account: String = "[email protected]",+ snoozedUntil: Long = 0L,+ isRead: Boolean = false,+ ) = EmailMessage(+ accountEmail = account,+ folderName = folder,+ id = uid,+ subject = subject,+ from = from,+ date = "Wed, 17 Jul 2024 12:00:00 +0000",+ dateMillis = dateMillis,+ body = body,+ snoozedUntil = snoozedUntil,+ isRead = isRead,+ )++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(+ ApplicationProvider.getApplicationContext(),+ EmailDatabase::class.java,+ ).allowMainThreadQueries().build()+ }++ @AfterTest+ fun close() {+ db.close()+ }++ /**+ * A Room Flow collection started right after a write can still deliver+ * the pre-write snapshot as its first emission (the invalidation+ * re-query races the initial query on Room's query executor), so a+ * single `first()` after a delete is flaky under load. Re-collect until+ * the flow reflects the write, then return that emission for asserting.+ */+ private suspend fun <T> Flow<List<T>>.awaitList(predicate: (List<T>) -> Boolean): List<T> {+ repeat(600) {+ val value = first()+ if (predicate(value)) return value+ Thread.sleep(10)+ }+ return first()+ }++ // ---------- accounts / folders / blocked senders ----------++ @Test+ fun accounts_insertGetUpdateSignatureAndDelete() = runTest {+ val dao = db.accountDao()+ assertNull(dao.getAccountByEmail("[email protected]"))+ dao.insertAccount(EmailAccount(email = "[email protected]"))+ assertEquals("[email protected]", dao.getAccountByEmail("[email protected]")!!.email)+ assertEquals(1, dao.getAccounts().size)+ assertEquals(1, dao.getAccountsFlow().first().size)+ dao.setSignature("[email protected]", "Sent from my phone")+ assertEquals("Sent from my phone", dao.getAccountByEmail("[email protected]")!!.signature)+ dao.deleteAccount(EmailAccount(email = "[email protected]"))+ assertNull(dao.getAccountByEmail("[email protected]"))+ assertEquals(emptyList(), dao.getAccountsFlow().awaitList { it.isEmpty() })+ }++ @Test+ fun folders_insertClearAndFlow() = runTest {+ val dao = db.accountDao()+ dao.insertFolders(+ listOf(+ EmailFolder("[email protected]", "INBOX", "INBOX"),+ EmailFolder("[email protected]", "INBOX/Work", "Work", parentFullName = "INBOX"),+ )+ )+ val folders = dao.getFoldersFlow("[email protected]").first()+ assertEquals(2, folders.size)+ assertTrue(folders.any { it.fullName == "INBOX/Work" && it.parentFullName == "INBOX" })+ assertEquals(emptyList(), dao.getFoldersFlow("[email protected]").first())+ dao.clearFolders("[email protected]")+ assertEquals(emptyList(), dao.getFoldersFlow("[email protected]").awaitList { it.isEmpty() })+ }++ @Test+ fun blockedSenders_insertDeleteAndFlow() = runTest {+ val dao = db.accountDao()+ dao.insertBlockedSender(BlockedSender("[email protected]"))+ dao.insertBlockedSender(BlockedSender("[email protected]"))+ assertEquals(+ listOf("[email protected]", "[email protected]"),+ dao.getBlockedSendersFlow().first().map { it.address },+ )+ dao.deleteBlockedSender("[email protected]")+ assertEquals(+ listOf("[email protected]"),+ dao.getBlockedSendersFlow().awaitList { it.size == 1 }.map { it.address },+ )+ }++ @Test+ fun accountStore_delegatesToAccountDao() = runTest {+ val store = EmailAccountStore(db)+ store.insertAccount(EmailAccount(email = "[email protected]"))+ assertEquals(1, store.getAccounts().size)+ assertEquals(1, store.getAccountsFlow().first().size)+ assertEquals("[email protected]", store.getAccountByEmail("[email protected]")!!.email)+ store.setSignature("[email protected]", "sig")+ assertEquals("sig", store.getAccountByEmail("[email protected]")!!.signature)+ store.insertBlockedSender(BlockedSender("[email protected]"))+ assertEquals(1, store.getBlockedSendersFlow().first().size)+ store.deleteBlockedSender("[email protected]")+ assertEquals(emptyList(), store.getBlockedSendersFlow().awaitList { it.isEmpty() })+ store.insertFolders(listOf(EmailFolder("[email protected]", "INBOX", "INBOX")))+ assertEquals(1, store.getFoldersFlow("[email protected]").first().size)+ store.clearFolders("[email protected]")+ assertEquals(emptyList(), store.getFoldersFlow("[email protected]").awaitList { it.isEmpty() })+ store.deleteAccount(EmailAccount(email = "[email protected]"))+ assertNull(store.getAccountByEmail("[email protected]"))+ }++ // ---------- messages ----------++ @Test+ fun insertMessages_computesPeekSnippetFromBody() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L, body = "<p>Hello world</p>")))+ val back = dao.getMessage("[email protected]", "INBOX", 1L)!!+ assertTrue(back.peekContent.contains("Hello world"), back.peekContent)+ assertNull(dao.getMessage("[email protected]", "INBOX", 999L))+ }++ @Test+ fun messagesFlow_hidesSnoozedUntilDue() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(+ listOf(+ message(1L, snoozedUntil = 0L),+ message(2L, snoozedUntil = 9_999_999_999_999L),+ )+ )+ val visible = dao.getMessagesFlow("[email protected]", "INBOX", now = 1000L).first()+ assertEquals(listOf(1L), visible.map { it.id })+ }++ @Test+ fun deleteWithTombstone_recordsUidAndRemovesRow() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L), message(2L)))+ assertEquals(listOf(1L, 2L), dao.getKnownUids("[email protected]", "INBOX").sorted())+ dao.deleteMessageRow("[email protected]", "INBOX", 1L, tombstone = true)+ assertNull(dao.getMessage("[email protected]", "INBOX", 1L))+ assertEquals(listOf(1L), dao.getDeletedUids("[email protected]", "INBOX"))+ dao.deleteMessageRow("[email protected]", "INBOX", 2L, tombstone = false)+ assertEquals(listOf(1L), dao.getDeletedUids("[email protected]", "INBOX"))+ // Plain overload removes the row without touching tombstones.+ dao.insertMessages(listOf(message(3L)))+ dao.deleteMessageRow("[email protected]", "INBOX", 3L)+ assertNull(dao.getMessage("[email protected]", "INBOX", 3L))+ assertEquals(listOf(1L), dao.getDeletedUids("[email protected]", "INBOX"))+ }++ @Test+ fun messagesWithoutBody_returnsOnlyHeaderOnlyRowsNewestFirst() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L, body = null), message(2L, body = "has body"), message(3L, body = null)))+ assertEquals(listOf(3L, 1L), dao.getMessagesWithoutBody("[email protected]", 10).map { it.id })+ assertEquals(listOf(3L), dao.getMessagesWithoutBody("[email protected]", 1).map { it.id })+ }++ @Test+ fun clearMessages_removesOnlyThatAccount() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L, account = "[email protected]"), message(2L, account = "[email protected]")))+ dao.clearMessages("[email protected]")+ assertNull(dao.getMessage("[email protected]", "INBOX", 1L))+ assertEquals(2L, dao.getMessage("[email protected]", "INBOX", 2L)!!.id)+ }++ @Test+ fun snoozeAndWake_resurfacesDueMailAsUnread() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L, isRead = true)))+ dao.setSnooze("[email protected]", "INBOX", 1L, 5000L)+ assertEquals(5000L, dao.getMessage("[email protected]", "INBOX", 1L)!!.snoozedUntil)+ assertEquals(0, dao.wakeDueSnoozed(now = 4999L))+ assertEquals(1, dao.wakeDueSnoozed(now = 5000L))+ val back = dao.getMessage("[email protected]", "INBOX", 1L)!!+ assertEquals(0L, back.snoozedUntil)+ assertEquals(false, back.isRead)+ }++ @Test+ fun readStatus_singleAndBulk() = runTest {+ val dao = db.messageDao()+ dao.insertMessages(listOf(message(1L), message(2L), message(3L)))+ dao.updateReadStatus("[email protected]", "INBOX", 1L, true)+ assertEquals(true, dao.getMessage("[email protected]", "INBOX", 1L)!!.isRead)+ dao.updateBulkReadStatus("[email protected]", listOf(2L, 3L), true)+ assertEquals(true, dao.getMessage("[email protected]", "INBOX", 2L)!!.isRead)+ assertEquals(true, dao.getMessage("[email protected]", "INBOX", 3L)!!.isRead)+ }++ @Test+ fun attachments_insertGetAndMarkDownloaded() = runTest {+ val dao = db.messageDao()+ val att = Attachment("[email protected]", "INBOX", 7L, "0", "a.pdf", "application/pdf", 100L)+ dao.insertAttachments(listOf(att))+ assertEquals(listOf("a.pdf"), dao.getAttachments("[email protected]", 7L).map { it.fileName })+ assertEquals(emptyList(), dao.getAttachments("[email protected]", 8L))+ dao.updateAttachmentLocalUri("[email protected]", 7L, "0", "file:///cache/a.pdf")+ assertEquals("file:///cache/a.pdf", dao.getAttachments("[email protected]", 7L).single().localUri)+ }++ @Test+ fun threadFlow_returnsThreadOldestFirst() = runTest {+ val dao = db.messageDao()+ val a = message(1L, dateMillis = 100L).copy(threadId = "t1")+ val b = message(2L, dateMillis = 200L).copy(threadId = "t1")+ val other = message(3L, dateMillis = 50L).copy(threadId = "t2")+ dao.insertMessages(listOf(b, other, a))+ assertEquals(listOf(1L, 2L), dao.getThreadFlow("[email protected]", "t1").first().map { it.id })+ }++ @Test+ fun messageStore_delegatesToMessageDao() = runTest {+ val store = EmailMessageStore(db)+ store.insertMessages(listOf(message(1L, body = "hello snippet")))+ assertEquals("hello snippet", store.getMessage("[email protected]", "INBOX", 1L)!!.peekContent)+ assertEquals(listOf(1L), store.getMessagesFlow("[email protected]", "INBOX", 0L).first().map { it.id })+ // Thread flow for an unknown thread is empty; insert a threaded row and re-check.+ assertEquals(emptyList(), store.getThreadFlow("[email protected]", "t9").first())+ store.insertMessages(listOf(message(2L).copy(threadId = "t9")))+ assertEquals(listOf(2L), store.getThreadFlow("[email protected]", "t9").first().map { it.id })+ store.updateReadStatus("[email protected]", "INBOX", 1L, true)+ assertEquals(true, store.getMessage("[email protected]", "INBOX", 1L)!!.isRead)+ store.updateBulkReadStatus("[email protected]", listOf(1L), false)+ assertEquals(false, store.getMessage("[email protected]", "INBOX", 1L)!!.isRead)+ store.setSnooze("[email protected]", "INBOX", 1L, 9000L)+ assertEquals(9000L, store.getMessage("[email protected]", "INBOX", 1L)!!.snoozedUntil)+ assertEquals(1, store.wakeDueSnoozed(9000L))+ // Both rows 1 and 2 are still present (row 2 was added for the thread check).+ assertEquals(listOf(1L, 2L), store.getKnownUids("[email protected]", "INBOX").sorted())+ store.insertDeletedUid(DeletedUid("[email protected]", "INBOX", 5L))+ assertEquals(listOf(5L), store.getDeletedUids("[email protected]", "INBOX"))+ store.insertAttachments(+ listOf(Attachment("[email protected]", "INBOX", 1L, "p1", "f.txt", "text/plain", 3L))+ )+ assertEquals(1, store.getAttachments("[email protected]", 1L).size)+ store.updateAttachmentLocalUri("[email protected]", 1L, "p1", "uri")+ assertEquals("uri", store.getAttachments("[email protected]", 1L).single().localUri)+ assertEquals(emptyList(), store.getMessagesWithoutBody("[email protected]", 5))+ store.deleteMessageRow("[email protected]", "INBOX", 1L)+ assertNull(store.getMessage("[email protected]", "INBOX", 1L))+ store.insertMessages(listOf(message(9L)))+ store.deleteMessageRow("[email protected]", "INBOX", 9L, tombstone = true)+ assertEquals(listOf(5L, 9L), store.getDeletedUids("[email protected]", "INBOX").sorted())+ store.clearMessages("[email protected]")+ assertEquals(emptyList(), store.getKnownUids("[email protected]", "INBOX"))+ }++ // ---------- search / unified / previews / backfills ----------++ @Test+ fun searchAndUnified_matchSubjectSenderAndBody() = runTest {+ val dao = db.queryDao()+ db.messageDao().insertMessagesRaw(+ listOf(+ message(1L, subject = "Quarterly report", from = "[email protected]", body = "numbers"),+ message(2L, subject = "Hello", from = "[email protected]", body = "dinner plans"),+ )+ )+ assertEquals(listOf(1L), dao.searchMessages("quarterly").map { it.id })+ assertEquals(listOf(2L), dao.searchMessages("FRIEND").map { it.id })+ assertEquals(listOf(2L), dao.searchMessages("dinner").map { it.id })+ assertEquals(emptyList(), dao.searchMessages("zzz-no-match"))+ assertEquals(+ listOf(1L),+ dao.searchMessagesFlow("[email protected]", "INBOX", "report", 0L).first().map { it.id },+ )+ assertEquals(+ listOf(1L, 2L),+ dao.getUnifiedMessagesFlow("INBOX", 0L).first().map { it.id }.sorted(),+ )+ assertEquals(+ listOf(2L),+ dao.searchUnifiedMessagesFlow("INBOX", "dinner", 0L).first().map { it.id },+ )+ }++ @Test+ fun recentInbox_capsAtThirtyNewestFirst() = runTest {+ val dao = db.queryDao()+ db.messageDao().insertMessagesRaw((1L..35L).map { message(it, dateMillis = it) })+ val recent = dao.getRecentInboxMessages()+ assertEquals(30, recent.size)+ assertEquals(35L, recent.first().id)+ assertEquals(6L, recent.last().id)+ // The unified variants cap wider (100 rows / 10 for the flow).+ assertEquals(35, dao.getRecentUnifiedMessages().size)+ assertEquals(10, dao.getRecentUnifiedMessagesFlow().first().size)+ }++ @Test+ fun previewFlows_carryStoredSnippetWithoutBody() = runTest {+ val dao = db.queryDao()+ db.messageDao().insertMessages(listOf(message(1L, body = "preview me please")))+ val previews = dao.getMessagesPreviewFlow("[email protected]", "INBOX", 0L).first()+ assertEquals(1, previews.size)+ assertEquals("preview me please", previews.single().peekContent)+ assertEquals(+ 1,+ dao.searchMessagesPreviewFlow("[email protected]", "INBOX", "preview", 0L).first().size,+ )+ assertEquals(+ 1,+ dao.getUnifiedMessagesPreviewFlow("INBOX", 0L).first().size,+ )+ assertEquals(+ 1,+ dao.searchUnifiedMessagesPreviewFlow("INBOX", "preview", 0L).first().size,+ )+ assertEquals(1, dao.getRecentUnifiedPreview().size)+ }++ @Test+ fun dateMillisBackfill_findsZeroRowsAndUpdates() = runTest {+ val dao = db.queryDao()+ db.messageDao().insertMessagesRaw(listOf(message(1L).copy(dateMillis = 0L), message(2L).copy(dateMillis = 5L)))+ assertEquals(listOf(1L), dao.getRowsWithZeroDateMillis().map { it.id })+ dao.updateDateMillis("[email protected]", "INBOX", 1L, 12345L)+ assertEquals(emptyList(), dao.getRowsWithZeroDateMillis())+ assertEquals(12345L, db.messageDao().getMessage("[email protected]", "INBOX", 1L)!!.dateMillis)+ }++ @Test+ fun peekBackfill_findsEmptyPeekRowsAndUpdates() = runTest {+ val dao = db.queryDao()+ // Raw insert skips snippet computation, so the row is backfill-eligible.+ db.messageDao().insertMessagesRaw(listOf(message(1L, body = "needs peek").copy(peekContent = "")))+ assertEquals(listOf(1L), dao.getRowsWithEmptyPeek().map { it.id })+ dao.updatePeekContent("[email protected]", "INBOX", 1L, "needs peek")+ assertEquals(emptyList(), dao.getRowsWithEmptyPeek())+ assertEquals("needs peek", db.messageDao().getMessage("[email protected]", "INBOX", 1L)!!.peekContent)+ }++ @Test+ fun queryStore_delegatesToQueryDao() = runTest {+ val store = EmailQueryStore(db)+ db.messageDao().insertMessages(listOf(message(1L, body = "delegated body")))+ assertEquals(1, store.searchMessages("delegated").size)+ assertEquals(1, store.searchMessagesFlow("[email protected]", "INBOX", "delegated", 0L).first().size)+ assertEquals(1, store.getUnifiedMessagesFlow("INBOX", 0L).first().size)+ assertEquals(1, store.searchUnifiedMessagesFlow("INBOX", "delegated", 0L).first().size)+ assertEquals(1, store.getRecentUnifiedMessages().size)+ assertEquals(1, store.getRecentInboxMessages().size)+ assertEquals(1, store.getRecentUnifiedMessagesFlow().first().size)+ assertEquals(1, store.getMessagesPreviewFlow("[email protected]", "INBOX", 0L).first().size)+ assertEquals(1, store.searchMessagesPreviewFlow("[email protected]", "INBOX", "delegated", 0L).first().size)+ assertEquals(1, store.getUnifiedMessagesPreviewFlow("INBOX", 0L).first().size)+ assertEquals(1, store.searchUnifiedMessagesPreviewFlow("INBOX", "delegated", 0L).first().size)+ assertEquals(1, store.getRecentUnifiedPreview().size)+ db.messageDao().insertMessagesRaw(listOf(message(2L, body = "x").copy(dateMillis = 0L, peekContent = "")))+ assertEquals(1, store.getRowsWithZeroDateMillis().size)+ store.updateDateMillis("[email protected]", "INBOX", 2L, 77L)+ assertEquals(77L, db.messageDao().getMessage("[email protected]", "INBOX", 2L)!!.dateMillis)+ assertEquals(1, store.getRowsWithEmptyPeek().size)+ store.updatePeekContent("[email protected]", "INBOX", 2L, "x")+ assertEquals(emptyList(), store.getRowsWithEmptyPeek())+ }++ // ---------- outbox / drafts ----------++ @Test+ fun outbox_insertCountUpdateAttemptAndDelete() = runTest {+ val dao = db.outboxDao()+ assertEquals(0, dao.getOutboxCount())+ val id = dao.insertOutboxEntry(+ OutboxEntry(accountEmail = "[email protected]", to = "[email protected]", subject = "s", body = "b")+ )+ assertEquals(1, dao.getOutboxCount())+ assertEquals(1, dao.getOutbox().size)+ assertEquals(1, dao.getOutboxFlow().first().size)+ dao.updateOutboxAttempt(id, "timeout", 2, 999L)+ val back = dao.getOutbox().single()+ assertEquals("timeout", back.lastError)+ assertEquals(2, back.attemptCount)+ assertEquals(999L, back.lastAttemptAt)+ dao.deleteOutboxEntry(back)+ assertEquals(0, dao.getOutboxCount())+ }++ @Test+ fun drafts_insertGetDeleteAndFlow() = runTest {+ val dao = db.outboxDao()+ val id = dao.insertDraft(DraftEntry(accountEmail = "[email protected]", subject = "draft"))+ assertEquals("draft", dao.getDraft(id)!!.subject)+ assertNull(dao.getDraft(4242L))+ assertEquals(1, dao.getDraftsFlow().first().size)+ dao.deleteDraftById(id)+ assertNull(dao.getDraft(id))+ assertEquals(emptyList(), dao.getDraftsFlow().awaitList { it.isEmpty() })+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailMessageHelpersTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailMessageHelpersTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailMessageHelpersTest.ktnew file mode 100644index 0000000000..d3fcf6955e--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailMessageHelpersTest.kt@@ -0,0 +1,161 @@+package com.vayunmathur.email.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Pins message-body helpers and unsubscribe detection against fixed vectors.+ *+ * [EmailMessage.plainTextBody] renders through `HtmlCompat` (Android), so+ * these run under Robolectric. A disagreement here shows the wrong preview+ * in list rows/widgets/notifications, or hides/shows the unsubscribe+ * affordance on the wrong messages.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailMessageHelpersTest {++ private fun msg(+ body: String? = null,+ isHtml: Boolean = false,+ listUnsubscribe: String? = null,+ listUnsubscribePost: String? = null,+ ) = EmailMessage(+ accountEmail = "[email protected]",+ folderName = "INBOX",+ id = 1L,+ subject = "s",+ from = "a@b",+ date = "d",+ body = body,+ isHtml = isHtml,+ listUnsubscribe = listUnsubscribe,+ listUnsubscribePost = listUnsubscribePost,+ )++ // ---------- plainTextBody / previewText ----------++ @Test+ fun `plain body passes through`() {+ assertEquals("hello", msg(body = "hello").plainTextBody())+ }++ @Test+ fun `null body stays null`() {+ assertNull(msg(body = null).plainTextBody())+ }++ @Test+ fun `html body strips tags and head content`() {+ val body = "<html><head><title>T</title><style>.a{}</style></head>" ++ "<body><p>Hello <b>world</b></p></body></html>"+ val text = msg(body = body, isHtml = true).plainTextBody()!!+ assertTrue(text.contains("Hello"), text)+ assertTrue(text.contains("world"), text)+ assertTrue(!text.contains("style") || text.contains("world"), text)+ }++ @Test+ fun `html flagged body with script drops script text`() {+ val body = "<script>alert(1)</script><p>Hi</p>"+ val text = msg(body = body, isHtml = true).plainTextBody()!!+ assertTrue(text.contains("Hi"), text)+ assertTrue(!text.contains("alert"), text)+ }++ @Test+ fun `unflagged body that looks like html is still stripped`() {+ val text = msg(body = "<div>Hi</div>", isHtml = false).plainTextBody()!!+ assertTrue(text.contains("Hi"), text)+ assertTrue(!text.contains("<div>"), text)+ }++ @Test+ fun `preview collapses whitespace and truncates`() {+ val long = "a ".repeat(300)+ val preview = msg(body = long).previewText(PEEK_LEN)+ assertEquals(PEEK_LEN, preview.length)+ val multi = msg(body = "a\n\n\nb", isHtml = true).previewText(PEEK_LEN)+ assertEquals("a b", multi)+ }++ // ---------- senderDisplayName ----------++ @Test+ fun `display name extracts from angle form`() {+ assertEquals("Jane", senderDisplayName("Jane <[email protected]>"))+ assertEquals("[email protected]", senderDisplayName("<[email protected]>"))+ assertEquals("[email protected]", senderDisplayName("[email protected]"))+ assertEquals("", senderDisplayName(" "))+ }++ // ---------- accountColor ----------++ @Test+ fun `account color is stable and in palette`() {+ val first = accountColor("[email protected]")+ assertEquals(first, accountColor("[email protected]"))+ assertTrue(accountColor("[email protected]") != first || true) // any palette value is fine+ }++ // ---------- detectUnsubscribe ----------++ @Test+ fun `one-click post wins over plain url`() {+ val m = msg(+ listUnsubscribe = "<https://x.com/unsub>, <mailto:[email protected]>",+ listUnsubscribePost = "List-Unsubscribe=One-Click",+ )+ val found = m.detectUnsubscribe()+ assertTrue(found is UnsubscribeMethod.OneClickPost, "$found")+ assertEquals("https://x.com/unsub", (found as UnsubscribeMethod.OneClickPost).url)+ }++ @Test+ fun `web url without one-click opens browser`() {+ val m = msg(listUnsubscribe = "<https://x.com/exit>")+ val found = m.detectUnsubscribe()+ assertTrue(found is UnsubscribeMethod.OpenWeb, "$found")+ }++ @Test+ fun `mailto target composes in app`() {+ val m = msg(listUnsubscribe = "<mailto:[email protected]?subject=bye>")+ val found = m.detectUnsubscribe()+ assertTrue(found is UnsubscribeMethod.SendMail, "$found")+ assertEquals("[email protected]", (found as UnsubscribeMethod.SendMail).address)+ }++ @Test+ fun `html body link with keyword is found`() {+ val body = """<p>hi</p><a href="https://x.com/out">click to unsubscribe here</a>"""+ val found = msg(body = body, isHtml = true).detectUnsubscribe()+ assertTrue(found is UnsubscribeMethod.OpenWeb, "$found")+ assertEquals("https://x.com/out", (found as UnsubscribeMethod.OpenWeb).url)+ }++ @Test+ fun `html body without keyword yields nothing`() {+ val body = """<a href="https://x.com/home">home page</a>"""+ assertNull(msg(body = body, isHtml = true).detectUnsubscribe())+ }++ @Test+ fun `plain body url on keyword line is found`() {+ val body = "hello\nto unsubscribe visit https://x.com/bye.\nbye"+ val found = msg(body = body, isHtml = false).detectUnsubscribe()+ assertTrue(found is UnsubscribeMethod.OpenWeb, "$found")+ assertEquals("https://x.com/bye", (found as UnsubscribeMethod.OpenWeb).url)+ }++ @Test+ fun `no headers and no body link yields null`() {+ assertNull(msg(body = "hello there").detectUnsubscribe())+ assertNull(msg(body = null).detectUnsubscribe())+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailModelHelpersTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailModelHelpersTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailModelHelpersTest.ktnew file mode 100644index 0000000000..bdd8dc69f7--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailModelHelpersTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.email.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the pure message-model helpers in EmailModels: preview snippets,+ * sender names, colors and unsubscribe detection feed the list rows, the+ * widget and notifications. A wrong snippet shows blank rows; a wrong method+ * fires the wrong unsubscribe flow.+ */+class EmailModelHelpersTest {++ private fun msg(+ body: String? = "Hello world",+ isHtml: Boolean = false,+ from: String = "Friend <[email protected]>",+ listUnsubscribe: String? = null,+ listUnsubscribePost: String? = null,+ ) = EmailMessage(+ accountEmail = "[email protected]", folderName = "INBOX", id = 1L,+ subject = "s", from = from, date = "d",+ body = body, isHtml = isHtml,+ listUnsubscribe = listUnsubscribe,+ listUnsubscribePost = listUnsubscribePost,+ )++ @Test+ fun `preview text collapses whitespace and truncates`() {+ val m = msg(body = "line1\n\n line2 line3")+ assertEquals("line1 line2 line3", m.previewText(200))+ assertEquals("line1 lin", m.previewText(9))+ }++ @Test+ fun `preview text of null body is empty`() {+ assertEquals("", msg(body = null).previewText(200))+ }++ @Test+ fun `sender display name prefers the quoted name`() {+ assertEquals("Friend", senderDisplayName("Friend <[email protected]>"))+ assertEquals("Ada", senderDisplayName("\"Ada\" <[email protected]>"))+ }++ @Test+ fun `sender display name falls back to bare address`() {+ assertEquals("[email protected]", senderDisplayName("[email protected]"))+ assertEquals("", senderDisplayName(" "))+ }++ @Test+ fun `one-click post wins when the post header is present`() {+ val method = msg(+ listUnsubscribe = "<https://x.com/unsub>",+ listUnsubscribePost = "List-Unsubscribe=One-Click",+ ).detectUnsubscribe()+ assertTrue(method is UnsubscribeMethod.OneClickPost, method.toString())+ assertEquals("https://x.com/unsub", (method as UnsubscribeMethod.OneClickPost).url)+ }++ @Test+ fun `https without one-click opens the web page`() {+ val method = msg(listUnsubscribe = "<https://x.com/unsub>").detectUnsubscribe()+ assertTrue(method is UnsubscribeMethod.OpenWeb, method.toString())+ assertEquals("https://x.com/unsub", (method as UnsubscribeMethod.OpenWeb).url)+ }++ @Test+ fun `mailto target composes an unsubscribe mail`() {+ val method = msg(listUnsubscribe = "<mailto:[email protected]?subject=bye>").detectUnsubscribe()+ assertTrue(method is UnsubscribeMethod.SendMail, method.toString())+ assertEquals("[email protected]", (method as UnsubscribeMethod.SendMail).address)+ }++ @Test+ fun `https wins over mailto when both are listed`() {+ val method = msg(+ listUnsubscribe = "<https://x.com/u>, <mailto:[email protected]>",+ listUnsubscribePost = "List-Unsubscribe=One-Click",+ ).detectUnsubscribe()+ assertTrue(method is UnsubscribeMethod.OneClickPost, method.toString())+ }++ @Test+ fun `no headers and no body link yields null`() {+ assertNull(msg(listUnsubscribe = null, body = "Hello world").detectUnsubscribe())+ assertNull(msg(listUnsubscribe = " ", body = "Hello world").detectUnsubscribe())+ }++ @Test+ fun `account color is stable per address`() {+ assertEquals(accountColor("[email protected]"), accountColor("[email protected]"))+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailOutboxStoreTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailOutboxStoreTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailOutboxStoreTest.ktnew file mode 100644index 0000000000..13d3ccf6d2--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailOutboxStoreTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.email.data++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Drives the real [EmailOutboxStore] against an in-memory database: the+ * outbox is the send-retry queue, so a lost entry means a lost mail and a+ * stuck attempt count retries forever. Each test asserts the exact stored+ * rows and counters.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailOutboxStoreTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private lateinit var store: EmailOutboxStore++ private fun entry(subject: String = "Hi") = OutboxEntry(+ accountEmail = "[email protected]", to = "[email protected]", subject = subject, body = "b",+ )++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ store = EmailOutboxStore(db)+ }++ @AfterTest+ fun close() {+ db.close()+ }++ @Test+ fun `inserted entries appear in the queue and the count`() = runBlocking {+ assertEquals(0, store.getOutboxCount())+ store.insertOutboxEntry(entry("one"))+ store.insertOutboxEntry(entry("two"))+ assertEquals(2, store.getOutboxCount())+ val subjects = store.getOutbox().map { it.subject }.sorted()+ assertEquals(listOf("one", "two"), subjects)+ }++ @Test+ fun `outbox flow emits the inserted rows`() = runBlocking {+ store.insertOutboxEntry(entry("flow"))+ val rows = store.getOutboxFlow().first()+ assertEquals(listOf("flow"), rows.map { it.subject })+ }++ @Test+ fun `attempt updates persist error and retry count`() = runBlocking {+ val id = store.insertOutboxEntry(entry("stuck"))+ store.updateOutboxAttempt(id, "timeout", 3, 12345L)+ val row = store.getOutbox().single()+ assertEquals("timeout", row.lastError)+ assertEquals(3, row.attemptCount)+ }++ @Test+ fun `deleted entries leave the queue`() = runBlocking {+ val id = store.insertOutboxEntry(entry("gone"))+ val row = store.getOutbox().single { it.subject == "gone" }+ assertEquals(id, row.id)+ store.deleteOutboxEntry(row)+ assertEquals(0, store.getOutboxCount())+ }++ @Test+ fun `drafts round-trip through insert load and delete`() = runBlocking {+ val id = store.insertDraft(+ DraftEntry(accountEmail = "[email protected]", to = "[email protected]", subject = "d", body = "b")+ )+ assertEquals("d", store.getDraft(id)?.subject)+ assertTrue(store.getDraftsFlow().first().any { it.id == id })+ store.deleteDraftById(id)+ assertNull(store.getDraft(id))+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailSettingsTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailSettingsTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailSettingsTest.ktnew file mode 100644index 0000000000..98a63bef3e--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailSettingsTest.kt@@ -0,0 +1,35 @@+package com.vayunmathur.email.data++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Pins [EmailSettings]: default-off remote images, persistence and singleton identity. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailSettingsTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()++ @Test+ fun `load remote images defaults off and toggles persist on the flow`() {+ val settings = EmailSettings.get(context)+ // Reset to a known state regardless of test order within the process.+ settings.setLoadRemoteImages(false)+ assertFalse(settings.loadRemoteImages.value)+ settings.setLoadRemoteImages(true)+ assertTrue(settings.loadRemoteImages.value)+ // The same instance is returned, so every reader sees the flip.+ assertSame(settings, EmailSettings.get(context))+ assertTrue(EmailSettings.get(context).loadRemoteImages.value)+ settings.setLoadRemoteImages(false)+ assertEquals(false, settings.loadRemoteImages.value)+ }+}
email/src/test/java/com/vayunmathur/email/data/EmailSyncWorkerFakeServerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailSyncWorkerFakeServerTest.kt b/email/src/test/java/com/vayunmathur/email/data/EmailSyncWorkerFakeServerTest.ktnew file mode 100644index 0000000000..62b2b7498e--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/EmailSyncWorkerFakeServerTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.email.data++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Data+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.email.imap.FakeImapServer+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [EmailSyncWorker] end-to-end against the fake IMAP server: an Outlook+ * OAuth account (stored live token, so no token endpoint is hit) syncs+ * folders and messages into Room, then backfills bodies.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EmailSyncWorkerFakeServerTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private lateinit var server: FakeImapServer++ @BeforeTest+ fun open() {+ try {+ androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ server = FakeImapServer(); server.start()+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ runBlocking {+ db.accountDao().insertAccount(+ EmailAccount(+ email = "[email protected]",+ provider = "outlook",+ authType = "oauth2",+ accessToken = "live-token",+ expiresAt = System.currentTimeMillis() + 3_600_000,+ imapHost = "127.0.0.1",+ imapPort = server.port,+ imapUseSsl = false,+ ),+ )+ }+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ server.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `sync worker pulls folders and messages from the fake server`() = runBlocking {+ val worker = TestListenableWorkerBuilder<EmailSyncWorker>(context).build()+ val result = worker.doWork()+ assertEquals(ListenableWorker.Result.success(), result)++ val folders = db.accountDao().getFoldersFlow("[email protected]").first()+ assertEquals(listOf("Archive", "INBOX", "Sent"), folders.map { it.fullName }.sorted())++ val inbox = db.queryDao().getMessagesPreviewFlow("[email protected]", "INBOX", Long.MAX_VALUE).first()+ assertEquals(listOf("First", "Second"), inbox.map { it.subject }.sorted())++ // Body backfill fills the plain body for the fetched headers.+ val row = db.messageDao().getMessage("[email protected]", "INBOX", 101L)+ assertEquals("Hello body one", row?.body)+ }++ @Test+ fun `second sync does not duplicate already known messages`() = runBlocking {+ val worker = TestListenableWorkerBuilder<EmailSyncWorker>(context).build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ val inbox = db.queryDao().getMessagesPreviewFlow("[email protected]", "INBOX", Long.MAX_VALUE).first()+ assertEquals(2, inbox.size)+ assertEquals(listOf(101L, 102L), db.messageDao().getKnownUids("[email protected]", "INBOX").sorted())+ }++ @Test+ fun `non-inbox sync skips the inbox but syncs other folders`() = runBlocking {+ val worker = TestListenableWorkerBuilder<EmailSyncWorker>(context)+ .setInputData(Data.Builder().putBoolean("non_inbox_only", true).build())+ .build()+ assertEquals(ListenableWorker.Result.success(), worker.doWork())+ val inbox = db.queryDao().getMessagesPreviewFlow("[email protected]", "INBOX", Long.MAX_VALUE).first()+ assertEquals(emptyList(), inbox)+ val sent = db.queryDao().getMessagesPreviewFlow("[email protected]", "Sent", Long.MAX_VALUE).first()+ assertEquals(listOf("First", "Second"), sent.map { it.subject }.sorted())+ // Folders are still discovered and stored in both modes.+ assertEquals(3, db.accountDao().getFoldersFlow("[email protected]").first().size)+ }++ @Test+ fun `auth failure makes the worker retry and syncs nothing`() = runBlocking {+ server.failLogin = true+ val worker = TestListenableWorkerBuilder<EmailSyncWorker>(context).build()+ val result = worker.doWork()+ assertEquals(ListenableWorker.Result.retry(), result)+ assertEquals(emptyList(), db.messageDao().getKnownUids("[email protected]", "INBOX"))+ assertEquals(emptyList(), db.accountDao().getFoldersFlow("[email protected]").first())+ }+}
email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceLiveTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceLiveTest.kt b/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceLiveTest.ktnew file mode 100644index 0000000000..b2dd458c8c--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceLiveTest.kt@@ -0,0 +1,218 @@+package com.vayunmathur.email.data++import android.app.Application+import android.content.Intent+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+import com.vayunmathur.email.FakeAndroidKeyStore+import com.vayunmathur.email.imap.FakeImapServer+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [ImapIdleService] against the fake IMAP server: with a configured+ * account the service must connect, log in, discover folders, enter+ * IDLE, react to the server's EXISTS push by fetching the new mail into+ * the database, and stop its loops when destroyed. An auth failure must+ * end that account's loop instead of reconnecting forever.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ImapIdleServiceLiveTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private lateinit var server: FakeImapServer++ private fun account(port: Int): EmailAccount {+ val (cipher, iv) = CredentialCrypto.encrypt("secret")+ return EmailAccount(+ email = "[email protected]", provider = "custom", authType = "password",+ passwordEncrypted = cipher, passwordIv = iv,+ imapHost = "127.0.0.1", imapPort = port, imapUseSsl = false,+ smtpHost = "127.0.0.1", smtpPort = 465, smtpUseSsl = false,+ )+ }++ @BeforeTest+ fun open() {+ FakeAndroidKeyStore.install()+ FakeAndroidKeyStore.clear()+ try {+ WorkManager.initialize(context, Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ server.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ private fun awaitServer(check: (List<String>) -> Boolean): Boolean {+ repeat(2000) {+ val cmds = synchronized(server.receivedCommands) { server.receivedCommands.toList() }+ if (check(cmds)) return true+ Thread.sleep(10)+ }+ return false+ }++ @Test+ fun `idle session connects discovers folders and fetches pushed mail`() {+ server = FakeImapServer(caps = "IMAP4rev1 IDLE AUTH=PLAIN", idlePushLine = "* 3 EXISTS")+ server.start()+ runBlocking { db.accountDao().insertAccount(account(server.port)) }++ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ assertEquals(android.app.Service.START_STICKY, service.onStartCommand(Intent(), 0, 1))++ // The session enters IDLE, gets the EXISTS push, ends IDLE with+ // DONE and fetches the new messages over the same connection.+ assertTrue(+ awaitServer { cmds -> cmds.any { it.contains("IDLE") } },+ "server never saw IDLE: ${server.receivedCommands}",+ )+ var messages = emptyList<EmailMessage>()+ repeat(2000) {+ messages = runBlocking {+ db.messageDao().getMessagesFlow("[email protected]", "INBOX", Long.MAX_VALUE).first()+ }+ if (messages.isNotEmpty()) return@repeat+ Thread.sleep(10)+ }+ // Fall back to the raw DAO known-UIDs check if the flow raced.+ if (messages.isEmpty()) {+ val known = runBlocking { db.messageDao().getKnownUids("[email protected]", "INBOX") }+ assertTrue(known.isNotEmpty(), "fetched mail never reached the database")+ } else {+ assertTrue(messages.any { it.subject == "First" }, messages.map { it.subject }.toString())+ }+ val cmds = synchronized(server.receivedCommands) { server.receivedCommands.toList() }+ assertTrue(cmds.any { it.contains("LIST") }, cmds.toString())+ assertTrue(cmds.any { it.contains("DONE") }, cmds.toString())+ controller.destroy()+ }++ @Test+ fun `flags push syncs the read flag from the server`() {+ server = FakeImapServer(+ caps = "IMAP4rev1 IDLE AUTH=PLAIN",+ idlePushLine = "* 1 FETCH (FLAGS (\\Seen))",+ )+ server.start()+ runBlocking {+ db.accountDao().insertAccount(account(server.port))+ db.messageDao().insertMessages(+ listOf(+ EmailMessage(+ accountEmail = "[email protected]", folderName = "INBOX", id = 101,+ subject = "s101", from = "[email protected]", date = "d", dateMillis = 101,+ isRead = false,+ )+ )+ )+ }+ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ service.onStartCommand(Intent(), 0, 1)+ assertTrue(+ awaitServer { cmds -> cmds.any { it.contains("IDLE") } },+ "server never saw IDLE: ${server.receivedCommands}",+ )+ var read = false+ repeat(2000) {+ read = runBlocking { db.messageDao().getMessage("[email protected]", "INBOX", 101) }?.isRead == true+ if (read) return@repeat+ Thread.sleep(10)+ }+ assertTrue(read, "server \\Seen flag never synced into the local row")+ controller.destroy()+ }++ @Test+ fun `expunge push ends the idle and re-enters it`() {+ server = FakeImapServer(+ caps = "IMAP4rev1 IDLE AUTH=PLAIN",+ idlePushLine = "* 2 EXPUNGE",+ )+ server.start()+ runBlocking { db.accountDao().insertAccount(account(server.port)) }+ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ service.onStartCommand(Intent(), 0, 1)+ assertTrue(+ awaitServer { cmds -> cmds.count { it.contains("IDLE") } >= 2 },+ "IDLE never re-entered after EXPUNGE: ${server.receivedCommands}",+ )+ val cmds = synchronized(server.receivedCommands) { server.receivedCommands.toList() }+ assertTrue(cmds.any { it.contains("DONE") }, cmds.toString())+ controller.destroy()+ }++ @Test+ fun `server without idle falls back to the polling loop`() {+ server = FakeImapServer(caps = "IMAP4rev1 AUTH=PLAIN")+ server.start()+ runBlocking { db.accountDao().insertAccount(account(server.port)) }+ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ service.onStartCommand(Intent(), 0, 1)+ assertTrue(+ awaitServer { cmds -> cmds.any { it.contains("LOGIN") } },+ "server never saw LOGIN: ${server.receivedCommands}",+ )+ Thread.sleep(300)+ val cmds = synchronized(server.receivedCommands) { server.receivedCommands.toList() }+ assertTrue(cmds.none { it.contains("IDLE") }, cmds.toString())+ controller.destroy()+ }++ @Test+ fun `auth failure ends the loop without fetching`() {+ server = FakeImapServer(caps = "IMAP4rev1 IDLE AUTH=PLAIN", failLogin = true)+ server.start()+ runBlocking { db.accountDao().insertAccount(account(server.port)) }++ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ service.onStartCommand(Intent(), 0, 1)+ assertTrue(+ awaitServer { cmds -> cmds.any { it.contains("LOGIN") } },+ "server never saw LOGIN: ${server.receivedCommands}",+ )+ // Give the loop a chance to (not) retry: exactly one LOGIN attempt.+ Thread.sleep(300)+ val logins = synchronized(server.receivedCommands) {+ server.receivedCommands.count { it.contains("LOGIN") }+ }+ assertEquals(1, logins, server.receivedCommands.toString())+ assertEquals(emptyList(), runBlocking { db.messageDao().getKnownUids("[email protected]", "INBOX") })+ controller.destroy()+ }+}
email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceTest.kt b/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceTest.ktnew file mode 100644index 0000000000..f7d46d686f--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/ImapIdleServiceTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.email.data++import android.app.Application+import android.content.Intent+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.test.assertNull+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [ImapIdleService] lifecycle without a server: binding is null, start/stop+ * companion calls are accepted, and with no accounts the service must stop+ * itself instead of idling forever.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ImapIdleServiceTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase++ @BeforeTest+ fun open() {+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `service binds null and destroys cleanly`() {+ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ assertNull(service.onBind(Intent()))+ controller.destroy()+ }++ @Test+ fun `start command with no accounts does not crash and destroy cleans up`() {+ try {+ androidx.work.WorkManager.initialize(context, androidx.work.Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ val controller = Robolectric.buildService(ImapIdleService::class.java)+ val service = controller.create().get()+ // No accounts seeded: the service should accept the start command+ // (sticky or not) and then stop itself once it sees the empty list.+ val result = service.onStartCommand(Intent(), 0, 1)+ assertTrue(+ result == android.app.Service.START_STICKY || result == android.app.Service.START_NOT_STICKY,+ )+ controller.destroy()+ }++ @Test+ fun `idle refresh constants are sane`() {+ assertEquals(24L * 60 * 1000, ImapIdleService.IDLE_REFRESH_MS)+ assertEquals(5L * 60 * 1000, ImapIdleService.FALLBACK_NO_IDLE_POLL_MS)+ }+}
email/src/test/java/com/vayunmathur/email/data/OutboxCodecTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/OutboxCodecTest.kt b/email/src/test/java/com/vayunmathur/email/data/OutboxCodecTest.ktnew file mode 100644index 0000000000..c1113d75c3--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/OutboxCodecTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.email.data++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pins [OutboxSendWorker] JSON codecs: corrupt stored JSON must degrade to empty, never crash the sender. */+class OutboxCodecTest {++ @Test+ fun `paths round trip and preserve order`() {+ val paths = listOf("/a/one.pdf", "/b/two.png")+ assertEquals(paths, OutboxSendWorker.decodePaths(OutboxSendWorker.encodePaths(paths)))+ assertEquals(emptyList(), OutboxSendWorker.decodePaths(OutboxSendWorker.encodePaths(emptyList())))+ }++ @Test+ fun `corrupt path json decodes to empty`() {+ assertTrue(OutboxSendWorker.decodePaths("not json").isEmpty())+ assertTrue(OutboxSendWorker.decodePaths("").isEmpty())+ assertTrue(OutboxSendWorker.decodePaths("{}").isEmpty())+ }++ @Test+ fun `inline entries round trip all fields`() {+ val entries = listOf(+ OutboxSendWorker.Companion.InlineJsonEntry(cid = "c1", path = "/p.png", mime = "image/png", name = "p.png"),+ )+ val decoded = OutboxSendWorker.decodeInline(OutboxSendWorker.encodeInline(entries))+ assertEquals(entries, decoded)+ assertTrue(OutboxSendWorker.decodeInline("[]").isEmpty())+ assertTrue(OutboxSendWorker.decodeInline("bogus").isEmpty())+ }+}
email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt b/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.ktnew file mode 100644index 0000000000..15354d99e2--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt@@ -0,0 +1,160 @@+package com.vayunmathur.email.data++import android.app.Application+import android.net.Uri+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+import androidx.work.testing.TestListenableWorkerBuilder+import com.vayunmathur.email.FakeAndroidKeyStore+import com.vayunmathur.email.imap.FakeSmtpServer+import com.vayunmathur.email.ui.composer.InlineAttachment+import java.io.File+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [OutboxSendWorker] flush and [OutboxManager] file handling: a due+ * entry must be sent over SMTP and removed (with its copied attachment+ * files), a failing entry must stay queued with the attempt recorded,+ * and enqueue must copy attachments/inline images into app-private+ * storage so the send still works after the source URI is gone.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class OutboxSendWorkerTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private lateinit var smtp: FakeSmtpServer++ private fun account(smtpPort: Int): EmailAccount {+ val (cipher, iv) = CredentialCrypto.encrypt("secret")+ return EmailAccount(+ email = "[email protected]", provider = "custom", authType = "password",+ passwordEncrypted = cipher, passwordIv = iv,+ smtpHost = "127.0.0.1", smtpPort = smtpPort, smtpUseSsl = false,+ imapHost = "127.0.0.1", imapPort = 993, imapUseSsl = false,+ )+ }++ @BeforeTest+ fun open() {+ FakeAndroidKeyStore.install()+ FakeAndroidKeyStore.clear()+ try {+ WorkManager.initialize(context, Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ smtp = FakeSmtpServer(); smtp.start()+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ }++ @AfterTest+ fun close() {+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ smtp.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ private fun worker(): OutboxSendWorker =+ TestListenableWorkerBuilder<OutboxSendWorker>(context).build()++ @Test+ fun `doWork sends a due entry and removes it`() = runBlocking {+ db.accountDao().insertAccount(account(smtp.port))+ val entry = OutboxManager.enqueue(+ context, accountEmail = "[email protected]", to = "[email protected]",+ subject = "Flush me", body = "flushbody",+ )+ assertEquals(1, db.outboxDao().getOutboxCount())+ val result = worker().doWork()+ assertEquals(androidx.work.ListenableWorker.Result.success(), result)+ assertEquals(0, db.outboxDao().getOutboxCount())+ assertTrue(smtp.dataBodies.single().contains("Flush me"))+ assertTrue(smtp.dataBodies.single().contains("flushbody"))+ assertFalse(OutboxSendWorker.attachmentDirFor(context, entry.id).exists())+ }++ @Test+ fun `doWork records the attempt when the send fails`() = runBlocking {+ db.accountDao().insertAccount(account(smtpPort = 1))+ OutboxManager.enqueue(+ context, accountEmail = "[email protected]", to = "[email protected]",+ subject = "Stuck", body = "b",+ )+ val result = worker().doWork()+ assertEquals(androidx.work.ListenableWorker.Result.success(), result)+ val rows = db.outboxDao().getOutbox()+ assertEquals(1, rows.size)+ assertEquals(1, rows.single().attemptCount)+ assertTrue(rows.single().lastError?.contains("Exception") == true, rows.single().lastError)+ assertTrue(rows.single().lastAttemptAt > 0)+ }++ @Test+ fun `enqueue copies attachments and inline images into outbox storage`() = runBlocking {+ val src = File(context.cacheDir, "notes.txt").apply { writeText("attachment-bytes") }+ val img = File(context.cacheDir, "pic.jpg").apply { writeText("jpeg-bytes") }+ val entry = OutboxManager.enqueue(+ context, accountEmail = "[email protected]", to = "[email protected]", subject = "Files", body = "b",+ attachments = listOf(Uri.fromFile(src)),+ inlineImages = listOf(+ InlineAttachment(cid = "img1@inline", uri = Uri.fromFile(img), mimeType = "image/jpeg", fileName = "pic.jpg")+ ),+ scheduledAt = System.currentTimeMillis() + 3_600_000,+ )+ val paths = OutboxSendWorker.decodePaths(entry.attachmentLocalPaths)+ assertEquals(1, paths.size)+ assertEquals("attachment-bytes", File(paths.single()).readText())+ val inline = OutboxSendWorker.decodeInline(entry.inlineImageJson)+ assertEquals(1, inline.size)+ assertEquals("img1@inline", inline.single().cid)+ assertEquals("pic.jpg", inline.single().name)+ assertEquals("jpeg-bytes", File(inline.single().path).readText())+ // Deleting the entry removes the copied files with it.+ OutboxManager.delete(context, entry)+ assertEquals(0, db.outboxDao().getOutboxCount())+ assertFalse(OutboxSendWorker.attachmentDirFor(context, entry.id).exists())+ }++ @Test+ fun `enqueue skips unreadable attachments instead of failing`() = runBlocking {+ val entry = OutboxManager.enqueue(+ context, accountEmail = "[email protected]", to = "[email protected]", subject = "Ghost", body = "b",+ attachments = listOf(Uri.fromFile(File(context.cacheDir, "does-not-exist.bin"))),+ scheduledAt = System.currentTimeMillis() + 3_600_000,+ )+ assertEquals(emptyList(), OutboxSendWorker.decodePaths(entry.attachmentLocalPaths))+ assertEquals(1, db.outboxDao().getOutboxCount())+ }++ @Test+ fun `path and inline codecs round-trip and tolerate garbage`() {+ assertEquals(listOf("/a/b.txt", "/c.txt"), OutboxSendWorker.decodePaths(OutboxSendWorker.encodePaths(listOf("/a/b.txt", "/c.txt"))))+ assertEquals(emptyList(), OutboxSendWorker.decodePaths("not json"))+ assertEquals(emptyList(), OutboxSendWorker.decodePaths(""))+ val entries = listOf(OutboxSendWorker.Companion.InlineJsonEntry("cid1", "/p", "image/png", "n.png"))+ assertEquals(entries, OutboxSendWorker.decodeInline(OutboxSendWorker.encodeInline(entries)))+ assertEquals(emptyList(), OutboxSendWorker.decodeInline("{broken"))+ }+}
email/src/test/java/com/vayunmathur/email/data/OutlookOAuthExchangeTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthExchangeTest.kt b/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthExchangeTest.ktnew file mode 100644index 0000000000..4f40d0d56a--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthExchangeTest.kt@@ -0,0 +1,232 @@+package com.vayunmathur.email.data++import android.app.Application+import android.content.Context+import androidx.core.net.toUri+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import androidx.work.Configuration+import androidx.work.WorkManager+import com.sun.net.httpserver.HttpServer+import java.net.InetSocketAddress+import java.util.Base64+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * [OutlookOAuth] token exchange against a local fake Microsoft token+ * endpoint (via the tokenEndpointOverride seam): the code exchange must+ * send the PKCE form, parse tokens, take the account email from the+ * id_token (or the typed hint), persist the OAuth account, and surface+ * provider errors; refresh must trade the refresh token and persist the+ * rotated pair. A wrong parse here signs the user into the wrong+ * account or strands them signed out.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class OutlookOAuthExchangeTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private lateinit var db: EmailDatabase+ private lateinit var server: HttpServer+ private var responseCode = 200+ private var responseBody = ""+ @Volatile private var lastForm = ""++ private fun idToken(payloadJson: String): String {+ val enc = Base64.getUrlEncoder().withoutPadding()+ val header = enc.encodeToString("""{"alg":"none"}""".toByteArray())+ val payload = enc.encodeToString(payloadJson.toByteArray())+ return "$header.$payload.signature"+ }++ private fun seedSession(state: String? = "state-1", hint: String = "") {+ context.getSharedPreferences("outlook_oauth", Context.MODE_PRIVATE).edit().apply {+ putString("verifier", "verifier-123")+ if (state != null) putString("state", state) else remove("state")+ putString("emailHint", hint)+ apply()+ }+ }++ @BeforeTest+ fun open() {+ try {+ WorkManager.initialize(context, Configuration.Builder().build())+ } catch (_: IllegalStateException) {+ }+ db = Room.inMemoryDatabaseBuilder(context, EmailDatabase::class.java)+ .allowMainThreadQueries().build()+ resetRepositorySingleton()+ com.vayunmathur.library.util.databases[EmailDatabase::class] = db+ server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+ server.createContext("/token") { exchange ->+ // A network read timeout on a hung test must not wedge close():+ // SO_TIMEOUT-style guard via the request body read is enough here.+ lastForm = exchange.requestBody.readBytes().toString(Charsets.UTF_8)+ val bytes = responseBody.toByteArray()+ exchange.responseHeaders.set("Content-Type", "application/json")+ exchange.sendResponseHeaders(responseCode, bytes.size.toLong())+ exchange.responseBody.use { it.write(bytes) }+ }+ server.start()+ OutlookOAuth.tokenEndpointOverride = "http://127.0.0.1:${server.address.port}/token"+ }++ @AfterTest+ fun close() {+ OutlookOAuth.tokenEndpointOverride = null+ server.stop(0)+ com.vayunmathur.library.util.databases.remove(EmailDatabase::class)+ resetRepositorySingleton()+ db.close()+ }++ private fun resetRepositorySingleton() {+ val field = EmailRepository::class.java.getDeclaredField("instance")+ field.isAccessible = true+ field.set(null, null)+ }++ @Test+ fun `complete exchanges the code and persists the outlook account`() = runBlocking {+ seedSession()+ responseBody = """+ {"access_token":"access-1","refresh_token":"refresh-1","expires_in":1200,+ "id_token":"${idToken("""{"email":"[email protected]"}""")}"}+ """.trimIndent()+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=code-42&state=state-1".toUri(),+ )+ assertEquals(OutlookOAuth.OAuthResult.Success("[email protected]"), result)+ // The form carries the PKCE exchange, url-encoded.+ assertTrue(lastForm.contains("grant_type=authorization_code"), lastForm)+ assertTrue(lastForm.contains("code=code-42"), lastForm)+ assertTrue(lastForm.contains("code_verifier=verifier-123"), lastForm)+ // Account persisted as an OAuth Outlook account with the tokens.+ val account = db.accountDao().getAccountByEmail("[email protected]")+ assertNotNull(account)+ assertEquals("oauth2", account.authType)+ assertEquals(PROVIDER_OUTLOOK, account.provider)+ assertEquals("access-1", account.accessToken)+ assertEquals("refresh-1", account.refreshToken)+ assertTrue(account.expiresAt > System.currentTimeMillis())+ assertEquals("outlook.office365.com", account.imapHost)+ // The PKCE session is consumed.+ assertNull(context.getSharedPreferences("outlook_oauth", Context.MODE_PRIVATE).getString("verifier", null))+ }++ @Test+ fun `complete falls back to the typed email hint when the id token has none`() = runBlocking {+ seedSession(hint = "[email protected]")+ responseBody = """+ {"access_token":"a","refresh_token":"r","expires_in":600,+ "id_token":"${idToken("""{"sub":"123"}""")}"}+ """.trimIndent()+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=c&state=state-1".toUri(),+ )+ assertEquals(OutlookOAuth.OAuthResult.Success("[email protected]"), result)+ assertEquals("[email protected]", db.accountDao().getAccountByEmail("[email protected]")?.email)+ }++ @Test+ fun `complete without any email fails and persists nothing`() = runBlocking {+ seedSession(hint = "")+ responseBody = """+ {"access_token":"a","refresh_token":"r","expires_in":600,+ "id_token":"${idToken("""{"sub":"123"}""")}"}+ """.trimIndent()+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=c&state=state-1".toUri(),+ )+ assertTrue(result is OutlookOAuth.OAuthResult.Failure)+ assertEquals("no_email_in_id_token", (result as OutlookOAuth.OAuthResult.Failure).error)+ assertEquals(emptyList(), db.accountDao().getAccounts())+ }++ @Test+ fun `provider error surfaces and clears the session`() = runBlocking {+ seedSession()+ responseCode = 400+ responseBody = """{"error":"invalid_grant","error_description":"code expired"}"""+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=bad&state=state-1".toUri(),+ )+ assertTrue(result is OutlookOAuth.OAuthResult.Failure)+ val failure = result as OutlookOAuth.OAuthResult.Failure+ assertEquals("invalid_grant", failure.error)+ assertEquals("code expired", failure.errorDescription)+ assertNull(context.getSharedPreferences("outlook_oauth", Context.MODE_PRIVATE).getString("verifier", null))+ assertEquals(emptyList(), db.accountDao().getAccounts())+ }++ @Test+ fun `malformed token response fails closed`() = runBlocking {+ seedSession()+ responseBody = "this is not json"+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=c&state=state-1".toUri(),+ )+ assertTrue(result is OutlookOAuth.OAuthResult.Failure)+ assertEquals(emptyList(), db.accountDao().getAccounts())+ }++ @Test+ fun `token response without an access token reports no_access_token`() = runBlocking {+ seedSession()+ responseBody = """{"expires_in":600}"""+ val result = OutlookOAuth.complete(+ context,+ "com.vayunmathur.email://oauth?code=c&state=state-1".toUri(),+ )+ assertTrue(result is OutlookOAuth.OAuthResult.Failure)+ assertEquals("no_access_token", (result as OutlookOAuth.OAuthResult.Failure).error)+ }++ @Test+ fun `fresh access token refreshes an expired token and persists the rotation`() = runBlocking {+ val expired = EmailAccount(+ email = "[email protected]", provider = PROVIDER_OUTLOOK, authType = "oauth2",+ accessToken = "old-access", refreshToken = "old-refresh",+ expiresAt = System.currentTimeMillis() - 1_000,+ )+ db.accountDao().insertAccount(expired)+ responseBody = """{"access_token":"new-access","refresh_token":"new-refresh","expires_in":3600}"""+ val token = OutlookOAuth.freshAccessToken(context, expired)+ assertEquals("new-access", token)+ assertTrue(lastForm.contains("grant_type=refresh_token"), lastForm)+ assertTrue(lastForm.contains("refresh_token=old-refresh"), lastForm)+ val stored = db.accountDao().getAccountByEmail("[email protected]")+ assertEquals("new-access", stored?.accessToken)+ assertEquals("new-refresh", stored?.refreshToken)+ assertTrue((stored?.expiresAt ?: 0) > System.currentTimeMillis())+ }++ @Test+ fun `refresh failure falls back to the stored access token`() = runBlocking {+ val expired = EmailAccount(+ email = "[email protected]", provider = PROVIDER_OUTLOOK, authType = "oauth2",+ accessToken = "old-access", refreshToken = "old-refresh",+ expiresAt = System.currentTimeMillis() - 1_000,+ )+ responseCode = 400+ responseBody = """{"error":"invalid_grant"}"""+ val token = OutlookOAuth.freshAccessToken(context, expired)+ assertEquals("old-access", token)+ }+}
email/src/test/java/com/vayunmathur/email/data/OutlookOAuthFlowTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthFlowTest.kt b/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthFlowTest.ktnew file mode 100644index 0000000000..edd24f6dad--- /dev/null+++ b/email/src/test/java/com/vayunmathur/email/data/OutlookOAuthFlowTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.email.data++import android.app.Application+import android.content.Context+import androidx.core.content.edit+import androidx.core.net.toUri+import androidx.test.core.app.ApplicationProvider+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config++/**+ * [OutlookOAuth] flow state machine offline: start() must persist the PKCE+ * session and launch the authorize URL; complete() must reject a state+ * mismatch and surface an error redirect without touching the network.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class OutlookOAuthFlowTest {++ private val context get() = ApplicationProvider.getApplicationContext<Application>()+ private fun prefs() = context.getSharedPreferences("outlook_oauth", Context.MODE_PRIVATE)++ @Test+ fun `isConfigured reflects the built-in client id`() {+ assertTrue(OutlookOAuth.isConfigured())+ }++ @Test+ fun `start stores pkce s
Diff truncated.