Modern Apps git

← Modern-Apps.git

add more tests

Commit
bc68f14c25c2b08fe8680a5065616df2dd82d72f
Author
vayun-mathur <[email protected]>
When
2026-10-21 18:38 UTC (1 month ago)
Parents
1d3ea01

Diff

appstore/src/main/rust/src/tests.rs
diff --git a/appstore/src/main/rust/src/tests.rs b/appstore/src/main/rust/src/tests.rsindex 1c8246b3f1..8c61a1fc9d 100644--- a/appstore/src/main/rust/src/tests.rs+++ b/appstore/src/main/rust/src/tests.rs@@ -76,3 +76,43 @@ fn rejects_truncated_inputs() {     assert!(!verify(&[], REPODATA, &sig));     assert!(!verify(&pk, REPODATA, &[])); }++#[test]+fn rejects_empty_message() {+    assert!(!verify(&pubkey(), &[], &signature()));+}++#[test]+fn rejects_message_with_flipped_final_byte() {+    let mut tampered = REPODATA.to_vec();+    let last = tampered.len() - 1;+    tampered[last] ^= 1;+    assert!(!verify(&pubkey(), &tampered, &signature()));+}++#[test]+fn rejects_signature_with_flipped_final_byte() {+    let mut sig = signature();+    let last = sig.len() - 1;+    sig[last] ^= 1;+    assert!(!verify(&pubkey(), REPODATA, &sig));+}++#[test]+fn rejects_oversized_public_key() {+    let mut pk = pubkey();+    pk.push(0);+    assert!(!verify(&pk, REPODATA, &signature()));+}++#[test]+fn rejects_oversized_signature() {+    let mut sig = signature();+    sig.push(0);+    assert!(!verify(&pubkey(), REPODATA, &sig));+}++#[test]+fn rejects_all_zero_signature() {+    assert!(!verify(&pubkey(), REPODATA, &[0u8; 64]));+}
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.ktnew file mode 100644index 0000000000..379136013b--- /dev/null+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorEvaluateTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.calculator.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: tap keys 2 + 3 x 4 = and the evaluated result is shown.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects on+ * hidden InputManager APIs that no longer exist on current releases, so every+ * compose-rule test dies before its first line. Text polling works for Compose+ * and non-Compose screens alike.+ */+@RunWith(AndroidJUnit4::class)+class CalculatorEvaluateTest {++    @Test+    fun tapKeys_evaluates_showsResult() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName++        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)++        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)++        // Past the permission screen: the gate wall never appears (calculator+        // has none; gated apps assert the same absence to prove they cleared it).+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        // Main content is actually visible: the keypad equals key plus a tab label.+        assertNotNull(+            "calculator keypad never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(EQUALS_KEY)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "calculator tabs never appeared",+            device.wait(Until.findObject(By.text(BOTTOM_TAB_LABEL)), SHORT_TIMEOUT_MS),+        )++        // Standard precedence: 2 + 3 x 4 evaluates to 14.+        for (key in arrayOf("2", "+", "3", "x", "4", EQUALS_KEY)) {+            val button = device.wait(Until.findObject(By.text(key)), SHORT_TIMEOUT_MS)+            assertNotNull("keypad key $key never appeared", button)+            button!!.click()+        }+        assertNotNull(+            "evaluated result never appeared",+            device.wait(Until.findObject(By.text(EXPECTED_RESULT)), CONTENT_TIMEOUT_MS),+        )+        // Still alive in front: the process did not crash after painting content.+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val SHORT_TIMEOUT_MS = 5_000L+        private const val BOTTOM_TAB_LABEL = "Calculator"+        private const val EQUALS_KEY = "="+        private const val EXPECTED_RESULT = "14"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++        /**+         * Special access behind some apps' gates: exact alarms + full-screen intent+         * have no pm-grantable permission, but the shell can flip their appops.+         * Ignored where the appop does not exist; the gate assertion reports it.+         */+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.ktnew file mode 100644index 0000000000..9c79ef944d--- /dev/null+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorGraphTest.kt@@ -0,0 +1,90 @@+package com.vayunmathur.calculator.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: Graph tab, tap Add function, a function row appears.+ * UiDevice polling, not compose-test: Espresso idle-sync is broken on API 37.+ */+@RunWith(AndroidJUnit4::class)+class CalculatorGraphTest {++    @Test+    fun graphTab_addFunction_showsFunctionRow() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "calculator keypad never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(EQUALS_KEY)), CONTENT_TIMEOUT_MS),+        )+        val graphTab = device.wait(Until.findObject(By.text(GRAPH_TAB)), CONTENT_TIMEOUT_MS)+        assertNotNull("Graph tab never appeared", graphTab)+        graphTab!!.click()+        val add = device.wait(Until.findObject(By.text(ADD_FUNCTION)), CONTENT_TIMEOUT_MS)+        assertNotNull("graph screen never opened", add)+        add!!.click()+        assertNotNull(+            "function editor never appeared",+            device.wait(Until.findObject(By.text(FUNCTION_PLACEHOLDER)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val EQUALS_KEY = "="+        private const val GRAPH_TAB = "Graph"+        private const val ADD_FUNCTION = "Add function"+        private const val FUNCTION_PLACEHOLDER = "f(x)"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt
diff --git a/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.ktnew file mode 100644index 0000000000..d73c1ceac6--- /dev/null+++ b/calculator/src/androidTest/java/com/vayunmathur/calculator/ui/CalculatorUnitsTest.kt@@ -0,0 +1,103 @@+package com.vayunmathur.calculator.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: Units tab, switch the category to Mass, the converter result shows.+ * UiDevice polling, not compose-test: Espresso idle-sync is broken on API 37.+ */+@RunWith(AndroidJUnit4::class)+class CalculatorUnitsTest {++    @Test+    fun unitsTab_selectCategory_showsResult() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "calculator keypad never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(EQUALS_KEY)), CONTENT_TIMEOUT_MS),+        )+        val unitsTab = device.wait(Until.findObject(By.text(UNITS_TAB)), CONTENT_TIMEOUT_MS)+        assertNotNull("Units tab never appeared", unitsTab)+        unitsTab!!.click()+        assertNotNull(+            "unit converter never opened",+            device.wait(Until.findObject(By.text(RESULT_LABEL)), CONTENT_TIMEOUT_MS),+        )+        val category = device.wait(Until.findObject(By.text(DEFAULT_CATEGORY)), SHORT_TIMEOUT_MS)+        assertNotNull("category selector never appeared", category)+        category!!.click()+        val mass = device.wait(Until.findObject(By.text(MASS_CATEGORY)), CONTENT_TIMEOUT_MS)+        assertNotNull("Mass category never appeared", mass)+        mass!!.click()+        assertNotNull(+            "Mass category was not selected",+            device.wait(Until.findObject(By.text(MASS_CATEGORY)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "converter result never appeared",+            device.wait(Until.findObject(By.text(RESULT_LABEL)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val SHORT_TIMEOUT_MS = 5_000L+        private const val EQUALS_KEY = "="+        private const val UNITS_TAB = "Units"+        private const val DEFAULT_CATEGORY = "Length"+        private const val MASS_CATEGORY = "Mass"+        private const val RESULT_LABEL = "Result"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarCreateTest.kt
diff --git a/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarCreateTest.kt b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarCreateTest.ktnew file mode 100644index 0000000000..a760769e38--- /dev/null+++ b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarCreateTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.calendar.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: FAB into the editor, type title, save, agenda shows the event.+ * UiDevice polling, not compose-test: Espresso idle-sync is broken on API 37.+ */+@RunWith(AndroidJUnit4::class)+class CalendarCreateTest {++    @Test+    fun createEvent_save_showsInAgenda() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "agenda view never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_TIMEOUT_MS),+        )+        ensureCalendar(device)+        device.findObject(By.desc(ADD_DESCRIPTION))!!.click()+        assertNotNull(+            "event editor never opened",+            device.wait(Until.findObject(By.text(TITLE_LABEL)), CONTENT_TIMEOUT_MS),+        )+        val fields = device.wait(Until.findObjects(By.clazz(EDIT_TEXT_CLASS)), CONTENT_TIMEOUT_MS)+        assertNotNull("title field never appeared", fields)+        fields!![0].click()+        fields[0].setText(EVENT_TITLE)+        device.findObject(By.desc(SAVE_DESCRIPTION))!!.click()+        assertNotNull(+            "created event never appeared in agenda",+            device.wait(Until.findObject(By.text(EVENT_TITLE)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun ensureCalendar(device: UiDevice) {+        val create = device.wait(Until.findObject(By.text(CREATE_CALENDAR)), SHORT_TIMEOUT_MS) ?: return+        create.click()+        assertNotNull(+            "new calendar dialog never opened",+            device.wait(Until.findObject(By.text(NEW_CALENDAR_TITLE)), CONTENT_TIMEOUT_MS),+        )+        val fields = device.wait(Until.findObjects(By.clazz(EDIT_TEXT_CLASS)), CONTENT_TIMEOUT_MS)+        assertNotNull("calendar name field never appeared", fields)+        fields!![0].click()+        fields[0].setText(CALENDAR_NAME)+        device.findObject(By.text(CONFIRM_CREATE))!!.click()+        assertNotNull(+            "did not return to agenda after creating calendar",+            device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_TIMEOUT_MS),+        )+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val SHORT_TIMEOUT_MS = 5_000L+        private const val AGENDA_TAB = "Agenda"+        private const val TITLE_LABEL = "Title"+        private const val ADD_DESCRIPTION = "Add"+        private const val SAVE_DESCRIPTION = "Save"+        private const val EDIT_TEXT_CLASS = "android.widget.EditText"+        private const val EVENT_TITLE = "Journey Standup Alpha"+        private const val CREATE_CALENDAR = "Create a calendar"+        private const val NEW_CALENDAR_TITLE = "New local calendar"+        private const val CALENDAR_NAME = "JourneyCal"+        private const val CONFIRM_CREATE = "Create"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarEditTest.kt
diff --git a/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarEditTest.kt b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarEditTest.ktnew file mode 100644index 0000000000..6f78a7c1f5--- /dev/null+++ b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarEditTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.calendar.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: open a created event, edit its title, save, agenda shows the new title.+ * UiDevice polling, not compose-test: Espresso idle-sync is broken on API 37.+ */+@RunWith(AndroidJUnit4::class)+class CalendarEditTest {++    @Test+    fun openEvent_editTitle_savedChipShows() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "agenda view never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_TIMEOUT_MS),+        )+        ensureCalendar(device)+        device.findObject(By.desc(ADD_DESCRIPTION))!!.click()+        setTitle(device, ORIGINAL_TITLE)+        val chip = device.wait(Until.findObject(By.text(ORIGINAL_TITLE)), CONTENT_TIMEOUT_MS)+        assertNotNull("created event never appeared in agenda", chip)+        chip!!.click()+        val edit = device.wait(Until.findObject(By.desc(EDIT_DESCRIPTION)), CONTENT_TIMEOUT_MS)+        assertNotNull("event edit entry never appeared", edit)+        edit!!.click()+        setTitle(device, UPDATED_TITLE)+        assertNotNull(+            "edited title never appeared",+            device.wait(Until.findObject(By.text(UPDATED_TITLE)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun setTitle(device: UiDevice, title: String) {+        assertNotNull("event editor never opened", device.wait(Until.findObject(By.text(TITLE_LABEL)), CONTENT_MS))+        val fields = device.wait(Until.findObjects(By.clazz(EDIT_TEXT_CLASS)), CONTENT_MS)+        assertNotNull("title field never appeared", fields)+        fields!![0].click()+        fields[0].setText(title)+        device.findObject(By.desc(SAVE_DESCRIPTION))!!.click()+    }++    private fun ensureCalendar(device: UiDevice) {+        val create = device.wait(Until.findObject(By.text(CREATE_CALENDAR)), SHORT_TIMEOUT_MS) ?: return+        create.click()+        assertNotNull("calendar dialog missing", device.wait(Until.findObject(By.text(NEW_CALENDAR)), CONTENT_MS))+        val fields = device.wait(Until.findObjects(By.clazz(EDIT_TEXT_CLASS)), CONTENT_MS)+        assertNotNull("calendar name field never appeared", fields)+        fields!![0].click()+        fields[0].setText(CALENDAR_NAME)+        device.findObject(By.text(CONFIRM_CREATE))!!.click()+        assertNotNull("no agenda after calendar", device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_MS))+    }++    private fun grantAllRequestedPermissions(uiAutomation: UiAutomation, pm: PackageManager, pkg: String) {+        val info = pm.getPackageInfo(pkg, PackageManager.GET_PERMISSIONS)+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $pkg $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(pkg) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val CONTENT_MS = CONTENT_TIMEOUT_MS+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val SHORT_TIMEOUT_MS = 5_000L+        private const val AGENDA_TAB = "Agenda"+        private const val TITLE_LABEL = "Title"+        private const val ADD_DESCRIPTION = "Add"+        private const val EDIT_DESCRIPTION = "Edit"+        private const val SAVE_DESCRIPTION = "Save"+        private const val EDIT_TEXT_CLASS = "android.widget.EditText"+        private const val ORIGINAL_TITLE = "Journey Edit Me"+        private const val UPDATED_TITLE = "Journey Edited Title"+        private const val CREATE_CALENDAR = "Create a calendar"+        private const val NEW_CALENDAR = "New local calendar"+        private const val CALENDAR_NAME = "JourneyCal"+        private const val CONFIRM_CREATE = "Create"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarSettingsTest.kt
diff --git a/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarSettingsTest.kt b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarSettingsTest.ktnew file mode 100644index 0000000000..4bd21caec4--- /dev/null+++ b/calendar/src/androidTest/java/com/vayunmathur/calendar/ui/CalendarSettingsTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.calendar.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Journey: settings icon into Settings, preference rows visible, back to agenda.+ * UiDevice polling, not compose-test: Espresso idle-sync is broken on API 37.+ */+@RunWith(AndroidJUnit4::class)+class CalendarSettingsTest {++    @Test+    fun openSettings_preferencesVisible_backToAgenda() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "agenda view never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_TIMEOUT_MS),+        )+        val settings = device.wait(Until.findObject(By.desc(SETTINGS_DESCRIPTION)), CONTENT_TIMEOUT_MS)+        assertNotNull("settings entry never appeared", settings)+        settings!!.click()+        assertNotNull(+            "settings screen never opened",+            device.wait(Until.findObject(By.text(SETTINGS_TITLE)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "theme preference never appeared",+            device.wait(Until.findObject(By.text(THEME_ROW)), SHORT_TIMEOUT_MS),+        )+        assertNotNull(+            "default layout preference never appeared",+            device.wait(Until.findObject(By.text(LAYOUT_ROW)), SHORT_TIMEOUT_MS),+        )+        device.pressBack()+        assertNotNull(+            "did not return to agenda",+            device.wait(Until.findObject(By.text(AGENDA_TAB)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        val commands = info.requestedPermissions.orEmpty().map { "pm grant $packageName $it" } ++            SPECIAL_ACCESS_COMMANDS.map { it.format(packageName) }+        for (command in commands) {+            try {+                uiAutomation.executeShellCommand(command).close()+            } catch (ignored: Exception) {+                // Not grantable here; the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val SHORT_TIMEOUT_MS = 5_000L+        private const val AGENDA_TAB = "Agenda"+        private const val SETTINGS_DESCRIPTION = "Settings"+        private const val SETTINGS_TITLE = "Settings"+        private const val THEME_ROW = "Theme"+        private const val LAYOUT_ROW = "Default Layout"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
calendar/src/test/java/com/vayunmathur/calendar/ui/EventOverlapTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/EventOverlapTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/EventOverlapTest.ktnew file mode 100644index 0000000000..4e08108061--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/EventOverlapTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.calendar.ui++import com.vayunmathur.calendar.data.Instance+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atTime+import kotlinx.datetime.toInstant+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Overlap math in [computePositionedEventsForDay]: events that merely touch share no+ * column, nested and identical events do, and an overnight event is sliced at midnight.+ *+ * The zero-duration point-in-time case lives in EventPositionerTest and is not repeated.+ */+class EventOverlapTest {++    private val day = LocalDate(2026, 9, 22)+    private val zone = TimeZone.currentSystemDefault()++    private fun millis(minutes: Int): Long =+        day.atTime(minutes / 60, minutes % 60).toInstant(zone).toEpochMilliseconds()++    private fun event(id: Long, startMinutes: Int, endMinutes: Int): Instance =+        Instance(+            id = id,+            eventID = id,+            begin = millis(startMinutes),+            end = millis(endMinutes),+            timezone = zone.id,+            allDay = false,+            eventTitle = "Event $id",+            color = 0,+            rrule = null,+        )++    @Test+    fun `events that merely touch share no column`() {+        val first = event(1, 9 * 60, 10 * 60)+        val second = event(2, 10 * 60, 11 * 60)+        val positioned = computePositionedEventsForDay(listOf(first, second), day)+        assertEquals(2, positioned.size)+        positioned.forEach {+            assertEquals(1, it.totalColumns)+            assertEquals(0, it.columnIndex)+        }+    }++    @Test+    fun `nested events split into two columns`() {+        val outer = event(1, 9 * 60, 12 * 60)+        val inner = event(2, 10 * 60, 11 * 60)+        val positioned = computePositionedEventsForDay(listOf(outer, inner), day)+        assertEquals(2, positioned.size)+        assertTrue(positioned.all { it.totalColumns == 2 })+        assertEquals(setOf(0, 1), positioned.map { it.columnIndex }.toSet())+    }++    @Test+    fun `three pairwise overlaps need three columns`() {+        val events = listOf(+            event(1, 9 * 60, 10 * 60 + 30),+            event(2, 9 * 60 + 30, 11 * 60),+            event(3, 10 * 60, 10 * 60 + 30),+        )+        val positioned = computePositionedEventsForDay(events, day)+        assertEquals(3, positioned.size)+        assertTrue(positioned.all { it.totalColumns == 3 })+    }++    @Test+    fun `identical times share the width`() {+        val events = listOf(event(1, 9 * 60, 10 * 60), event(2, 9 * 60, 10 * 60))+        val positioned = computePositionedEventsForDay(events, day)+        assertEquals(2, positioned.size)+        assertTrue(positioned.all { it.totalColumns == 2 })+    }++    @Test+    fun `an overnight event is sliced at midnight`() {+        val next = LocalDate(2026, 9, 23)+        val overnight = Instance(+            id = 1,+            eventID = 1,+            begin = day.atTime(22, 0).toInstant(zone).toEpochMilliseconds(),+            end = next.atTime(2, 0).toInstant(zone).toEpochMilliseconds(),+            timezone = zone.id,+            allDay = false,+            eventTitle = "Night shift",+            color = 0,+            rrule = null,+        )+        val firstDay = computePositionedEventsForDay(listOf(overnight), day).single()+        assertEquals(22 * 60, firstDay.startMinutes)+        assertEquals(24 * 60, firstDay.endMinutes)+        val secondDay = computePositionedEventsForDay(listOf(overnight), next).single()+        assertEquals(0, secondDay.startMinutes)+        assertEquals(2 * 60, secondDay.endMinutes)+    }+}
calendar/src/test/java/com/vayunmathur/calendar/ui/IcsTextTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsTextTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsTextTest.ktnew file mode 100644index 0000000000..a6acf96d75--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/IcsTextTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.calendar.ui++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The small pure parsers behind ICS import: TEXT unescaping, VALARM TRIGGER to+ * minutes-before, offset sniffing, TZID extraction, and DURATION maths.+ *+ * None of these touch the provider or the clock, so they run as plain JVM tests.+ */+class IcsTextTest {++    @Test+    fun `escaped newlines become real ones`() {+        assertEquals("a\nb", unescapeIcsText("a\\nb"))+        assertEquals("a\nb", unescapeIcsText("a\\Nb"))+    }++    @Test+    fun `escaped separators and backslashes collapse`() {+        assertEquals("a,b;c\\d", unescapeIcsText("a\\,b\\;c\\\\d"))+    }++    @Test+    fun `plain text and a trailing backslash pass through`() {+        assertEquals("plain", unescapeIcsText("plain"))+        assertEquals("abc\\", unescapeIcsText("abc\\"))+    }++    @Test+    fun `a start-relative trigger becomes minutes before`() {+        assertEquals(15, parseTriggerMinutesBefore("-PT15M"))+        assertEquals(90, parseTriggerMinutesBefore("-PT1H30M"))+        assertEquals(0, parseTriggerMinutesBefore("PT0S"))+        assertEquals(1560, parseTriggerMinutesBefore("-P1DT2H"))+    }++    @Test+    fun `post-start and absolute triggers have no minutes-before`() {+        assertNull(parseTriggerMinutesBefore("PT15M"))+        assertNull(parseTriggerMinutesBefore("20250704T090000Z"))+        assertNull(parseTriggerMinutesBefore(""))+        assertNull(parseTriggerMinutesBefore("tomorrow"))+    }++    @Test+    fun `only the duration half before a semicolon counts`() {+        assertEquals(15, parseTriggerMinutesBefore("-PT15M;20250704T090000Z"))+    }++    @Test+    fun `offset sniffing ignores date dashes`() {+        assertTrue(hasExplicitOffset("20250704T090000+0200"))+        assertTrue(hasExplicitOffset("20250704T090000-0500"))+        assertFalse(hasExplicitOffset("20250704T090000Z"))+        assertFalse(hasExplicitOffset("2025-07-04T09:00:00"))+        assertFalse(hasExplicitOffset("2025-07-04"))+    }++    @Test+    fun `TZID extraction is case-insensitive on the key only`() {+        assertEquals("America/New_York", extractTZID("DTSTART;TZID=America/New_York"))+        assertEquals("UTC", extractTZID("dtstart;tzid=UTC"))+        assertNull(extractTZID("DTSTART;VALUE=DATE"))+        assertNull(extractTZID("DTSTART"))+    }++    @Test+    fun `a duration shifts the start or fails cleanly`() {+        assertEquals(3_600_000L + 1_000L, tryParseDurationMillis("PT1H", 1_000L))+        assertEquals(86_400_000L, tryParseDurationMillis("P1D", 0L))+        assertNull(tryParseDurationMillis("an hour", 0L))+    }+}
calendar/src/test/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDatesTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDatesTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDatesTest.ktnew file mode 100644index 0000000000..c0e9d8d230--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/ui/dialogs/RecurrenceDatesTest.kt@@ -0,0 +1,62 @@+package com.vayunmathur.calendar.ui.dialogs++import kotlinx.datetime.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Calendar maths behind the recurrence dialog: day-of-year, ISO week years of 52 versus+ * 53 weeks, week-number edges around New Year, and ordinal suffixes including the teens.+ */+class RecurrenceDatesTest {++    @Test+    fun `day of year counts from one`() {+        assertEquals(1, dayOfYear(LocalDate(2026, 1, 1)))+        assertEquals(59, dayOfYear(LocalDate(2025, 2, 28)))+        assertEquals(365, dayOfYear(LocalDate(2025, 12, 31)))+    }++    @Test+    fun `leap day shifts the rest of the year`() {+        assertEquals(60, dayOfYear(LocalDate(2024, 2, 29)))+        assertEquals(61, dayOfYear(LocalDate(2024, 3, 1)))+        assertEquals(366, dayOfYear(LocalDate(2024, 12, 31)))+    }++    @Test+    fun `years starting Thursday or leap Wednesday have 53 weeks`() {+        assertEquals(53, isoWeeksInYear(2015))+        assertEquals(53, isoWeeksInYear(2020))+        assertEquals(53, isoWeeksInYear(2026))+        assertEquals(52, isoWeeksInYear(2021))+        assertEquals(52, isoWeeksInYear(2025))+    }++    @Test+    fun `week numbers wrap at both ends of the year`() {+        assertEquals(1, isoWeekNumber(LocalDate(2026, 1, 1)))+        assertEquals(1, isoWeekNumber(LocalDate(2024, 12, 30)))+        assertEquals(1, isoWeekNumber(LocalDate(2025, 12, 29)))+        assertEquals(52, isoWeekNumber(LocalDate(2025, 12, 28)))+        assertEquals(53, isoWeekNumber(LocalDate(2026, 12, 31)))+        assertEquals(29, isoWeekNumber(LocalDate(2026, 7, 15)))+    }++    @Test+    fun `ordinals handle one two three and the teens`() {+        assertEquals("1st", ordinal(1))+        assertEquals("2nd", ordinal(2))+        assertEquals("3rd", ordinal(3))+        assertEquals("4th", ordinal(4))+        assertEquals("11th", ordinal(11))+        assertEquals("12th", ordinal(12))+        assertEquals("13th", ordinal(13))+        assertEquals("21st", ordinal(21))+        assertEquals("22nd", ordinal(22))+        assertEquals("23rd", ordinal(23))+        assertEquals("111th", ordinal(111))+        assertEquals("112th", ordinal(112))+        assertEquals("113th", ordinal(113))+    }+}
calendar/src/test/java/com/vayunmathur/calendar/util/IcalInstantTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/IcalInstantTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/IcalInstantTest.ktnew file mode 100644index 0000000000..ff39f37a19--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/IcalInstantTest.kt@@ -0,0 +1,60 @@+package com.vayunmathur.calendar.util++import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toInstant+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Millis-based ICS formatting cross-checked against java.time: the UTC instant form,+ * the zone wall-time form, and the winter/summer offset split across a DST boundary.+ *+ * The LocalDate-based writers live in DateFormatsTest; only the millis overloads are+ * covered here.+ */+class IcalInstantTest {++    private val utcFormat = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'")+        .withZone(ZoneId.of("UTC"))++    private fun millis(year: Int, month: Int, day: Int, hour: Int, minute: Int): Long {+        val zone = TimeZone.of("America/New_York")+        return LocalDateTime(year, month, day, hour, minute).toInstant(zone).toEpochMilliseconds()+    }++    @Test+    fun `the epoch formats as the ICS origin`() {+        assertEquals("19700101T000000Z", icalUtcDateTime(0))+    }++    @Test+    fun `a UTC instant matches java time`() {+        val at = millis(2026, 1, 15, 9, 0)+        val expected = utcFormat.format(java.time.Instant.ofEpochMilli(at))+        assertEquals(expected, icalUtcDateTime(at))+    }++    @Test+    fun `the wall form keeps the zone-local clock time`() {+        val at = millis(2026, 7, 15, 9, 0)+        val wall = icalLocalDateTime(at, TimeZone.of("America/New_York"))+        assertEquals("20260715T090000", wall)+    }++    @Test+    fun `summer and winter share a wall time but not an instant`() {+        assertEquals("20260715T130000Z", icalUtcDateTime(millis(2026, 7, 15, 9, 0)))+        assertEquals("20260115T140000Z", icalUtcDateTime(millis(2026, 1, 15, 9, 0)))+    }++    @Test+    fun `a late evening maps onto the next UTC day`() {+        val at = millis(2026, 7, 4, 22, 0)+        assertEquals("20260705T020000Z", icalUtcDateTime(at))+        val wall = icalLocalDateTime(at, TimeZone.of("America/New_York"))+        assertEquals("20260704T220000", wall)+    }+}
calendar/src/test/java/com/vayunmathur/calendar/util/RRuleEdgeTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleEdgeTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleEdgeTest.ktnew file mode 100644index 0000000000..81e328f33c--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/RRuleEdgeTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.calendar.util++import kotlinx.datetime.DayOfWeek+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Rejects and clamps in [RRule.parse] plus emission edges in [RRule.asString].+ *+ * The happy-path shapes live in RRuleTest; everything here is input the parser must+ * refuse (blank, missing FREQ, unknown frequency, malformed pairs, bad UNTIL) or+ * normalise (non-positive INTERVAL, out-of-range COUNT).+ */+class RRuleEdgeTest {++    private val zone = TimeZone.UTC++    @Test+    fun `blank input has no rule`() {+        assertNull(RRule.parse("", zone))+        assertNull(RRule.parse("   ", zone))+    }++    @Test+    fun `a rule without FREQ is refused`() {+        assertNull(RRule.parse("INTERVAL=2;COUNT=5", zone))+    }++    @Test+    fun `an unsupported frequency is refused`() {+        assertNull(RRule.parse("FREQ=HOURLY;INTERVAL=1", zone))+    }++    @Test+    fun `a malformed pair poisons the whole rule`() {+        assertNull(RRule.parse("FREQ=DAILY;INTERVAL", zone))+    }++    @Test+    fun `a bad UNTIL refuses the rule instead of guessing`() {+        assertNull(RRule.parse("FREQ=DAILY;UNTIL=not-a-date", zone))+    }++    @Test+    fun `a non-positive INTERVAL falls back to one`() {+        val zero = RRule.parse("FREQ=DAILY;INTERVAL=0", zone) as RRule.EveryXDays+        assertEquals(1, zero.days)+        val negative = RRule.parse("FREQ=WEEKLY;INTERVAL=-3;BYDAY=MO", zone)+        assertEquals(1, (negative as RRule.EveryXWeeks).weeks)+        val garbage = RRule.parse("FREQ=DAILY;INTERVAL=often", zone) as RRule.EveryXDays+        assertEquals(1, garbage.days)+    }++    @Test+    fun `COUNT is clamped into range`() {+        val low = RRule.parse("FREQ=DAILY;COUNT=0", zone) as RRule.EveryXDays+        assertEquals(RRule.EndCondition.Count(1), low.endCondition)+        val high = RRule.parse("FREQ=DAILY;COUNT=5000", zone) as RRule.EveryXDays+        assertEquals(RRule.EndCondition.Count(MAX_RRULE_COUNT), high.endCondition)+        val garbage = RRule.parse("FREQ=DAILY;COUNT=many", zone) as RRule.EveryXDays+        assertEquals(RRule.EndCondition.Count(1), garbage.endCondition)+    }++    @Test+    fun `COUNT wins when both end conditions are present`() {+        val rule = RRule.parse("FREQ=DAILY;COUNT=3;UNTIL=20260315", zone) as RRule.EveryXDays+        assertEquals(RRule.EndCondition.Count(3), rule.endCondition)+    }++    @Test+    fun `a date-only UNTIL parses to that day`() {+        val rule = RRule.parse("FREQ=DAILY;UNTIL=20260315", zone) as RRule.EveryXDays+        assertEquals(RRule.EndCondition.Until(LocalDate(2026, 3, 15)), rule.endCondition)+    }++    @Test+    fun `the RRULE prefix form parses like the bare form`() {+        val rule = RRule.parse("RRULE:FREQ=DAILY;INTERVAL=2", zone) as RRule.EveryXDays+        assertEquals(2, rule.days)+    }++    @Test+    fun `a weekly rule with no days omits BYDAY`() {+        val text = RRule.EveryXWeeks(1, emptyList(), RRule.EndCondition.Never)+            .asString(LocalDate(2026, 7, 20), zone)+        assertEquals("FREQ=WEEKLY;INTERVAL=1", text)+    }++    @Test+    fun `a monthly rule with plain day names stays type zero`() {+        val rule = RRule.parse("FREQ=MONTHLY;BYDAY=MO,WE", zone)+        assertTrue(rule is RRule.EveryXMonths)+        assertEquals(0, rule.typeE)+        assertEquals(listOf(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY), rule.byDay)+    }+}
calendar/src/test/java/com/vayunmathur/calendar/util/RecurrenceParamsTest.kt
diff --git a/calendar/src/test/java/com/vayunmathur/calendar/util/RecurrenceParamsTest.kt b/calendar/src/test/java/com/vayunmathur/calendar/util/RecurrenceParamsTest.ktnew file mode 100644index 0000000000..e60d7cb14a--- /dev/null+++ b/calendar/src/test/java/com/vayunmathur/calendar/util/RecurrenceParamsTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.calendar.util++import kotlinx.datetime.DayOfWeek+import kotlinx.datetime.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull++/**+ * [RecurrenceParams.fromRRule] must map every [RRule] shape back to the dialog model:+ * the frequency word, the interval, the weekly days, the monthly kind, the end+ * condition, and the advanced BY lists plus WKST.+ */+class RecurrenceParamsTest {++    @Test+    fun `null has no params`() {+        assertNull(RecurrenceParams.fromRRule(null))+    }++    @Test+    fun `daily maps to days with its count`() {+        val params = RecurrenceParams.fromRRule(+            RRule.EveryXDays(3, RRule.EndCondition.Count(4)),+        )+        assertEquals("days", params?.freq)+        assertEquals(3, params?.interval)+        assertEquals(RRule.EndCondition.Count(4), params?.endCondition)+    }++    @Test+    fun `weekly keeps the selected days`() {+        val days = listOf(DayOfWeek.MONDAY, DayOfWeek.FRIDAY)+        val params = RecurrenceParams.fromRRule(+            RRule.EveryXWeeks(2, days, RRule.EndCondition.Never),+        )+        assertEquals("weeks", params?.freq)+        assertEquals(2, params?.interval)+        assertEquals(days, params?.daysOfWeek)+    }++    @Test+    fun `monthly keeps the monthly kind`() {+        val params = RecurrenceParams.fromRRule(+            RRule.EveryXMonths(1, 2, RRule.EndCondition.Never),+        )+        assertEquals("months", params?.freq)+        assertEquals(2, params?.monthlyType)+    }++    @Test+    fun `yearly keeps its until`() {+        val until = RRule.EndCondition.Until(LocalDate(2026, 12, 31))+        val params = RecurrenceParams.fromRRule(RRule.EveryXYears(5, until))+        assertEquals("years", params?.freq)+        assertEquals(5, params?.interval)+        assertEquals(until, params?.endCondition)+    }++    @Test+    fun `advanced BY lists and WKST survive`() {+        val rule = RRule.EveryXDays(+            days = 1,+            endCondition = RRule.EndCondition.Never,+            byMonthDay = listOf(1, -1),+            byMonth = listOf(6),+            bySetPos = listOf(1),+            byYearDay = listOf(100),+            byWeekNo = listOf(26),+            wkst = DayOfWeek.SUNDAY,+        )+        val params = RecurrenceParams.fromRRule(rule)+        assertEquals(listOf(1, -1), params?.byMonthDay)+        assertEquals(listOf(6), params?.byMonth)+        assertEquals(listOf(1), params?.bySetPos)+        assertEquals(listOf(100), params?.byYearDay)+        assertEquals(listOf(26), params?.byWeekNo)+        assertEquals(DayOfWeek.SUNDAY, params?.wkst)+    }+}
clock/src/test/java/com/vayunmathur/clock/pure/AlarmNextFireTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/AlarmNextFireTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/AlarmNextFireTest.ktnew file mode 100644index 0000000000..677aa390d6--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/AlarmNextFireTest.kt@@ -0,0 +1,185 @@+package com.vayunmathur.clock.pure++import java.time.DayOfWeek+import java.time.LocalDate+import java.time.LocalTime+import java.time.ZoneId+import java.time.ZonedDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Pins the alarm next-fire computation: repeat-day bitmask, one-shot+ * fallback, week wrap-around and daylight-saving edges.+ *+ * Mirrors platform/AlarmScheduler's wall-clock semantics (bit 0 is+ * Sunday, days == 0 is a one-shot) using java.time so the host JVM can+ * run it with explicit zones instead of the device default.+ */+class AlarmNextFireTest {+    private val utc = ZoneId.of("UTC")+    private val newYork = ZoneId.of("America/New_York")++    private fun maskOf(vararg days: DayOfWeek): Int {+        var mask = 0+        for (day in days) {+            val bit = if (day == DayOfWeek.SUNDAY) 0 else day.value+            mask = mask or (1 shl bit)+        }+        return mask+    }++    private fun nextFire(+        now: ZonedDateTime,+        alarmTime: LocalTime,+        daysMask: Int,+    ): ZonedDateTime? {+        var candidate = ZonedDateTime.of(now.toLocalDate(), alarmTime, now.zone)+        if (!candidate.isAfter(now)) candidate = candidate.plusDays(1)+        if (daysMask == 0) return candidate+        repeat(7) {+            val bit = if (candidate.dayOfWeek == DayOfWeek.SUNDAY) 0 else candidate.dayOfWeek.value+            if ((daysMask and (1 shl bit)) != 0) return candidate+            candidate = candidate.plusDays(1)+        }+        return null+    }++    private fun at(date: LocalDate, time: LocalTime, zone: ZoneId): ZonedDateTime =+        ZonedDateTime.of(date, time, zone)++    @Test+    fun oneShotLaterTodayFiresToday() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        val fire = nextFire(now, LocalTime.of(9, 0), 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 1), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun oneShotEarlierTodayFiresTomorrow() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(10, 0), utc)+        val fire = nextFire(now, LocalTime.of(9, 0), 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 2), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun oneShotAtExactNowFiresTomorrow() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(9, 0), utc)+        val fire = nextFire(now, LocalTime.of(9, 0), 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 2), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun recurringTodaySelectedFiresToday() {+        val monday = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        assertEquals(DayOfWeek.MONDAY, monday.dayOfWeek)+        val fire = nextFire(monday, LocalTime.of(9, 0), maskOf(DayOfWeek.MONDAY))!!+        assertEquals(at(LocalDate.of(2026, 6, 1), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun recurringTodayPassedAdvancesToNextSelectedDay() {+        val monday = at(LocalDate.of(2026, 6, 1), LocalTime.of(10, 0), utc)+        val mask = maskOf(DayOfWeek.MONDAY, DayOfWeek.WEDNESDAY)+        val fire = nextFire(monday, LocalTime.of(9, 0), mask)!!+        assertEquals(at(LocalDate.of(2026, 6, 3), LocalTime.of(9, 0), utc), fire)+        assertEquals(DayOfWeek.WEDNESDAY, fire.dayOfWeek)+    }++    @Test+    fun recurringWrapsAcrossWeekBoundary() {+        val saturday = at(LocalDate.of(2026, 6, 6), LocalTime.of(10, 0), utc)+        assertEquals(DayOfWeek.SATURDAY, saturday.dayOfWeek)+        val fire = nextFire(saturday, LocalTime.of(9, 0), maskOf(DayOfWeek.SUNDAY))!!+        assertEquals(at(LocalDate.of(2026, 6, 7), LocalTime.of(9, 0), utc), fire)+        assertEquals(DayOfWeek.SUNDAY, fire.dayOfWeek)+    }++    @Test+    fun allDaysBehavesLikeDaily() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(10, 0), utc)+        val fire = nextFire(now, LocalTime.of(9, 0), 0x7F)!!+        assertEquals(at(LocalDate.of(2026, 6, 2), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun sundayBitZeroMapsToSunday() {+        val monday = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        val fire = nextFire(monday, LocalTime.of(9, 0), 1 shl 0)!!+        assertEquals(DayOfWeek.SUNDAY, fire.dayOfWeek)+        assertEquals(LocalDate.of(2026, 6, 7), fire.toLocalDate())+    }++    @Test+    fun saturdayBitSixMapsToSaturday() {+        val monday = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        val fire = nextFire(monday, LocalTime.of(9, 0), 1 shl 6)!!+        assertEquals(DayOfWeek.SATURDAY, fire.dayOfWeek)+        assertEquals(LocalDate.of(2026, 6, 6), fire.toLocalDate())+    }++    @Test+    fun invalidMaskWithOnlyHighBitsReturnsNull() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        assertNull(nextFire(now, LocalTime.of(9, 0), 1 shl 9))+    }++    @Test+    fun mixedValidAndHighBitsStillMatchesValidDay() {+        val monday = at(LocalDate.of(2026, 6, 1), LocalTime.of(8, 0), utc)+        val mask = maskOf(DayOfWeek.MONDAY) or (1 shl 12)+        val fire = nextFire(monday, LocalTime.of(9, 0), mask)!!+        assertEquals(at(LocalDate.of(2026, 6, 1), LocalTime.of(9, 0), utc), fire)+    }++    @Test+    fun midnightAlarmJustBeforeMidnightFiresOneMinuteLater() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(23, 59), utc)+        val fire = nextFire(now, LocalTime.MIDNIGHT, 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 2), LocalTime.MIDNIGHT, utc), fire)+    }++    @Test+    fun noonAndMidnightAreDistinctFires() {+        val now = at(LocalDate.of(2026, 6, 1), LocalTime.of(0, 1), utc)+        val noon = nextFire(now, LocalTime.NOON, 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 1), LocalTime.NOON, utc), noon)+        val midnight = nextFire(now, LocalTime.MIDNIGHT, 0)!!+        assertEquals(at(LocalDate.of(2026, 6, 2), LocalTime.MIDNIGHT, utc), midnight)+    }++    @Test+    fun springForwardGapResolvesForwardWithoutThrowing() {+        val eve = at(LocalDate.of(2026, 3, 7), LocalTime.of(10, 0), newYork)+        val fire = nextFire(eve, LocalTime.of(2, 30), 0)!!+        assertEquals(LocalDate.of(2026, 3, 8), fire.toLocalDate())+        assertTrue(fire.toInstant().isAfter(eve.toInstant()), "gap fire must be in the future")+        assertEquals("-04:00", fire.offset.id)+    }++    @Test+    fun fallBackOverlapUsesEarlierOffsetByDefault() {+        val morning = at(LocalDate.of(2026, 11, 1), LocalTime.of(0, 30), newYork)+        val fire = nextFire(morning, LocalTime.of(1, 30), 0)!!+        assertEquals(LocalTime.of(1, 30), fire.toLocalTime())+        assertEquals("-04:00", fire.offset.id)+    }++    @Test+    fun dailyAcrossSpringForwardIs23Hours() {+        val before = at(LocalDate.of(2026, 3, 7), LocalTime.of(9, 0), newYork)+        val fire = nextFire(before, LocalTime.of(9, 0), 0x7F)!!+        val hours = java.time.Duration.between(before.toInstant(), fire.toInstant()).toHours()+        assertEquals(23L, hours)+    }++    @Test+    fun dailyAcrossFallBackIs25Hours() {+        val before = at(LocalDate.of(2026, 10, 31), LocalTime.of(9, 0), newYork)+        val fire = nextFire(before, LocalTime.of(9, 0), 0x7F)!!+        val hours = java.time.Duration.between(before.toInstant(), fire.toInstant()).toHours()+        assertEquals(25L, hours)+    }+}
clock/src/test/java/com/vayunmathur/clock/pure/CityDataTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/CityDataTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/CityDataTest.ktnew file mode 100644index 0000000000..d0d19c8e2c--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/CityDataTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.clock.pure++import java.time.ZoneId+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pins the world-clock city list integrity: newline-joined storage,+ * add/remove toggling, order preservation and IANA zone validation.+ *+ * Mirrors platform/WorldClockCities' encode/decode/toggle semantics+ * (commas are legal inside names, blank lines are dropped) using only+ * Kotlin and java.time so the host JVM can run it.+ */+class CityDataTest {+    private fun encode(cities: List<String>): String = cities.joinToString("\n")++    private fun decode(stored: String?): List<String> =+        stored?.split('\n')?.filter { it.isNotBlank() }.orEmpty()++    private fun toggle(cities: List<String>, city: String): List<String> =+        if (city in cities) cities - city else cities + city++    private fun isValidZone(id: String): Boolean =+        try {+            ZoneId.of(id)+            true+        } catch (_: Exception) {+            false+        }++    @Test+    fun emptyListEncodesToEmptyString() {+        assertEquals("", encode(emptyList()))+    }++    @Test+    fun nullStoredDecodesToEmptyList() {+        assertEquals(emptyList(), decode(null))+    }++    @Test+    fun emptyStringDecodesToEmptyList() {+        assertEquals(emptyList(), decode(""))+    }++    @Test+    fun blankLinesAreFilteredOnDecode() {+        assertEquals(listOf("Paris", "Tokyo"), decode("Paris\n\nTokyo\n   \n"))+    }++    @Test+    fun commasInCityNamesSurviveRoundTrip() {+        val cities = listOf("New York, USA", "Paris, France")+        assertEquals(cities, decode(encode(cities)))+    }++    @Test+    fun orderIsPreservedThroughRoundTrip() {+        val cities = listOf("Tokyo", "Paris", "New York, USA")+        assertEquals(cities, decode(encode(cities)))+    }++    @Test+    fun toggleAddsMissingCityAtEnd() {+        assertEquals(listOf("Paris", "Tokyo"), toggle(listOf("Paris"), "Tokyo"))+    }++    @Test+    fun toggleRemovesExistingCityKeepsOrder() {+        assertEquals(listOf("Paris", "Tokyo"), toggle(listOf("Paris", "Lima", "Tokyo"), "Lima"))+    }++    @Test+    fun toggleTwiceRestoresOriginal() {+        val start = listOf("Paris", "Tokyo")+        assertEquals(start, toggle(toggle(start, "Lima"), "Lima"))+    }++    @Test+    fun legacyMigrationSortsAlphabetically() {+        val legacy = setOf("Tokyo", "Paris", "Lima")+        assertEquals(listOf("Lima", "Paris", "Tokyo"), legacy.sorted())+    }++    @Test+    fun invalidZoneIdIsRejected() {+        assertFalse(isValidZone("Not/AZone"))+    }++    @Test+    fun blankZoneIdIsRejected() {+        assertFalse(isValidZone(""))+    }++    @Test+    fun lowerCaseZoneIdIsRejected() {+        assertFalse(isValidZone("europe/paris"))+    }++    @Test+    fun utcAndFixedOffsetsAreValid() {+        assertTrue(isValidZone("UTC"))+        assertTrue(isValidZone("Europe/Paris"))+        assertTrue(isValidZone("America/New_York"))+        assertTrue(isValidZone("+05:30"))+    }++    @Test+    fun largeCityListRoundTrips() {+        val cities = (1..100).map { "City $it" }+        assertEquals(cities, decode(encode(cities)))+    }++    @Test+    fun whitespaceOnlyEntriesAreDropped() {+        assertEquals(listOf("Paris"), decode("   \nParis\n\t\n"))+    }+}
clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.ktnew file mode 100644index 0000000000..16bc84c19e--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/StopwatchStateTest.kt@@ -0,0 +1,132 @@+package com.vayunmathur.clock.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Duration+import kotlin.time.Duration.Companion.hours+import kotlin.time.Duration.Companion.milliseconds+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import kotlin.time.Instant++/**+ * Pins the stopwatch state machine: live counting, pause accumulation,+ * reset clearing and cumulative-lap splits.+ *+ * Mirrors the ViewModel's stopwatchCountingTime combine plus the+ * notification receiver's toggle/lap persistence rules, reduced to pure+ * kotlin.time functions over (running, total, start, now).+ */+class StopwatchStateTest {+    private val base = Instant.fromEpochMilliseconds(2_000_000L)++    private fun counting(running: Boolean, total: Duration, start: Instant, now: Instant): Duration =+        if (running) total + (now - start) else total++    private fun pauseTotal(total: Duration, start: Instant, now: Instant): Duration =+        total + (now - start)++    private fun lapIfRunning(+        running: Boolean,+        total: Duration,+        start: Instant,+        now: Instant,+        laps: List<Duration>,+    ): List<Duration> = if (!running) laps else laps + counting(running, total, start, now)++    private fun splits(laps: List<Duration>): List<Duration> {+        val out = mutableListOf<Duration>()+        var previous = Duration.ZERO+        for (lap in laps) {+            out += lap - previous+            previous = lap+        }+        return out+    }++    @Test+    fun stoppedStopwatchShowsStoredTotal() {+        assertEquals(90.seconds, counting(false, 90.seconds, base, base + 60.seconds))+    }++    @Test+    fun runningStopwatchAddsLiveDelta() {+        assertEquals(100.seconds, counting(true, 90.seconds, base, base + 10.seconds))+    }++    @Test+    fun pauseAccumulatesElapsedIntoTotal() {+        assertEquals(15.seconds, pauseTotal(10.seconds, base, base + 5.seconds))+    }++    @Test+    fun resumeContinuesFromPausedTotal() {+        val paused = pauseTotal(10.seconds, base, base + 5.seconds)+        val resumedStart = base + 1_000.seconds+        assertEquals(20.seconds, counting(true, paused, resumedStart, resumedStart + 5.seconds))+    }++    @Test+    fun resetClearsTotalAndLaps() {+        assertEquals(Duration.ZERO, counting(false, Duration.ZERO, base, base + 50.seconds))+        assertEquals(emptyList(), splits(emptyList()))+    }++    @Test+    fun emptyLapsHaveNoSplits() {+        assertEquals(emptyList(), splits(emptyList()))+    }++    @Test+    fun lapsAreMonotonicNonDecreasing() {+        val laps = listOf(10.seconds, 10.seconds, 25.seconds, 60.seconds)+        for (index in 1 until laps.size) {+            assertTrue(laps[index] >= laps[index - 1], "lap $index went backwards")+        }+    }++    @Test+    fun lapSplitsSumToLastCumulativeTime() {+        val laps = listOf(10.seconds, 25.seconds, 45.seconds)+        val total = splits(laps).fold(Duration.ZERO) { acc, split -> acc + split }+        assertEquals(45.seconds, total)+    }++    @Test+    fun lapWhilePausedIsIgnored() {+        val laps = listOf(10.seconds)+        val kept = lapIfRunning(false, 10.seconds, base, base + 5.seconds, laps)+        assertEquals(laps, kept)+    }++    @Test+    fun lapWhileRunningAppendsCountingTime() {+        val laps = lapIfRunning(true, 10.seconds, base, base + 5.seconds, emptyList())+        assertEquals(listOf(15.seconds), laps)+    }++    @Test+    fun centisecondBoundaryAt99Vs100Millis() {+        assertEquals(99.milliseconds, counting(true, Duration.ZERO, base, base + 99.milliseconds))+        assertEquals(100.milliseconds, counting(true, Duration.ZERO, base, base + 100.milliseconds))+    }++    @Test+    fun zeroTotalAtEpochStart() {+        val epoch = Instant.fromEpochMilliseconds(0)+        assertEquals(7.seconds, counting(true, Duration.ZERO, epoch, epoch + 7.seconds))+    }++    @Test+    fun longRunOverTenHoursCountsCorrectly() {+        assertEquals(10.hours, counting(true, 9.hours, base, base + 1.hours))+        assertEquals(10.hours, counting(false, 10.hours, base, base + 5.hours))+    }++    @Test+    fun consecutiveLapsProduceCorrectSplits() {+        val laps = listOf(10.seconds, 30.seconds, 31.minutes)+        assertEquals(listOf(10.seconds, 20.seconds, 30.minutes), splits(laps))+    }+}
clock/src/test/java/com/vayunmathur/clock/pure/TimerStateTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/TimerStateTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/TimerStateTest.ktnew file mode 100644index 0000000000..9cac2a89bb--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/TimerStateTest.kt@@ -0,0 +1,130 @@+package com.vayunmathur.clock.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.time.Duration+import kotlin.time.Duration.Companion.hours+import kotlin.time.Duration.Companion.milliseconds+import kotlin.time.Duration.Companion.minutes+import kotlin.time.Duration.Companion.seconds+import kotlin.time.Instant++/**+ * Pins the countdown-timer state machine: remaining-time math, pause /+ * resume / reset transitions and the finished-timer restart rule.+ *+ * Mirrors platform/ClockUiContract.timerRemaining and the notification+ * receivers' pause-resume-reset semantics with kotlin.time so the host+ * JVM can run it without any device or database.+ */+class TimerStateTest {+    private val base = Instant.fromEpochMilliseconds(1_000_000L)++    private fun remaining(+        isRunning: Boolean,+        length: Duration,+        start: Instant,+        now: Instant,+    ): Duration {+        val raw = if (isRunning) length - (now - start) else length+        return raw.coerceAtLeast(Duration.ZERO)+    }++    private fun addMinute(length: Duration): Duration = length + 60.seconds++    @Test+    fun pausedTimerIgnoresWallClock() {+        val later = base + 30.seconds+        assertEquals(5.minutes, remaining(false, 5.minutes, base, later))+    }++    @Test+    fun runningTimerSubtractsElapsed() {+        val now = base + 90.seconds+        assertEquals(30.seconds, remaining(true, 2.minutes, base, now))+    }++    @Test+    fun elapsedExactlyEqualsLengthGivesZero() {+        val now = base + 60.seconds+        assertEquals(Duration.ZERO, remaining(true, 60.seconds, base, now))+    }++    @Test+    fun elapsedBeyondLengthClampsToZero() {+        val now = base + 120.seconds+        assertEquals(Duration.ZERO, remaining(true, 60.seconds, base, now))+    }++    @Test+    fun zeroLengthStaysZeroWhenRunning() {+        val now = base + 5.seconds+        assertEquals(Duration.ZERO, remaining(true, Duration.ZERO, base, now))+    }++    @Test+    fun pauseFreezesRemainingAcrossLaterReads() {+        val pausedAt = base + 20.seconds+        val frozen = remaining(true, 60.seconds, base, pausedAt)+        assertEquals(40.seconds, frozen)+        assertEquals(frozen, remaining(false, frozen, base, pausedAt + 300.seconds))+    }++    @Test+    fun resumeRestartsClockFromSameRemaining() {+        val frozen = 40.seconds+        val resumedAt = base + 1_000.seconds+        assertEquals(30.seconds, remaining(true, frozen, resumedAt, resumedAt + 10.seconds))+    }++    @Test+    fun resetRestoresTotalLength() {+        val total = 10.minutes+        val partlyElapsed = remaining(true, 10.minutes, base, base + 9.minutes)+        assertEquals(1.minutes, partlyElapsed)+        assertEquals(total, remaining(false, total, base, base + 9.minutes))+    }++    @Test+    fun addMinuteAddsSixtySecondsWhenPaused() {+        assertEquals(6.minutes, addMinute(5.minutes))+    }++    @Test+    fun addMinuteShiftsFinishLaterWhenRunning() {+        val length = addMinute(5.minutes)+        assertEquals(5.minutes, remaining(true, length, base, base + 1.minutes))+    }++    @Test+    fun oneMillisecondBeforeFinishLeavesOneMillisecond() {+        val now = base + 59_999.milliseconds+        assertEquals(1.milliseconds, remaining(true, 60.seconds, base, now))+    }++    @Test+    fun futureStartTimeNeverShrinksBelowStoredLength() {+        val startInFuture = base + 10.seconds+        val shown = remaining(true, 60.seconds, startInFuture, base)+        assertTrue(shown >= 60.seconds, "lead time must not shrink the display")+    }++    @Test+    fun negativeStoredLengthCoercesToZero() {+        assertEquals(Duration.ZERO, remaining(false, (-5).seconds, base, base))+        assertEquals(Duration.ZERO, remaining(true, (-5).seconds, base, base + 1.seconds))+    }++    @Test+    fun largeDurationArithmeticStaysExact() {+        val now = base + 1.hours+        assertEquals(98.hours, remaining(true, 99.hours, base, now))+    }++    @Test+    fun emptyNameAndZeroTotalIsAlreadyFinished() {+        assertEquals(Duration.ZERO, remaining(false, Duration.ZERO, base, base))+        assertEquals(Duration.ZERO, remaining(true, Duration.ZERO, base, base + 1.hours))+    }+}
clock/src/test/java/com/vayunmathur/clock/pure/WorldClockOffsetTest.kt
diff --git a/clock/src/test/java/com/vayunmathur/clock/pure/WorldClockOffsetTest.kt b/clock/src/test/java/com/vayunmathur/clock/pure/WorldClockOffsetTest.ktnew file mode 100644index 0000000000..9371e578b9--- /dev/null+++ b/clock/src/test/java/com/vayunmathur/clock/pure/WorldClockOffsetTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.clock.pure++import java.time.Instant+import java.time.LocalDate+import java.time.LocalTime+import java.time.ZoneId+import java.time.ZonedDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/**+ * Pins world-clock offset math: one instant rendered across zones,+ * half-hour offsets, daylight-saving shifts and date-line crossings.+ *+ * Uses java.time only, with fixed instants so the results never depend+ * on the machine running the test.+ */+class WorldClockOffsetTest {+    private val summerNoonUtc = Instant.parse("2026-06-01T12:00:00Z")+    private val winterNoonUtc = Instant.parse("2026-01-15T12:00:00Z")++    private fun localIn(instant: Instant, zone: String): ZonedDateTime =+        instant.atZone(ZoneId.of(zone))++    @Test+    fun sameInstantShowsDifferentLocalTimes() {+        assertEquals(LocalTime.of(8, 0), localIn(summerNoonUtc, "America/New_York").toLocalTime())+        assertEquals(LocalTime.of(21, 0), localIn(summerNoonUtc, "Asia/Tokyo").toLocalTime())+    }++    @Test+    fun newYorkAndLondonDifferByFiveHoursInSummer() {+        val newYork = localIn(summerNoonUtc, "America/New_York")+        val london = localIn(summerNoonUtc, "Europe/London")+        val gapHours = (london.offset.totalSeconds - newYork.offset.totalSeconds) / 3600+        assertEquals(5, gapHours)+    }++    @Test+    fun kathmanduHalfHourOffsetIs5Hours45Minutes() {+        val zone = ZoneId.of("Asia/Kathmandu")+        val offsetSeconds = zone.rules.getOffset(summerNoonUtc).totalSeconds+        assertEquals((5 * 3600) + 45 * 60, offsetSeconds)+        assertEquals(LocalTime.of(17, 45), localIn(summerNoonUtc, "Asia/Kathmandu").toLocalTime())+    }++    @Test+    fun sydneyGainsOneHourInDaylightSaving() {+        val january = localIn(winterNoonUtc, "Australia/Sydney").offset.totalSeconds+        val june = localIn(summerNoonUtc, "Australia/Sydney").offset.totalSeconds+        assertEquals(3600, january - june)+    }++    @Test+    fun dateLineCitiesFallOnDifferentCalendarDates() {+        val christmas = localIn(summerNoonUtc, "Pacific/Kiritimati")+        val midway = localIn(summerNoonUtc, "Pacific/Midway")+        assertEquals(LocalDate.of(2026, 6, 2), christmas.toLocalDate())+        assertEquals(LocalDate.of(2026, 6, 1), midway.toLocalDate())+        val gapHours = (christmas.offset.totalSeconds - midway.offset.totalSeconds) / 3600+        assertEquals(25, gapHours)+    }++    @Test+    fun midnightUtcSplitsCalendarDates() {+        val night = Instant.parse("2026-06-01T00:30:00Z")+        assertEquals(LocalDate.of(2026, 6, 1), localIn(night, "Europe/Paris").toLocalDate())+        assertEquals(LocalDate.of(2026, 5, 31), localIn(night, "America/New_York").toLocalDate())+    }++    @Test+    fun springForwardSkipsHalfPastTwo() {+        val zone = ZoneId.of("America/New_York")+        val resolved = ZonedDateTime.of(LocalDate.of(2026, 3, 8), LocalTime.of(2, 30), zone)+        assertEquals(LocalTime.of(3, 30), resolved.toLocalTime())+    }++    @Test+    fun fallBackRepeatsHalfPastOneWithTwoOffsets() {+        val zone = ZoneId.of("America/New_York")+        val first = ZonedDateTime.of(LocalDate.of(2026, 11, 1), LocalTime.of(1, 30), zone)+        val second = first.withLaterOffsetAtOverlap()+        assertEquals(first.toLocalTime(), second.toLocalTime())+        assertTrue(first.offset != second.offset, "overlap must offer two offsets")+        assertEquals(3600, second.toEpochSecond() - first.toEpochSecond())+    }++    @Test+    fun invalidZoneIdThrows() {+        assertFailsWith<Exception> { ZoneId.of("Not/AZone") }+    }++    @Test+    fun blankZoneIdThrows() {+        assertFailsWith<Exception> { ZoneId.of("") }+    }++    @Test+    fun utcOffsetIsZero() {+        assertEquals(0, ZoneId.of("UTC").rules.getOffset(summerNoonUtc).totalSeconds)+    }++    @Test+    fun fixedOffsetMatchesNamedZoneInWinter() {+        val kolkata = ZoneId.of("Asia/Kolkata").rules.getOffset(winterNoonUtc).totalSeconds+        val fixed = ZoneId.of("+05:30").rules.getOffset(winterNoonUtc).totalSeconds+        assertEquals(kolkata, fixed)+    }++    @Test+    fun winterAndSummerOffsetsDifferInNewYork() {+        val summer = localIn(summerNoonUtc, "America/New_York").offset.totalSeconds+        val winter = localIn(winterNoonUtc, "America/New_York").offset.totalSeconds+        assertEquals(3600, summer - winter)+    }++    @Test+    fun tokyoHasNoDaylightSavingShift() {+        val summer = localIn(summerNoonUtc, "Asia/Tokyo").offset.totalSeconds+        val winter = localIn(winterNoonUtc, "Asia/Tokyo").offset.totalSeconds+        assertEquals(summer, winter)+    }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupingTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupingTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupingTest.ktnew file mode 100644index 0000000000..44440d04dc--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactGroupingTest.kt@@ -0,0 +1,79 @@+package com.vayunmathur.contacts.pure++import java.text.Normalizer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class ContactGroupingTest {++    private data class GroupFixture(val name: String, val favorite: Boolean = false)++    private fun groupKey(displayName: String): Char {+        val first = displayName.trim().firstOrNull() ?: return '#'+        val decomposed = Normalizer.normalize(first.toString(), Normalizer.Form.NFD)+        val stripped = decomposed.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "")+        val base = stripped.firstOrNull() ?: first+        val upper = base.uppercaseChar()+        return if (upper.isLetter()) upper else '#'+    }++    private fun groupContacts(+        contacts: List<GroupFixture>,+    ): Pair<List<GroupFixture>, Map<Char, List<GroupFixture>>> {+        val favorites = contacts.filter { it.favorite }+        val grouped = contacts.filter { !it.favorite }.groupBy { groupKey(it.name) }.toSortedMap()+        return favorites to grouped+    }++    @Test+    fun asciiGroupsUnderUppercaseLetter() {+        assertEquals('A', groupKey("alice"))+        assertEquals('B', groupKey("Bob"))+    }++    @Test+    fun accentedGroupsUnderBaseLetter() {+        assertEquals('E', groupKey("Émile"))+        assertEquals('C', groupKey("çan"))+    }++    @Test+    fun nonLettersGroupUnderHash() {+        assertEquals('#', groupKey("3 Doors"))+        assertEquals('#', groupKey("@home"))+        assertEquals('#', groupKey(""))+        assertEquals('#', groupKey("   "))+    }++    @Test+    fun lowercaseAndUppercaseShareGroup() {+        val (_, grouped) = groupContacts(listOf(GroupFixture("amy"), GroupFixture("Amy")))+        assertEquals(2, grouped['A']?.size)+    }++    @Test+    fun favoritesArePartitionedOut() {+        val contacts = listOf(+            GroupFixture("Alice", favorite = true),+            GroupFixture("Bob", favorite = true),+            GroupFixture("Carol"),+        )+        val (favorites, grouped) = groupContacts(contacts)+        assertEquals(2, favorites.size)+        assertEquals(1, grouped.values.sumOf { it.size })+        assertTrue(grouped.values.all { group -> group.none { it.favorite } })+    }++    @Test+    fun groupsAreSortedByKey() {+        val contacts = listOf(GroupFixture("Zed"), GroupFixture("amy"), GroupFixture("3po"), GroupFixture("Bob"))+        val (_, grouped) = groupContacts(contacts)+        assertEquals(listOf('#', 'A', 'B', 'Z'), grouped.keys.toList())+    }++    @Test+    fun cjkNameGroupsUnderOwnCharacter() {+        assertEquals('北', groupKey("北京伟"))+    }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.ktnew file mode 100644index 0000000000..8b8699fd85--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSearchFilterTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.contacts.pure++import java.text.Normalizer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class ContactSearchFilterTest {++    private data class SearchFixture(+        val name: String,+        val phone: String = "",+        val email: String = "",+        val nickname: String = "",+    )++    private fun foldText(value: String): String {+        val decomposed = Normalizer.normalize(value.trim(), Normalizer.Form.NFD)+        return decomposed.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "").lowercase()+    }++    private fun digitsOf(value: String): String = value.filter { it in '0'..'9' }++    private fun matches(contact: SearchFixture, query: String): Boolean {+        if (query.isBlank()) return true+        val folded = foldText(query)+        if (foldText(contact.name).contains(folded)) return true+        if (foldText(contact.email).contains(folded)) return true+        if (contact.nickname.isNotBlank() && foldText(contact.nickname).contains(folded)) return true+        val queryDigits = digitsOf(query)+        if (queryDigits.isNotEmpty() && digitsOf(contact.phone).contains(queryDigits)) return true+        return false+    }++    private fun filter(contacts: List<SearchFixture>, query: String): List<SearchFixture> {+        return contacts.filter { matches(it, query) }+    }++    private fun fixtures(): List<SearchFixture> {+        return listOf(+            SearchFixture("Alice Anderson", "4155550132", "[email protected]"),+            SearchFixture("Émilie Bernard", "5105550199", "[email protected]", "Mimi"),+            SearchFixture("Robert Chen", "6505550123", "[email protected]", "Bobby"),+            SearchFixture("北京伟", "2125550145", "[email protected]"),+        )+    }++    @Test+    fun emptyQueryReturnsEverything() {+        assertEquals(4, filter(fixtures(), "").size)+        assertEquals(4, filter(fixtures(), "   ").size)+    }++    @Test+    fun nameSearchIgnoresCase() {+        val result = filter(fixtures(), "ALI")+        assertEquals(listOf("Alice Anderson"), result.map { it.name })+    }++    @Test+    fun diacriticInsensitiveNameSearch() {+        val result = filter(fixtures(), "emilie")+        assertEquals(listOf("Émilie Bernard"), result.map { it.name })+    }++    @Test+    fun phoneSearchIgnoresSeparators() {+        assertEquals(listOf("Alice Anderson"), filter(fixtures(), "(415)").map { it.name })+        assertEquals(listOf("Robert Chen"), filter(fixtures(), "650-555").map { it.name })+    }++    @Test+    fun emailSearchMatchesDomain() {+        assertEquals(listOf("Émilie Bernard"), filter(fixtures(), "example.fr").map { it.name })+    }++    @Test+    fun nicknameSearchFindsContact() {+        assertEquals(listOf("Robert Chen"), filter(fixtures(), "bobby").map { it.name })+    }++    @Test+    fun sharedDomainMatchesEveryone() {+        assertEquals(4, filter(fixtures(), "example").size)+    }++    @Test+    fun unicodeQueryMatches() {+        val result = filter(fixtures(), "北京")+        assertEquals(listOf("北京伟"), result.map { it.name })+    }++    @Test+    fun noMatchGivesEmpty() {+        assertTrue(filter(fixtures(), "zzz").isEmpty())+    }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.ktnew file mode 100644index 0000000000..867c275627--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/ContactSortTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.contacts.pure++import java.text.Collator+import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals++class ContactSortTest {++    private enum class Mode { First, Last }++    private data class SortFixture(val first: String, val last: String)++    private fun displayOf(contact: SortFixture): String {+        return listOf(contact.first, contact.last)+            .map { it.trim() }+            .filter { it.isNotEmpty() }+            .joinToString(" ")+    }++    private fun sortName(contact: SortFixture, mode: Mode): String {+        if (mode == Mode.First) return displayOf(contact)+        val last = contact.last.trim()+        val first = contact.first.trim()+        return when {+            last.isNotEmpty() && first.isNotEmpty() -> "$last $first"+            last.isNotEmpty() -> last+            displayOf(contact).isNotBlank() -> displayOf(contact)+            else -> first+        }+    }++    private fun collator(): Collator {+        return Collator.getInstance(Locale.ROOT).apply {+            strength = Collator.PRIMARY+            decomposition = Collator.CANONICAL_DECOMPOSITION+        }+    }++    private fun sortedByMode(contacts: List<SortFixture>, mode: Mode): List<SortFixture> {+        val col = collator()+        return contacts.map { it to col.getCollationKey(sortName(it, mode)) }+            .sortedWith(compareBy { it.second })+            .map { it.first }+    }++    @Test+    fun sortsByFirstNameIgnoringCase() {+        val contacts = listOf(SortFixture("bob", "B"), SortFixture("alice", "A"), SortFixture("Carol", "C"))+        val result = sortedByMode(contacts, Mode.First)+        assertEquals(listOf("alice", "bob", "Carol"), result.map { it.first })+    }++    @Test+    fun sortsByLastNameMode() {+        val contacts = listOf(SortFixture("Ada", "Zebra"), SortFixture("Bob", "Apple"))+        val result = sortedByMode(contacts, Mode.Last)+        assertEquals(listOf("Apple", "Zebra"), result.map { it.last })+    }++    @Test+    fun accentedSortsWithBaseLetter() {+        val contacts = listOf(SortFixture("Victor", "V"), SortFixture("Véronique", "V"))+        val result = sortedByMode(contacts, Mode.First)+        assertEquals("Véronique", result[0].first)+        assertEquals("Victor", result[1].first)+    }++    @Test+    fun emptyDisplaySortsBeforeLetters() {+        val contacts = listOf(SortFixture("Amy", "A"), SortFixture("", ""))+        val result = sortedByMode(contacts, Mode.First)+        assertEquals("", result[0].first)+        assertEquals("Amy", result[1].first)+    }++    @Test+    fun singleNameFallsBackToFullValue() {+        assertEquals("Madonna", sortName(SortFixture("Madonna", ""), Mode.Last))+    }++    @Test+    fun lastNameModePrefersLastFirst() {+        assertEquals("Doe John", sortName(SortFixture("John", "Doe"), Mode.Last))+    }++    @Test+    fun unicodeSortIsStableAndLossless() {+        val contacts = listOf(SortFixture("伟", "北京"), SortFixture("Amy", "A"), SortFixture("Émile", "B"))+        val once = sortedByMode(contacts, Mode.First)+        val twice = sortedByMode(once, Mode.First)+        assertEquals(once.map { it.first }, twice.map { it.first })+        assertEquals(setOf("伟", "Amy", "Émile"), once.map { it.first }.toSet())+    }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/NamePhoneNormalizationTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/NamePhoneNormalizationTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/NamePhoneNormalizationTest.ktnew file mode 100644index 0000000000..9bc7683834--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/NamePhoneNormalizationTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.contacts.pure++import java.text.Normalizer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith++class NamePhoneNormalizationTest {++    private fun displayName(prefix: String, first: String, middle: String, last: String, suffix: String): String {+        return listOf(prefix, first, middle, last, suffix)+            .map { it.trim().replace(Regex("\\s+"), " ") }+            .filter { it.isNotEmpty() }+            .joinToString(" ")+    }++    private fun sortKey(name: String): String {+        val collapsed = name.trim().replace(Regex("\\s+"), " ")+        val decomposed = Normalizer.normalize(collapsed, Normalizer.Form.NFD)+        return decomposed.replace(Regex("\\p{InCombiningDiacriticalMarks}+"), "").lowercase()+    }++    private fun normalizePhone(raw: String): String {+        val trimmed = raw.trim()+        require(trimmed.isNotEmpty()) { "phone is blank" }+        val hasPlus = trimmed.startsWith("+")+        val body = if (hasPlus) trimmed.substring(1) else trimmed+        require(body.all { it in '0'..'9' || it in " +-().xX#" }) { "bad characters: $raw" }+        val digits = trimmed.filter { it in '0'..'9' }+        require(digits.length in 7..15) { "bad digit count: $raw" }+        return if (hasPlus) "+$digits" else digits+    }++    private fun formatUsNational(digits: String): String {+        require(digits.length == 10 && digits.all { it in '0'..'9' }) { "need exactly 10 digits" }+        return "(${digits.substring(0, 3)}) ${digits.substring(3, 6)}-${digits.substring(6)}"+    }++    @Test+    fun displayNameSkipsBlanksAndCollapsesSpaces() {+        assertEquals("Ada Love lace", displayName("", "  Ada  ", "", " Love  lace ", ""))+    }++    @Test+    fun unicodeDisplayNameIsPreserved() {+        assertEquals("José 北京伟 Jr.", displayName("", "José", "", "北京伟", "Jr."))+    }++    @Test+    fun emptyPartsGiveEmptyDisplay() {+        assertEquals("", displayName("", "   ", "", "", ""))+    }++    @Test+    fun sortKeyIsDiacriticAndCaseInsensitive() {+        assertEquals("emilie muller", sortKey("  Émilie  MÜLLER "))+    }++    @Test+    fun normalizePhoneStripsSeparators() {+        assertEquals("4155550132", normalizePhone("(415) 555-0132"))+    }++    @Test+    fun normalizePhoneKeepsLeadingPlus() {+        assertEquals("+442071234567", normalizePhone("+44 20 7123 4567"))+    }++    @Test+    fun extensionWithXIsAccepted() {+        assertEquals("4155550132123", normalizePhone("415-555-0132 x123"))+    }++    @Test+    fun invalidPhonesThrow() {+        val bad = listOf("", "   ", "abc", "123456", "1234567890123456", "4155550132abcd")+        for (raw in bad) {+            assertFailsWith<IllegalArgumentException>("input '$raw'") { normalizePhone(raw) }+        }+    }++    @Test+    fun nonAsciiDigitsAreRejected() {+        assertFailsWith<IllegalArgumentException> { normalizePhone("4155550132") }+    }++    @Test+    fun formatUsNationalFormatsTenDigits() {+        assertEquals("(415) 555-0132", formatUsNational("4155550132"))+    }++    @Test+    fun formatUsNationalRejectsBadInput() {+        assertFailsWith<IllegalArgumentException> { formatUsNational("415555013") }+        assertFailsWith<IllegalArgumentException> { formatUsNational("14155550132") }+        assertFailsWith<IllegalArgumentException> { formatUsNational("41555501ab") }+    }+}
contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt
diff --git a/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.ktnew file mode 100644index 0000000000..5f33e8b542--- /dev/null+++ b/contacts/src/test/java/com/vayunmathur/contacts/pure/VCardRoundTripTest.kt@@ -0,0 +1,262 @@+package com.vayunmathur.contacts.pure++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class VCardRoundTripTest {++    private data class VCardContact(+        val firstName: String = "",+        val lastName: String = "",+        val middleName: String = "",+        val prefix: String = "",+        val suffix: String = "",+        val phones: List<String> = emptyList(),+        val emails: List<String> = emptyList(),+        val note: String = "",+        val favorite: Boolean = false,+    )++    private fun escapeV(value: String): String {+        return value.replace("\\", "\\\\").replace("\n", "\\n").replace(",", "\\,").replace(";", "\\;")+    }++    private fun unescapeV(value: String): String {+        return value.replace("\\n", "\n").replace("\\N", "\n").replace("\\,", ",").replace("\\;", ";")+            .replace("\\\\", "\\")+    }++    private fun foldLine(line: String): List<String> {+        if (line.length <= 75) return listOf(line)+        val out = mutableListOf<String>()+        var idx = 0+        var first = true+        while (idx < line.length) {+            val end = minOf(idx + 75, line.length)+            val part = line.substring(idx, end)+            out.add(if (first) part else " $part")+            first = false+            idx = end+        }+        return out+    }++    private fun serialize(contact: VCardContact): String {+        val fields = mutableListOf("BEGIN:VCARD", "VERSION:3.0")+        val nameLine = "N:${escapeV(contact.lastName)};${escapeV(contact.firstName)};" ++            "${escapeV(contact.middleName)};${escapeV(contact.prefix)};${escapeV(contact.suffix)}"+        fields.add(nameLine)+        val full = listOf(contact.prefix, contact.firstName, contact.middleName, contact.lastName)+            .plus(contact.suffix)+            .map { it.trim() }+            .filter { it.isNotEmpty() }+            .joinToString(" ")+        fields.add("FN:${escapeV(full)}")+        contact.phones.forEach { fields.add("TEL;TYPE=VOICE:${escapeV(it)}") }+        contact.emails.forEach { fields.add("EMAIL;TYPE=INTERNET:${escapeV(it)}") }+        if (contact.note.isNotEmpty()) fields.add("NOTE:${escapeV(contact.note)}")+        if (contact.favorite) fields.add("X-STARRED:1")+        fields.add("END:VCARD")+        return fields.flatMap(::foldLine).joinToString("\r\n") + "\r\n"+    }++    private fun unfold(text: String): List<String> {+        val out = mutableListOf<String>()+        var pending: String? = null+        text.split("\r\n", "\n").forEach { raw ->+            if (raw.startsWith(" ") || raw.startsWith("\t")) {+                pending = (pending ?: "") + raw.trimStart()+            } else {+                pending?.let { out.add(it) }+                pending = raw+            }+        }+        pending?.let { out.add(it) }+        return out+    }++    private fun parse(text: String): List<VCardContact> {+        val contacts = mutableListOf<VCardContact>()+        var last = ""+        var firstName = ""+        var middle = ""+        var prefix = ""+        var suffix = ""+        var full = ""+        val phones = mutableListOf<String>()+        val emails = mutableListOf<String>()+        val notes = mutableListOf<String>()+        var favorite = false+        var inCard = false+        fun build(): VCardContact {+            var f = firstName+            var l = last+            if (f.isBlank() && l.isBlank() && middle.isBlank() && prefix.isBlank() && suffix.isBlank()) {+                val parts = full.split(" ").filter { it.isNotEmpty() }+                f = parts.firstOrNull() ?: ""+                l = parts.drop(1).joinToString(" ")+            }+            return VCardContact(+                f, l, middle, prefix, suffix, phones.toList(), emails.toList(),+                notes.joinToString("\n"), favorite,+            )+        }+        fun flush() {+            if (inCard) contacts.add(build())+            last = ""+            firstName = ""+            middle = ""+            prefix = ""+            suffix = ""+            full = ""+            phones.clear()+            emails.clear()+            notes.clear()+            favorite = false+            inCard = false+        }+        for (line in unfold(text)) {+            val trimmed = line.trimEnd()+            if (trimmed.isEmpty()) continue+            if (trimmed.startsWith("BEGIN:VCARD", ignoreCase = true)) {+                inCard = true+                continue+            }+            if (trimmed.startsWith("END:VCARD", ignoreCase = true)) {+                flush()+                continue+            }+            if (!inCard) continue+            val colon = trimmed.indexOf(':')+            if (colon == -1) continue+            val prop = trimmed.take(colon).split(';').firstOrNull()?.uppercase() ?: continue+            val rawValue = trimmed.substring(colon + 1)+            when (prop) {+                "N" -> {+                    val comps = unescapeV(rawValue).split(';')+                    last = comps.getOrNull(0) ?: ""+                    firstName = comps.getOrNull(1) ?: ""+                    middle = comps.getOrNull(2) ?: ""+                    prefix = comps.getOrNull(3) ?: ""+                    suffix = comps.getOrNull(4) ?: ""+                }+                "FN" -> full = unescapeV(rawValue)+                "TEL" -> phones.add(unescapeV(rawValue))+                "EMAIL" -> emails.add(unescapeV(rawValue))+                "NOTE" -> notes.add(unescapeV(rawValue))+                "X-STARRED" -> if (rawValue.trim() == "1") favorite = true+            }+        }+        return contacts+    }++    private fun parseStrict(text: String): List<VCardContact> {+        require(text.contains("BEGIN:VCARD", ignoreCase = true)) { "not a vCard blob" }+        return parse(text)+    }++    private fun roundTrip(contact: VCardContact): VCardContact = parse(serialize(contact)).single()++    @Test+    fun simpleContactRoundTrips() {+        val original = VCardContact(+            firstName = "Ada",+            lastName = "Lovelace",+            phones = listOf("+1 415-555-0132"),+            emails = listOf("[email protected]"),+            note = "First programmer",+            favorite = true,+        )+        assertEquals(original, roundTrip(original))+    }++    @Test+    fun unicodeNamesAndNotesSurvive() {+        val original = VCardContact(+            firstName = "José",+            lastName = "北京伟",+            middleName = "Émilie",+            note = "Müller — café",+        )+        assertEquals(original, roundTrip(original))+    }++    @Test+    fun commasSemicolonsAndNewlinesAreEscaped() {+        val original = VCardContact(firstName = "Ann;Marie", lastName = "O,Neil", note = "line1\nline2\\end")+        val blob = serialize(original)+        assertTrue(blob.contains("O\\,Neil"), "comma must be escaped")+        assertTrue(blob.contains("Ann\\;Marie"), "semicolon must be escaped")+        assertEquals(original, roundTrip(original))+    }++    @Test+    fun longNoteIsFoldedAndRestored() {+        val long = "n".repeat(70) + ", tail " + "n".repeat(120)+        val blob = serialize(VCardContact(firstName = "Ana", note = long))+        assertTrue(blob.contains("\r\n "), "expected a folded continuation line")+        assertEquals(long, parse(blob).single().note)+    }++    @Test+    fun emptyContactRoundTrips() {+        val back = roundTrip(VCardContact())+        assertEquals("", back.firstName)+        assertEquals("", back.note)+        assertTrue(back.phones.isEmpty())+        assertTrue(back.emails.isEmpty())+        assertFalse(back.favorite)+    }++    @Test+    fun invalidPhoneStringsSurviveVerbatim() {+        val weird = listOf("not-a-phone", "123", "+-() ", "12")+        val back = roundTrip(VCardContact(firstName = "Zed", phones = weird))+        assertEquals(weird, back.phones)+    }++    @Test+    fun phoneAndEmailOrderIsPreserved() {+        val original = VCardContact(+            firstName = "Cy",+            phones = listOf("111", "222"),+            emails = listOf("[email protected]", "[email protected]"),+        )+        val back = roundTrip(original)+        assertEquals(listOf("111", "222"), back.phones)+        assertEquals(listOf("[email protected]", "[email protected]"), back.emails)+    }++    @Test+    fun twoContactsShareOneBlob() {+        val blob = serialize(VCardContact(firstName = "Ada")) + serialize(VCardContact(firstName = "Bob"))+        val parsed = parse(blob)+        assertEquals(2, parsed.size)+        assertEquals("Ada", parsed[0].firstName)+        assertEquals("Bob", parsed[1].firstName)+    }++    @Test+    fun linesWithoutColonAreSkipped() {+        val blob = "BEGIN:VCARD\r\nVERSION:3.0\r\nGARBAGE-LINE\r\nFN:Kim\r\nEND:VCARD\r\n"+        val parsed = parse(blob).single()+        assertEquals("Kim", parsed.firstName)+        assertTrue(parsed.phones.isEmpty())+    }++    @Test+    fun fnSuppliesNameWhenNIsEmpty() {+        val blob = "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Madonna\r\nEND:VCARD\r\n"+        val parsed = parse(blob).single()+        assertEquals("Madonna", parsed.firstName)+        assertEquals("", parsed.lastName)+    }++    @Test+    fun blobWithoutBeginThrows() {+        assertFailsWith<IllegalArgumentException> { parseStrict("FN:No Card Here") }+    }+}
email/src/androidTest/java/com/vayunmathur/email/ui/EmailAddAccountTest.kt
diff --git a/email/src/androidTest/java/com/vayunmathur/email/ui/EmailAddAccountTest.kt b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailAddAccountTest.ktnew file mode 100644index 0000000000..980a9e6852--- /dev/null+++ b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailAddAccountTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.email.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * First-run gate journey: no accounts shows AddAccountScreen (see MainContent).+ *+ * The Gmail preset stays in-app (Outlook needs an external browser that never+ * finishes headless), so this fills its form and asserts validation holds the+ * gate: no inbox appears and the app stays foreground. UiDevice polling only;+ * compose-test idle-sync is broken on current releases.+ */+@RunWith(AndroidJUnit4::class)+class EmailAddAccountTest {++    @Test+    fun launch_presetForm_rendersAndValidates() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "add-account gate never appeared",+            device.wait(Until.findObject(By.text(ADD_ACCOUNT_TITLE)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "provider picker never appeared",+            device.wait(Until.findObject(By.text(PROVIDER_PICKER_TITLE)), CONTENT_TIMEOUT_MS),+        )+        requireNotNull(device.wait(Until.findObject(By.text(GMAIL_PRESET)), CONTENT_TIMEOUT_MS)) {+            "Gmail preset row missing"+        }.click()+        assertNotNull(+            "account form never rendered",+            device.wait(Until.findObject(By.text(EMAIL_FIELD_LABEL)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "save action never rendered",+            device.wait(Until.findObject(By.text(SAVE_BUTTON)), CONTENT_TIMEOUT_MS),+        )+        requireNotNull(device.wait(Until.findObject(By.text(EMAIL_FIELD_LABEL)), CONTENT_TIMEOUT_MS)) {+            "email field missing"+        }.click()+        val edit = device.wait(Until.findObject(By.clazz("android.widget.EditText")), CONTENT_TIMEOUT_MS)+        assertNotNull("email field never took focus", edit)+        edit!!.setText("not-an-email")+        assertNotNull(+            "save action disappeared after invalid input",+            device.wait(Until.findObject(By.text(SAVE_BUTTON)), CONTENT_TIMEOUT_MS),+        )+        val save = requireNotNull(device.wait(Until.findObject(By.text(SAVE_BUTTON)), CONTENT_TIMEOUT_MS)) {+            "save button missing"+        }+        assertFalse(+            "save must stay disabled until a valid email and password are entered",+            save.isClickable,+        )+        assertNull(+            "inbox shown without a valid account; validation did not hold the gate",+            device.wait(Until.findObject(By.text(INBOX_TITLE)), GATE_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        for (permission in info.requestedPermissions.orEmpty()) {+            try {+                uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+            } catch (ignored: SecurityException) { // Not grantable headlessly.+            } catch (ignored: IOException) { // Pipe failed; content asserts report it.+            }+        }+        for (command in SPECIAL_ACCESS_COMMANDS) {+            try {+                uiAutomation.executeShellCommand(command.format(packageName)).close()+            } catch (ignored: SecurityException) { // Appop missing on this release.+            } catch (ignored: IOException) { // Pipe failed; gate assert reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private const val ADD_ACCOUNT_TITLE = "Add Account"+        private const val PROVIDER_PICKER_TITLE = "Choose your email provider"+        private const val GMAIL_PRESET = "Gmail"+        private const val EMAIL_FIELD_LABEL = "Email address"+        private const val SAVE_BUTTON = "Test connection & save"+        private const val INBOX_TITLE = "Unified Inbox"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
email/src/androidTest/java/com/vayunmathur/email/ui/EmailComposerTest.kt
diff --git a/email/src/androidTest/java/com/vayunmathur/email/ui/EmailComposerTest.kt b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailComposerTest.ktnew file mode 100644index 0000000000..c576aab31f--- /dev/null+++ b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailComposerTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.email.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.core.content.FileProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import java.io.File+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * EML viewer journey: VIEW a test .eml via intent (the EmlViewer bypass in+ * MainContent needs no account), asserting the parsed content renders and the+ * forward action is offered.+ *+ * The .eml is written to the app cache and served through the app's own+ * FileProvider, so no external file or account exists. UiDevice polling only;+ * compose-test idle-sync is broken on current releases.+ */+@RunWith(AndroidJUnit4::class)+class EmailComposerTest {++    @Test+    fun viewEml_showsContentWithForwardAction() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        val eml = File(targetContext.cacheDir, "journey.eml")+        eml.writeText(TEST_EML)+        val uri = FileProvider.getUriForFile(targetContext, "$packageName.fileprovider", eml)+        val intent = Intent(Intent.ACTION_VIEW)+            .setDataAndType(uri, "message/rfc822")+            .setClassName(packageName, "$packageName.MainActivity")+            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)+            .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "eml subject never rendered; the viewer may have failed to parse",+            device.wait(Until.findObject(By.text(EML_SUBJECT)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "eml body never rendered",+            device.wait(Until.findObject(By.textContains(EML_BODY_SNIPPET)), CONTENT_TIMEOUT_MS),+        )+        assertNotNull(+            "forward action missing from the viewer",+            device.wait(Until.findObject(By.desc(FORWARD_DESC)), CONTENT_TIMEOUT_MS),+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        for (permission in info.requestedPermissions.orEmpty()) {+            try {+                uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+            } catch (ignored: SecurityException) { // Not grantable headlessly.+            } catch (ignored: IOException) { // Pipe failed; content asserts report it.+            }+        }+        for (command in SPECIAL_ACCESS_COMMANDS) {+            try {+                uiAutomation.executeShellCommand(command.format(packageName)).close()+            } catch (ignored: SecurityException) { // Appop missing on this release.+            } catch (ignored: IOException) { // Pipe failed; gate assert reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private const val EML_SUBJECT = "Journey hello"+        private const val EML_BODY_SNIPPET = "Hello from the journey test"+        private const val FORWARD_DESC = "Forward"+        private const val TEST_EML = "From: [email protected]\n" ++            "To: [email protected]\n" ++            "Subject: Journey hello\n" ++            "Date: Wed, 21 Oct 2026 12:00:00 +0000\n" ++            "Content-Type: text/plain; charset=utf-8\n" ++            "\n" ++            "Hello from the journey test.\n"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
email/src/androidTest/java/com/vayunmathur/email/ui/EmailOutboxTest.kt
diff --git a/email/src/androidTest/java/com/vayunmathur/email/ui/EmailOutboxTest.kt b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailOutboxTest.ktnew file mode 100644index 0000000000..429c97f38b--- /dev/null+++ b/email/src/androidTest/java/com/vayunmathur/email/ui/EmailOutboxTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.email.ui++import android.app.UiAutomation+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.Until+import com.vayunmathur.email.data.EmailAccount+import com.vayunmathur.email.data.EmailRepository+import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.email.data.OutboxManager+import java.io.IOException+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Outbox journey: with accounts present the app opens past the gate onto the+ * inbox; a send that fails (unroutable host) lands in the outbox queue.+ *+ * Headless runs have no real credentials, so the test seeds a `custom` account+ * pointing at a localhost port nothing listens on, then queues the unsendable+ * message directly through [OutboxManager], which is the same enqueue path+ * [com.vayunmathur.email.platform.EmailSendActions.sendFrom] falls back to on+ * error. The test asserts the inbox opens past the seeded account and the+ * queued entry persists in the outbox store. UiDevice polling+ * only; compose-test idle-sync is broken on current releases.+ */+@RunWith(AndroidJUnit4::class)+class EmailOutboxTest {++    @Test+    fun seedAccountAndQueue_showsOutboxBadge() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName+        grantAllRequestedPermissions(instrumentation.uiAutomation, targetContext.packageManager, packageName)+        runBlocking {+            val repo = EmailRepository.get(targetContext)+            if (repo.accounts.getAccountByEmail(ACCOUNT_EMAIL) == null) {+                repo.accounts.insertAccount(+                    EmailAccount(+                        email = ACCOUNT_EMAIL,+                        provider = "custom",+                        imapHost = "127.0.0.1",+                        imapPort = 10993,+                        imapUseSsl = false,+                        smtpHost = "127.0.0.1",+                        smtpPort = 11025,+                        smtpUseSsl = false,+                        authType = "password",+                    ),+                )+            }+            OutboxManager.enqueue(+                context = targetContext,+                accountEmail = ACCOUNT_EMAIL,+                to = "[email protected]",+                subject = OUTBOX_SUBJECT,+                body = "queued by journey test",+                initialError = "journey seed",+            )+        }+        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK)+        intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "inbox never opened past the seeded account",+            device.wait(Until.findObject(By.text(INBOX_TITLE)), CONTENT_TIMEOUT_MS),+        )+        assertNull(+            "add-account gate showing despite seeded account",+            device.wait(Until.findObject(By.text(ADD_ACCOUNT_TITLE)), GATE_TIMEOUT_MS),+        )+        runBlocking {+            val outbox: List<OutboxEntry> = EmailRepository.get(targetContext).outbox.getOutbox()+            check(outbox.any { it.subject == OUTBOX_SUBJECT }) { "seeded outbox entry missing" }+            val stale = outbox.filter { it.subject == OUTBOX_SUBJECT }.drop(1)+            stale.forEach { EmailRepository.get(targetContext).outbox.deleteOutboxEntry(it) }+        }+        assertEquals(packageName, device.currentPackageName)+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        for (permission in info.requestedPermissions.orEmpty()) {+            try {+                uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+            } catch (ignored: SecurityException) { // Not grantable headlessly.+            } catch (ignored: IOException) { // Pipe failed; content asserts report it.+            }+        }+        for (command in SPECIAL_ACCESS_COMMANDS) {+            try {+                uiAutomation.executeShellCommand(command.format(packageName)).close()+            } catch (ignored: SecurityException) { // Appop missing on this release.+            } catch (ignored: IOException) { // Pipe failed; gate assert reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"+        private const val ADD_ACCOUNT_TITLE = "Add Account"+        private const val INBOX_TITLE = "Unified Inbox"+        private const val ACCOUNT_EMAIL = "[email protected]"+        private const val OUTBOX_SUBJECT = "Journey queued send"+        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubAchievementsTest.kt
diff --git a/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubAchievementsTest.kt b/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubAchievementsTest.ktnew file mode 100644index 0000000000..14164e2474--- /dev/null+++ b/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubAchievementsTest.kt@@ -0,0 +1,127 @@+package com.vayunmathur.games.hub.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.UiObject2+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Achievements journey: launch onto the tabbed hub, open the Achievements+ * tab, and see the achievements filter content.+ *+ * With nothing registered the tab shows the stable "No matching+ * achievements" empty row; with data it shows achievement rows instead.+ * Either one proves the tab renders.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects+ * on hidden InputManager APIs that no longer exist on current releases.+ */+@RunWith(AndroidJUnit4::class)+class HubAchievementsTest {++    @Test+    fun achievements_openTab_filterContentVisible() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName++        grantAllRequestedPermissions(+            instrumentation.uiAutomation,+            targetContext.packageManager,+            packageName,+        )++        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)++        // No gate in the hub: the wall never appears and the Achievements+        // bottom-nav tab is showing.+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "achievements tab never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(ACHIEVEMENTS_TAB_LABEL)), CONTENT_TIMEOUT_MS),+        )++        // The profile stat cards reuse the "Achievements" label, so tap+        // the bottom-most match: the bottom-nav tab itself.+        clickBottomMost(device, ACHIEVEMENTS_TAB_LABEL)+        val empty = device.wait(Until.findObject(By.text(EMPTY_STATE)), NAV_TIMEOUT_MS)+        val populated = device.wait(Until.findObject(By.text(ALL_GAMES_CHIP)), GATE_TIMEOUT_MS)+        assertTrue(+            "achievements content never appeared",+            empty != null || populated != null,+        )+        assertEquals(packageName, device.currentPackageName)+    }++    private fun clickBottomMost(device: UiDevice, text: String) {+        val matches: List<UiObject2> = device.findObjects(By.text(text))+        assertTrue("no object with text \"$text\" found", matches.isNotEmpty())+        val target = matches.maxByOrNull { it.visibleBounds.centerY() }+        assertNotNull("no visible object with text \"$text\" found", target)+        target!!.click()+    }++    private fun grantAllRequestedPermissions(+        uiAutomation: UiAutomation,+        packageManager: PackageManager,+        packageName: String,+    ) {+        val info = try {+            packageManager.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)+        } catch (e: PackageManager.NameNotFoundException) {+            throw AssertionError("package $packageName not installed", e)+        }+        for (permission in info.requestedPermissions.orEmpty()) {+            try {+                uiAutomation.executeShellCommand("pm grant $packageName $permission").close()+            } catch (ignored: SecurityException) {+                // Not a headlessly grantable permission: nothing to do.+            } catch (ignored: IOException) {+                // Shell pipe failed: the assertions below report it.+            }+        }+        for (command in SPECIAL_ACCESS_COMMANDS) {+            try {+                uiAutomation.executeShellCommand(command.format(packageName)).close()+            } catch (ignored: SecurityException) {+                // Appop missing on this release: the gate assertion reports it.+            } catch (ignored: IOException) {+                // Shell pipe failed: the gate assertion below reports it.+            }+        }+    }++    private companion object {+        private const val CONTENT_TIMEOUT_MS = 15_000L+        private const val GATE_TIMEOUT_MS = 5_000L+        private const val NAV_TIMEOUT_MS = 30_000L+        private const val ACHIEVEMENTS_TAB_LABEL = "Achievements"+        private const val EMPTY_STATE = "No matching achievements"+        private const val ALL_GAMES_CHIP = "All games"+        private const val PERMISSION_GATE_TITLE = "Grant Required Permissions"++        private val SPECIAL_ACCESS_COMMANDS = arrayOf(+            "appops set %s SCHEDULE_EXACT_ALARM allow",+            "appops set %s USE_FULL_SCREEN_INTENT allow",+        )+    }+}
games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubBrowseTest.kt
diff --git a/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubBrowseTest.kt b/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubBrowseTest.ktnew file mode 100644index 0000000000..f9d3a7960d--- /dev/null+++ b/games/hub/src/androidTest/java/com/vayunmathur/games/hub/ui/HubBrowseTest.kt@@ -0,0 +1,152 @@+package com.vayunmathur.games.hub.ui++import android.app.UiAutomation+import android.content.Intent+import android.content.pm.PackageManager+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import androidx.test.uiautomator.By+import androidx.test.uiautomator.UiDevice+import androidx.test.uiautomator.UiObject2+import androidx.test.uiautomator.Until+import java.io.IOException+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith++/**+ * Hub browse journey: launch onto the tabbed hub, open the Games tab,+ * see the games list, and open a game detail when one is registered.+ *+ * Games register via the hub provider when sibling game apps run, so a+ * fresh hub shows the stable no-games empty state instead of any card.+ * Both branches assert the screen; the detail branch additionally opens+ * the first card and checks the detail stats.+ *+ * UiDevice polling, not compose-test: compose's Espresso idle-sync reflects+ * on hidden InputManager APIs that no longer exist on current releases.+ */+@RunWith(AndroidJUnit4::class)+class HubBrowseTest {++    @Test+    fun browse_openGamesTab_listVisible() {+        val instrumentation = InstrumentationRegistry.getInstrumentation()+        val device = UiDevice.getInstance(instrumentation)+        val targetContext = instrumentation.targetContext+        val packageName = targetContext.packageName++        grantAllRequestedPermissions(+            instrumentation.uiAutomation,+            targetContext.packageManager,+            packageName,+        )++        val intent = targetContext.packageManager.getLaunchIntentForPackage(packageName)+        assertNotNull("no launcher intent for $packageName", intent)+        intent!!.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)+        targetContext.startActivity(intent)++        // No gate in the hub: the wall never appears and the Games+        // bottom-nav tab is showing.+        assertNull(+            "permission gate is showing; grants did not clear it",+            device.wait(Until.findObject(By.text(PERMISSION_GATE_TITLE)), GATE_TIMEOUT_MS),+        )+        assertNotNull(+            "games tab never appeared; the app may have crashed on launch",+            device.wait(Until.findObject(By.text(GAMES_TAB_LABEL)), CONTENT_TIMEOUT_MS),+        )++        // The dashboard reuses the "Games" label for a stat card, so tap+        // the bottom-most match: the bottom-nav tab itself.+        clickBottomMost(device, GAMES_TAB_LABEL)+        assertNotNull(+            "games list never appeared",+            device.wait(Until.findObject(By.text(SEARCH_GAMES)), NAV_TIMEOUT_MS),+        )++        // A registered game opens its detail (stat row with the Last+        // label); otherwise the stable empty state is showing.+        val badge = device.wait(+            Until.findObject(By.text(INSTALLED_BADGE)),+            NAV_TIMEOUT_MS,+        ) ?: device.wait(Until.findObject(By.text(NOT_INSTALLED_BADGE)), GATE_TIMEOUT_MS)+        if (badge != null) {+            badge.click()+            assertTrue(+                "search bar still showing; game detail never opened",+                device.wait(Until.gone(By.text(SEARCH_GAMES)), NAV_TIMEOUT_MS),+            )+            val detailStats = device.wait(Until.findObject(By.text(DETAIL_LAST_LABEL)), NAV_TIMEOUT_MS)+            val missing = device.wait(Until.findObject(By.text(GAME_NOT_FOUND)), GATE_TIMEOUT_MS)+            assertTrue("game detail never appeared", detailStats != null || missing != null)+        } else {+            assertNotNull(+                "neither a game card nor the empty state is showing",+                device.wait(Until.findObject(By.textContains(EMPTY_STATE_PREFIX)), NAV_TIMEOUT_MS),+            )+        }+        assertEquals(packageName, device.currentPackageName)+    }++    private fun clickBottomMost(device: UiDevice, text: String) {+        val matches: List<UiObject2> = device.findObjects(By.text(text))+        assertTrue("no object with text \"$text\" found", matches.isNotEmpty())+        val target

Diff truncated.