Modern Apps git

← Modern-Apps.git

todo: cover assistant intents, calendar mirror, widgets and navigation

Commit
78c7489e3f3f595cbbcba6fe1357ed0898fd84c9
Author
Vayun Mathur <[email protected]>
When
2026-11-16 13:38 UTC (20 days ago)
Parents
a47e08a
Add Robolectric tests for the previously uncovered todo paths:

- Assistant tools Insert/Get/CompleteTodoIntent via
  performCalculation against the in-memory Room repository
  (quick-add parsing, explicit due/priority override, scope
  filtering, complete by id/title, missing/deleted rows).
- Today/QuickAdd widget data loading, preview data, the
  CompleteTaskAction callback and provideGlance/providePreview
  smoke entry points. Glance RemoteViews rendering remains
  host-bound and is not asserted.
- CalendarMirror full write path via an in-memory fake
  CalendarProvider under the real authority (calendar create/
  reuse, timed/all-day/recurring events, fingerprint-stable
  second run, update/delete, disable deletes calendar,
  provider failures swallowed).
- ReminderActionReceiver complete/snooze, BootReceiver
  re-arming, TodoBackground reconcileNow/start reactions.
- Navigation graph composition, IntentEffect consuming
  OpenTask/OpenView/QuickAdd requests, MainActivity intent
  recording, and Route equality.

Coverage (merged report, INSTRUCTION): 46297 covered /
9860 missed before, 48846 covered / 7311 missed after
(+2549). LINE 3650/608 before, 3876/382 after.

Verified without the CI ignore file:
./gradlew :todo:testDevUnitTest :todo:detekt :todo:lint
green (384 tests; one intermittent TodoEditorTest timeout
seen in a coverage run passed on the forced re-run).

Diff

todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt b/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.ktnew file mode 100644index 0000000000..fff4fde08a--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/NavigationAndMainActivityTest.kt@@ -0,0 +1,140 @@+package com.vayunmathur.todo++import android.app.Application+import android.content.Context+import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.lifecycle.SavedStateHandle+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.todo.data.TestTodoRepository+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoSettings+import com.vayunmathur.todo.domain.TodoView+import com.vayunmathur.todo.platform.IntentRouter+import com.vayunmathur.todo.platform.TodoViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [Navigation] + [com.vayunmathur.todo.ui.IntentEffect] + [MainActivity]+ * routing: the real nav graph composes the list page, consumes pending+ * [IntentRouter] requests once, and the activity records its launch intent.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class NavigationAndMainActivityTest {+    @get:Rule val rule = createComposeRule()++    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private var harness: TestTodoRepository? = null+    private val repo get() = harness!!.repository++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        harness = TestTodoRepository.create(context)+        IntentRouter.consume()+    }++    @AfterTest fun tearDown() {+        IntentRouter.consume()+        harness?.close()+        harness = null+        Dispatchers.resetMain()+    }++    private fun viewModel() = TodoViewModel(app, repo, TodoSettings(context), SavedStateHandle())++    private fun seed() = runBlocking {+        repo.upsert(Todo(syncId = "nav1", title = "Nav alpha task"))+        repo.upsert(Todo(syncId = "nav2", title = "Nav beta task"))+    }++    @Test fun navigationComposesListPageFromRealViewModel() {+        seed()+        val vm = viewModel()+        vm.setView(TodoView.All)+        rule.setContent { DynamicTheme { Navigation(vm) } }+        rule.onNodeWithText("Nav alpha task").assertIsDisplayed()+        rule.onNodeWithText("Nav beta task").assertIsDisplayed()+    }++    @Test fun intentEffectOpensTaskRequestedBeforeComposition() {+        seed()+        val vm = viewModel()+        val id = runBlocking { repo.getBySyncId("nav1")!!.id }+        IntentRouter.handle(+            Intent().putExtra(IntentRouter.EXTRA_OPEN_TASK, "nav1"),+        )+        assertTrue(IntentRouter.pending.value is IntentRouter.Request.OpenTask)+        rule.setContent { DynamicTheme { Navigation(vm) } }+        // The detail page for the requested task composes and the request+        // is consumed exactly once.+        rule.waitUntil(timeoutMillis = 5_000) {+            rule.onAllNodesWithText("Nav alpha task").fetchSemanticsNodes().isNotEmpty()+        }+        rule.onNodeWithText("Nav alpha task").assertIsDisplayed()+        assertNull(IntentRouter.pending.value)+        assertTrue(id > 0)+    }++    @Test fun intentEffectOpensViewAndQuickAddRequests() {+        seed()+        val vm = viewModel()+        IntentRouter.handle(Intent().putExtra(IntentRouter.EXTRA_VIEW, TodoView.All.key))+        rule.setContent { DynamicTheme { Navigation(vm) } }+        rule.waitUntil(timeoutMillis = 5_000) { IntentRouter.pending.value == null }+        assertEquals(TodoView.All, vm.view.value)+        // A later quick-add request resets to the list and pre-fills the sheet.+        rule.runOnIdle {+            IntentRouter.handle(+                Intent(IntentRouter.ACTION_QUICK_ADD).putExtra(Intent.EXTRA_TEXT, "Quick nav task"),+            )+        }+        rule.waitUntil(timeoutMillis = 5_000) { IntentRouter.pending.value == null }+        rule.onNodeWithText("Quick nav task").assertExists()+    }++    @Test fun routeTypesAreDistinctNavKeys() {+        assertEquals(Route.TodoList, Route.TodoList)+        assertEquals(Route.Settings, Route.Settings)+        assertEquals(Route.TodoDetail(7L, "sync"), Route.TodoDetail(7L, "sync"))+        assertTrue(Route.TodoDetail(7L) != Route.TodoDetail(8L))+        assertEquals(null, Route.TodoDetail(7L).newSyncId)+    }++    @Test fun mainActivityRecordsLaunchIntentAndComposesNavigation() {+        seed()+        val intent = Intent(context, MainActivity::class.java)+            .putExtra(IntentRouter.EXTRA_VIEW, TodoView.All.key)+        val controller = Robolectric.buildActivity(MainActivity::class.java, intent).setup()+        // The activity's own Navigation graph consumes the recorded view+        // request as soon as it composes.+        org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+        assertNull(IntentRouter.pending.value)+        // A fresh intent arriving while alive is recorded the same way and+        // likewise recorded by the live activity (its graph may or may not+        // have a frame in flight under Robolectric to consume it yet).+        controller.newIntent(Intent(context, MainActivity::class.java).setAction(IntentRouter.ACTION_QUICK_ADD))+        // Recording is synchronous in onNewIntent; consumption happens on a+        // later composition frame.+        assertTrue(IntentRouter.pending.value is IntentRouter.Request.QuickAdd)+    }+}
todo/src/test/java/com/vayunmathur/todo/intents/AssistantIntentsTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/intents/AssistantIntentsTest.kt b/todo/src/test/java/com/vayunmathur/todo/intents/AssistantIntentsTest.ktnew file mode 100644index 0000000000..e6818901a6--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/intents/AssistantIntentsTest.kt@@ -0,0 +1,252 @@+package com.vayunmathur.todo.intents++import android.content.Context+import androidx.glance.appwidget.AppWidgetId+import androidx.glance.action.actionParametersOf+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.intents.todo.CompleteTodoData+import com.vayunmathur.library.intents.todo.GetTodosQuery+import com.vayunmathur.library.intents.todo.InsertTodoData+import com.vayunmathur.todo.data.TestTodoRepository+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.TodoList+import com.vayunmathur.todo.data.getLists+import com.vayunmathur.todo.data.upsertList+import com.vayunmathur.todo.widget.CompleteTaskAction+import com.vayunmathur.todo.widget.QuickAddWidget+import com.vayunmathur.todo.widget.TodayWidget+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Assistant-tool ([InsertTodoIntent]/[GetTodosIntent]/[CompleteTodoIntent]) and+ * widget data-path behaviour against a real in-memory repository installed as+ * the [com.vayunmathur.todo.data.TodoRepository] singleton, which is how the+ * production activities/widgets resolve it. Glance rendering itself is not+ * exercised here (device/host-bound); the pure data loading, preview data and+ * the checkbox action callback are.+ */+@RunWith(RobolectricTestRunner::class)+class AssistantIntentsTest {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private var harness: TestTodoRepository? = null+    private val repo get() = harness!!.repository++    @BeforeTest fun setUp() { harness = TestTodoRepository.create(context) }+    @AfterTest fun tearDown() { harness?.close(); harness = null }++    // Widget classes are final and loadData/previewData are protected on+    // MaWidget, so the genuine data path is invoked reflectively; Glance+    // rendering itself is host-bound and not exercised.+    private fun findMethod(widget: Any, method: String): java.lang.reflect.Method {+        var type: Class<*>? = widget.javaClass+        while (type != null) {+            type.declaredMethods.firstOrNull { it.name == method }?.let { it.isAccessible = true; return it }+            type = type.superclass+        }+        error("No $method on ${widget.javaClass}")+    }++    private fun <T> callWidget(widget: Any, method: String, vararg args: Any?): T {+        @Suppress("UNCHECKED_CAST")+        return findMethod(widget, method).invoke(widget, *args) as T+    }++    /** Reflectively calls a suspend widget method, blocking until it resumes. */+    private fun <T> blockingWidget(widget: Any, method: String, vararg args: Any?): T {+        val latch = java.util.concurrent.CountDownLatch(1)+        var outcome: Result<T>? = null+        val cont = object : kotlin.coroutines.Continuation<T> {+            override val context = kotlin.coroutines.EmptyCoroutineContext+            override fun resumeWith(result: Result<T>) { outcome = result; latch.countDown() }+        }+        val returned = findMethod(widget, method).invoke(widget, *args, cont)+        if (returned != kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED) {+            @Suppress("UNCHECKED_CAST")+            outcome = Result.success(returned as T)+            latch.countDown()+        }+        assertTrue(latch.await(10, java.util.concurrent.TimeUnit.SECONDS), "widget $method timed out")+        return outcome!!.getOrThrow()+    }++    // --- InsertTodoIntent ---++    @Test fun insertPlainTitleCreatesTaskAndReturnsSyncId() = runBlocking {+        val syncId = InsertTodoIntent().performCalculation(InsertTodoData(title = "Buy milk", notes = "oat"))+        val stored = repo.getBySyncId(syncId)+        assertNotNull(stored)+        assertEquals("Buy milk", stored.title)+        assertEquals("oat", stored.notes)+        assertNull(stored.dueAt)+        assertEquals(0, stored.priority)+    }++    @Test fun insertHonoursQuickAddSyntaxWhenNoDueGiven(): Unit = runBlocking {+        repo.upsertList(TodoList(syncId = "home", name = "Home"))+        val syncId = InsertTodoIntent().performCalculation(InsertTodoData(title = "Pay rent @home !1 tomorrow"))+        val stored = repo.getBySyncId(syncId)!!+        assertEquals("Pay rent", stored.title)+        assertEquals(1, stored.priority)+        assertEquals("home", stored.listSyncId)+        assertNotNull(stored.dueAt)+    }++    @Test fun insertExplicitDueAndPriorityOverrideQuickAdd() = runBlocking {+        val due = System.currentTimeMillis() + 86_400_000L+        val syncId = InsertTodoIntent().performCalculation(+            InsertTodoData(title = "Call @nobody tomorrow", dueAt = due, priority = 3),+        )+        val stored = repo.getBySyncId(syncId)!!+        // Explicit due/priority: title is used verbatim, no parsed tags/list.+        assertEquals("Call @nobody tomorrow", stored.title)+        assertEquals(due, stored.dueAt)+        assertEquals(3, stored.priority)+        assertFalse(stored.dueAllDay)+        assertTrue(stored.tags.isEmpty())+        assertNull(stored.listSyncId)+    }++    @Test fun insertOutOfRangePriorityFallsBackToParsedOrZero() = runBlocking {+        val a = repo.getBySyncId(InsertTodoIntent().performCalculation(InsertTodoData(title = "Low", priority = 99)))!!+        assertEquals(0, a.priority)+        val b = repo.getBySyncId(InsertTodoIntent().performCalculation(InsertTodoData(title = "High !2", priority = -1)))!!+        assertEquals(2, b.priority)+    }++    @Test fun insertBlankTitleFallsBackToTrimmedInput() = runBlocking {+        // Quick-add tokens only: parsed title is empty, so the input is kept.+        val syncId = InsertTodoIntent().performCalculation(InsertTodoData(title = "tomorrow"))+        assertEquals("tomorrow", repo.getBySyncId(syncId)!!.title)+    }++    // --- GetTodosIntent ---++    private suspend fun seedForGet() {+        repo.upsertList(TodoList(syncId = "work", name = "Work"))+        val now = System.currentTimeMillis()+        repo.upsert(Todo(syncId = "today", title = "Today task", dueAt = now, listSyncId = "work", priority = 2, notes = "n1"))+        repo.upsert(Todo(syncId = "future", title = "Future task", dueAt = now + 7 * 86_400_000L))+        repo.upsert(Todo(syncId = "nodate", title = "No date task"))+        repo.upsert(Todo(syncId = "done", title = "Done task", dueAt = now, done = true, completedAt = now))+    }++    @Test fun getTodosTodayReturnsOnlyTodaysOpenTasks() = runBlocking {+        seedForGet()+        val out = GetTodosIntent().performCalculation(GetTodosQuery(scope = "today"))+        assertEquals(listOf("Today task"), out.map { it.title })+        assertEquals("Work", out.single().list)+        assertEquals(2, out.single().priority)+        assertEquals("n1", out.single().notes)+        assertFalse(out.single().done)+    }++    @Test fun getTodosUpcomingAndAllAndUnknownScope() = runBlocking {+        seedForGet()+        val upcoming = GetTodosIntent().performCalculation(GetTodosQuery(scope = "UPCOMING"))+        assertTrue(upcoming.any { it.title == "Future task" })+        val all = GetTodosIntent().performCalculation(GetTodosQuery(scope = "all"))+        assertTrue(all.map { it.title }.containsAll(listOf("Today task", "Future task", "No date task")))+        // Unknown scope defaults to Today, case-insensitively.+        val fallback = GetTodosIntent().performCalculation(GetTodosQuery(scope = "whatever"))+        assertEquals(listOf("Today task"), fallback.map { it.title })+        val empty = GetTodosIntent().performCalculation(GetTodosQuery(scope = ""))+        assertEquals(listOf("Today task"), empty.map { it.title })+    }++    @Test fun getTodosEmptyRepoReturnsEmpty() = runBlocking {+        assertTrue(GetTodosIntent().performCalculation(GetTodosQuery()).isEmpty())+        assertEquals(0, repo.getLists().size)+    }++    // --- CompleteTodoIntent ---++    @Test fun completeByIdMarksDoneAndIsIdempotent() = runBlocking {+        repo.upsert(Todo(syncId = "c1", title = "Finish me"))+        assertTrue(CompleteTodoIntent().performCalculation(CompleteTodoData(id = "c1")))+        assertTrue(repo.getBySyncId("c1")!!.done)+        // Already done via id path: still true, and title path skips done rows.+        assertTrue(CompleteTodoIntent().performCalculation(CompleteTodoData(id = "c1")))+    }++    @Test fun completeByTitleCaseInsensitiveTrimsAndSkipsDoneAndDeleted() = runBlocking {+        repo.upsert(Todo(syncId = "done1", title = "Report", done = true, completedAt = 1L))+        repo.upsert(Todo(syncId = "open1", title = "Report"))+        repo.upsert(Todo(syncId = "del1", title = "Ghost", deleted = true))+        assertTrue(CompleteTodoIntent().performCalculation(CompleteTodoData(title = "  report ")))+        assertTrue(repo.getBySyncId("open1")!!.done)+        // Deleted row is not matched by id, and no open "Ghost" exists.+        assertFalse(CompleteTodoIntent().performCalculation(CompleteTodoData(id = "del1", title = "Ghost")))+        assertFalse(repo.getBySyncId("del1")!!.done)+    }++    @Test fun completeMissingReturnsFalse() = runBlocking {+        assertFalse(CompleteTodoIntent().performCalculation(CompleteTodoData(id = "nope", title = "Nope")))+        assertFalse(CompleteTodoIntent().performCalculation(CompleteTodoData()))+    }++    @Test fun completeBlankIdFallsThroughToTitle() = runBlocking {+        repo.upsert(Todo(syncId = "b1", title = "Blank id task"))+        assertTrue(CompleteTodoIntent().performCalculation(CompleteTodoData(id = "  ", title = "Blank id task")))+        assertTrue(repo.getBySyncId("b1")!!.done)+    }++    // --- Widgets: data path only (Glance rendering skipped, host-bound) ---++    @Test fun todayWidgetLoadsTodaysRowsWithOverdueFlag() = runBlocking {+        val now = System.currentTimeMillis()+        repo.upsert(Todo(syncId = "over", title = "Overdue", dueAt = now - 86_400_000L))+        repo.upsert(Todo(syncId = "today", title = "Today", dueAt = now))+        repo.upsert(Todo(syncId = "future", title = "Future", dueAt = now + 86_400_000L))+        repo.upsert(Todo(syncId = "done", title = "Done", dueAt = now, done = true, completedAt = now))+        val data: com.vayunmathur.todo.widget.TodayWidgetData =+            blockingWidget(TodayWidget(), "loadData", context, AppWidgetId(11))+        assertEquals(setOf("Overdue", "Today"), data.rows.map { it.title }.toSet())+        assertTrue(data.rows.first { it.syncId == "over" }.overdue)+        assertFalse(data.rows.first { it.syncId == "today" }.overdue)+    }++    @Test fun todayWidgetPreviewHasThreeRowsAndQuickWidgetLoadsUnit() = runBlocking {+        val preview: com.vayunmathur.todo.widget.TodayWidgetData = callWidget(TodayWidget(), "previewData", context)+        assertEquals(3, preview.rows.size)+        assertTrue(preview.rows.first().overdue)+        assertFalse(preview.rows.last().overdue)+        val quick: Unit = blockingWidget(QuickAddWidget(), "loadData", context, AppWidgetId(12))+        assertEquals(Unit, quick)+        assertEquals(Unit, callWidget<Unit>(QuickAddWidget(), "previewData", context))+    }++    @Test fun widgetProvideGlanceAndPreviewRunWithoutCrashing() = runBlocking {+        repo.upsert(Todo(syncId = "wg1", title = "Glance task", dueAt = System.currentTimeMillis()))+        // MaWidget.provideGlance/providePreview compose Content internally;+        // under Robolectric there is no widget host, so this is a smoke entry+        // (precedent: calendar's Glance widget tests) — Glance rendering to+        // RemoteViews remains host-bound and is not asserted here.+        TodayWidget().providePreview(context, 0)+        TodayWidget().provideGlance(context, AppWidgetId(21))+        QuickAddWidget().providePreview(context, 0)+        QuickAddWidget().provideGlance(context, AppWidgetId(22))+    }++    @Test fun completeTaskActionCompletesAndIgnoresMissingOrDone() = runBlocking {+        repo.upsert(Todo(syncId = "w1", title = "Widget task"))+        repo.upsert(Todo(syncId = "w2", title = "Already done", done = true, completedAt = 1L))+        val action = CompleteTaskAction()+        action.onAction(context, AppWidgetId(13), actionParametersOf(CompleteTaskAction.SYNC_ID to "w1"))+        assertTrue(repo.getBySyncId("w1")!!.done)+        action.onAction(context, AppWidgetId(13), actionParametersOf(CompleteTaskAction.SYNC_ID to "w2"))+        action.onAction(context, AppWidgetId(13), actionParametersOf(CompleteTaskAction.SYNC_ID to "missing"))+        // No SYNC_ID parameter at all: returns without touching anything.+        action.onAction(context, AppWidgetId(13), actionParametersOf())+        assertEquals(1, repo.getAll().count { it.done && it.syncId == "w2" })+    }+}
todo/src/test/java/com/vayunmathur/todo/notifications/ReceiversAndBackgroundTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/notifications/ReceiversAndBackgroundTest.kt b/todo/src/test/java/com/vayunmathur/todo/notifications/ReceiversAndBackgroundTest.ktnew file mode 100644index 0000000000..01e181cf16--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/notifications/ReceiversAndBackgroundTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.todo.notifications++import android.app.Application+import android.content.ComponentName+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.todo.data.TestTodoRepository+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.data.awaitCondition+import com.vayunmathur.todo.platform.TodoBackground+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * [ReminderActionReceiver] (complete/snooze from a notification), [BootReceiver]+ * re-arming, and [TodoBackground]'s data-change reactions, all against the+ * in-memory repository singleton. Receivers are delivered as real broadcasts:+ * calling `onReceive` directly leaves `goAsync()` without a pending result.+ */+@RunWith(RobolectricTestRunner::class)+class ReceiversAndBackgroundTest {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private var harness: TestTodoRepository? = null+    private val repo get() = harness!!.repository++    @BeforeTest fun setUp() { harness = TestTodoRepository.create(context) }+    @AfterTest fun tearDown() { harness?.close(); harness = null }++    private fun deliver(receiver: Class<*>, intent: Intent) {+        context.sendBroadcast(intent.setComponent(ComponentName(context, receiver)))+        shadowOf(android.os.Looper.getMainLooper()).idle()+    }++    private fun await(description: String, condition: suspend () -> Boolean) = runBlocking {+        assertTrue(awaitCondition { condition() }, "Timed out: $description")+    }++    // --- ReminderActionReceiver ---++    @Test fun reminderActionCompleteMarksTodoDone() = runBlocking {+        repo.upsert(Todo(syncId = "ra1", title = "Complete me"))+        deliver(+            ReminderActionReceiver::class.java,+            Intent(ReminderActionReceiver.ACTION_COMPLETE)+                .putExtra(ReminderScheduler.EXTRA_SYNC_ID, "ra1"),+        )+        await("complete lands") { repo.getBySyncId("ra1")?.done == true }+    }++    @Test fun reminderActionSnoozeHourMovesReminderAboutAnHour() = runBlocking {+        val before = System.currentTimeMillis()+        repo.upsert(Todo(syncId = "ra2", title = "Snooze me", reminderAt = before))+        deliver(+            ReminderActionReceiver::class.java,+            Intent(ReminderActionReceiver.ACTION_SNOOZE)+                .putExtra(ReminderScheduler.EXTRA_SYNC_ID, "ra2")+                .putExtra(ReminderActionReceiver.EXTRA_SNOOZE, ReminderActionReceiver.SNOOZE_HOUR),+        )+        await("snooze lands") { (repo.getBySyncId("ra2")?.reminderAt ?: 0) > before }+        val until = repo.getBySyncId("ra2")!!.reminderAt!!+        assertTrue(until >= before + 3_600_000L - 5_000 && until <= System.currentTimeMillis() + 3_600_000L + 5_000)+        assertFalse(repo.getBySyncId("ra2")!!.done)+    }++    @Test fun reminderActionSnoozeTomorrowMovesReminderToNextDay() = runBlocking {+        val before = System.currentTimeMillis()+        repo.upsert(Todo(syncId = "ra3", title = "Tomorrow", reminderAt = before))+        deliver(+            ReminderActionReceiver::class.java,+            Intent(ReminderActionReceiver.ACTION_SNOOZE)+                .putExtra(ReminderScheduler.EXTRA_SYNC_ID, "ra3")+                .putExtra(ReminderActionReceiver.EXTRA_SNOOZE, ReminderActionReceiver.SNOOZE_TOMORROW),+        )+        await("tomorrow snooze lands") { (repo.getBySyncId("ra3")?.reminderAt ?: 0) > before + 3_600_000L }+    }++    @Test fun reminderActionUnknownMissingAndNoExtraAreNoOps() = runBlocking {+        repo.upsert(Todo(syncId = "ra4", title = "Untouched", reminderAt = 123L))+        deliver(+            ReminderActionReceiver::class.java,+            Intent("com.example.OTHER").putExtra(ReminderScheduler.EXTRA_SYNC_ID, "ra4"),+        )+        deliver(+            ReminderActionReceiver::class.java,+            Intent(ReminderActionReceiver.ACTION_COMPLETE)+                .putExtra(ReminderScheduler.EXTRA_SYNC_ID, "missing"),+        )+        // Direct call is safe here: it returns before goAsync() when no sync id.+        ReminderActionReceiver().onReceive(context, Intent(ReminderActionReceiver.ACTION_COMPLETE))+        Thread.sleep(300)+        val stored = repo.getBySyncId("ra4")!!+        assertFalse(stored.done)+        assertEquals(123L, stored.reminderAt)+    }++    // --- BootReceiver + TodoBackground ---++    @Test fun bootReceiverRearmsRemindersAndIgnoresOtherActions() = runBlocking {+        val future = System.currentTimeMillis() + 3_600_000L+        repo.upsert(Todo(syncId = "boot1", title = "Boot task", reminderAt = future))+        deliver(BootReceiver::class.java, Intent("com.example.OTHER"))+        deliver(BootReceiver::class.java, Intent(Intent.ACTION_BOOT_COMPLETED))+        await("boot reconcile schedules reminder") {+            context.getSharedPreferences("todo_reminders", Context.MODE_PRIVATE)+                .getStringSet("scheduled", emptySet())!!.contains("boot1")+        }+        deliver(BootReceiver::class.java, Intent(Intent.ACTION_TIME_CHANGED))+        deliver(BootReceiver::class.java, Intent(Intent.ACTION_TIMEZONE_CHANGED))+        deliver(BootReceiver::class.java, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))+    }++    @Test fun todoBackgroundReconcileNowSchedulesFutureReminders() = runBlocking {+        val future = System.currentTimeMillis() + 3_600_000L+        repo.upsert(Todo(syncId = "bg1", title = "Background task", reminderAt = future))+        TodoBackground.reconcileNow(context)+        assertTrue(+            context.getSharedPreferences("todo_reminders", Context.MODE_PRIVATE)+                .getStringSet("scheduled", emptySet())!!.contains("bg1"),+        )+    }++    @Test fun todoBackgroundStartReactsToDataChangesAndIsIdempotent() = runBlocking {+        // TodoApplication already called start() before the harness existed;+        // reset the guard so this start binds the in-memory repository.+        val started = TodoBackground.javaClass.getDeclaredField("started").apply { isAccessible = true }+        (started.get(TodoBackground) as java.util.concurrent.atomic.AtomicBoolean).set(false)+        TodoBackground.start(context)+        // Second start is a no-op behind the atomic guard.+        TodoBackground.start(context)+        val future = System.currentTimeMillis() + 3_600_000L+        repo.upsert(Todo(syncId = "bg2", title = "Watched task", reminderAt = future))+        await("background collector schedules reminder") {+            shadowOf(android.os.Looper.getMainLooper()).idle()+            context.getSharedPreferences("todo_reminders", Context.MODE_PRIVATE)+                .getStringSet("scheduled", emptySet())!!.contains("bg2")+        }+    }+}
todo/src/test/java/com/vayunmathur/todo/sync/CalendarMirrorProviderTest.kt
diff --git a/todo/src/test/java/com/vayunmathur/todo/sync/CalendarMirrorProviderTest.kt b/todo/src/test/java/com/vayunmathur/todo/sync/CalendarMirrorProviderTest.ktnew file mode 100644index 0000000000..1550d463e4--- /dev/null+++ b/todo/src/test/java/com/vayunmathur/todo/sync/CalendarMirrorProviderTest.kt@@ -0,0 +1,253 @@+package com.vayunmathur.todo.sync++import android.Manifest+import android.app.Application+import android.content.ContentProvider+import android.content.ContentProviderOperation+import android.content.ContentProviderResult+import android.content.ContentUris+import android.content.ContentValues+import android.content.Context+import android.database.Cursor+import android.database.MatrixCursor+import android.net.Uri+import android.provider.CalendarContract+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.todo.data.Todo+import com.vayunmathur.todo.domain.DueDates+import com.vayunmathur.todo.domain.Recurrence+import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.ShadowContentResolver+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * In-memory CalendarProvider stand-in under the real calendar authority, so+ * [CalendarMirror]'s full write path (create calendar, insert/update/delete+ * events, delete calendar) runs under Robolectric. Same pattern as the+ * calendar app's FakeCalendarProvider; state is asserted through the provider.+ */+class FakeCalendarProvider : ContentProvider() {+    val calendarIds = mutableListOf<Long>()+    val events = linkedMapOf<Long, ContentValues>()+    var nextCalendarId = 42L+    var nextEventId = 100L+    var insertCount = 0+    var updateCount = 0+    var deleteCount = 0+    var calendarDeleteCount = 0+    var throwOnQuery = false++    override fun onCreate(): Boolean = true+    override fun getType(uri: Uri): String? = null++    override fun query(+        uri: Uri, projection: Array<out String>?, selection: String?,+        selectionArgs: Array<out String>?, sortOrder: String?,+    ): Cursor {+        if (throwOnQuery) throw IllegalStateException("provider boom")+        val cols = projection ?: emptyArray()+        val cursor = MatrixCursor(cols)+        when (uri.pathSegments.firstOrNull()) {+            "calendars" -> calendarIds.forEach { id ->+                cursor.addRow(cols.map { if (it == CalendarContract.Calendars._ID) id else null })+            }+            "events" -> events.forEach { (id, values) ->+                cursor.addRow(cols.map { col ->+                    when (col) {+                        CalendarContract.Events._ID -> id+                        CalendarContract.Events._SYNC_ID -> values.getAsString(CalendarContract.Events._SYNC_ID)+                        CalendarContract.Events.SYNC_DATA1 -> values.getAsString(CalendarContract.Events.SYNC_DATA1)+                        else -> values.get(col)+                    }+                })+            }+        }+        return cursor+    }++    override fun insert(uri: Uri, values: ContentValues?): Uri {+        val copy = ContentValues(values)+        return when (uri.pathSegments.firstOrNull()) {+            "calendars" -> {+                val id = nextCalendarId+++                calendarIds += id+                ContentUris.withAppendedId(uri, id)+            }+            else -> {+                val id = nextEventId+++                events[id] = copy+                insertCount+++                ContentUris.withAppendedId(uri, id)+            }+        }+    }++    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {+        val id = ContentUris.parseId(uri)+        if (events.containsKey(id)) {+            events[id] = ContentValues(values)+            updateCount+++            return 1+        }+        return 0+    }++    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =+        when (uri.pathSegments.firstOrNull()) {+            "calendars" -> {+                calendarIds.remove(ContentUris.parseId(uri))+                calendarDeleteCount+++                1+            }+            else -> {+                if (events.remove(ContentUris.parseId(uri)) != null) { deleteCount++; 1 } else 0+            }+        }++    override fun applyBatch(operations: ArrayList<ContentProviderOperation>): Array<ContentProviderResult> {+        val results = ArrayList<ContentProviderResult>(operations.size)+        for ((index, op) in operations.withIndex()) {+            results += when {+                op.isDelete -> ContentProviderResult(delete(op.uri, null, null))+                op.isUpdate -> ContentProviderResult(+                    update(op.uri, op.resolveValueBackReferences(results.toTypedArray(), index), null, null),+                )+                else -> {+                    insert(op.uri, op.resolveValueBackReferences(results.toTypedArray(), index))+                    ContentProviderResult(1)+                }+            }+        }+        return results.toTypedArray()+    }+}++@RunWith(RobolectricTestRunner::class)+class CalendarMirrorProviderTest {+    private val context: Context get() = ApplicationProvider.getApplicationContext()+    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private lateinit var provider: FakeCalendarProvider++    @BeforeTest fun setUp() {+        provider = FakeCalendarProvider()+        ShadowContentResolver.registerProviderInternal(CalendarContract.AUTHORITY, provider)+        shadowOf(app).grantPermissions(Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR)+    }++    private val zone = TimeZone.currentSystemDefault()+    private fun allDayTodo(syncId: String, title: String) = Todo(+        syncId = syncId, title = title,+        dueAt = DueDates.startOfDay(LocalDate(2026, 10, 20), zone), dueAllDay = true,+    )++    @Test fun reconcileCreatesCalendarAndWritesOnlyMirroredTasks() {+        val timed = System.currentTimeMillis() + 3_600_000L+        CalendarMirror.reconcile(+            context, enabled = true,+            todos = listOf(+                Todo(syncId = "t1", title = "Timed", notes = "note", dueAt = timed, dueAllDay = false),+                allDayTodo("t2", "All day"),+                Todo(syncId = "t3", title = "Daily", dueAt = timed, dueAllDay = false, recurrence = Recurrence.Daily(2).serialize()),+                Todo(syncId = "done", title = "Done", dueAt = timed, done = true, completedAt = timed),+                Todo(syncId = "del", title = "Deleted", dueAt = timed, deleted = true),+                Todo(syncId = "nodate", title = "No date"),+                Todo(syncId = "sub", title = "Sub", dueAt = timed, parentSyncId = "t1"),+            ),+        )+        assertEquals(listOf(42L), provider.calendarIds)+        assertEquals(3, provider.events.size)+        val bySync = provider.events.values.associateBy { it.getAsString(CalendarContract.Events._SYNC_ID) }+        assertEquals(setOf("t1", "t2", "t3"), bySync.keys)+        assertEquals("Timed", bySync["t1"]!!.getAsString(CalendarContract.Events.TITLE))+        assertEquals("note", bySync["t1"]!!.getAsString(CalendarContract.Events.DESCRIPTION))+        assertEquals(timed, bySync["t1"]!!.getAsLong(CalendarContract.Events.DTSTART))+        assertEquals(timed + 30 * 60_000L, bySync["t1"]!!.getAsLong(CalendarContract.Events.DTEND))+        assertEquals(0, bySync["t1"]!!.getAsInteger(CalendarContract.Events.ALL_DAY))+        assertEquals(1, bySync["t2"]!!.getAsInteger(CalendarContract.Events.ALL_DAY))+        assertEquals("UTC", bySync["t2"]!!.getAsString(CalendarContract.Events.EVENT_TIMEZONE))+        // All-day duration is one day from its UTC-midnight start.+        assertEquals(+            bySync["t2"]!!.getAsLong(CalendarContract.Events.DTSTART) + 86_400_000L,+            bySync["t2"]!!.getAsLong(CalendarContract.Events.DTEND),+        )+        // Recurring: RRULE + DURATION, no DTEND value.+        assertNotNull(bySync["t3"]!!.getAsString(CalendarContract.Events.RRULE))+        assertEquals("PT30M", bySync["t3"]!!.getAsString(CalendarContract.Events.DURATION))+        assertTrue(bySync.values.all { it.getAsString(CalendarContract.Events.SYNC_DATA1) != null })+        assertTrue(bySync.values.all { it.getAsLong(CalendarContract.Events.CALENDAR_ID) == 42L })+    }++    @Test fun reconcileSecondRunIsStableThenUpdatesAndDeletesChangedRows() {+        val timed = System.currentTimeMillis() + 3_600_000L+        val todos = listOf(+            Todo(syncId = "a", title = "Alpha", dueAt = timed, dueAllDay = false),+            Todo(syncId = "b", title = "Beta", dueAt = timed, dueAllDay = false),+        )+        CalendarMirror.reconcile(context, enabled = true, todos = todos)+        assertEquals(2, provider.insertCount)+        // Unchanged: fingerprints match, so no further writes.+        CalendarMirror.reconcile(context, enabled = true, todos = todos)+        assertEquals(2, provider.insertCount)+        assertEquals(0, provider.updateCount)+        assertEquals(0, provider.deleteCount)+        // Changed title updates in place; dropping "b" deletes its event.+        CalendarMirror.reconcile(+            context, enabled = true,+            todos = listOf(Todo(syncId = "a", title = "Alpha renamed", dueAt = timed, dueAllDay = false)),+        )+        assertEquals(1, provider.updateCount)+        assertEquals(1, provider.deleteCount)+        assertEquals(2, provider.insertCount)+        assertEquals(1, provider.events.size)+        assertEquals(+            "Alpha renamed",+            provider.events.values.single().getAsString(CalendarContract.Events.TITLE),+        )+    }++    @Test fun reconcileReusesExistingCalendarInsteadOfCreatingAnother() {+        provider.calendarIds += 7L+        val timed = System.currentTimeMillis() + 3_600_000L+        CalendarMirror.reconcile(+            context, enabled = true,+            todos = listOf(Todo(syncId = "a", title = "Alpha", dueAt = timed, dueAllDay = false)),+        )+        assertEquals(listOf(7L), provider.calendarIds)+        assertEquals(7L, provider.events.values.single().getAsLong(CalendarContract.Events.CALENDAR_ID))+    }++    @Test fun reconcileDisabledDeletesCalendarAndDisabledWithoutCalendarIsNoOp() {+        val timed = System.currentTimeMillis() + 3_600_000L+        CalendarMirror.reconcile(+            context, enabled = true,+            todos = listOf(Todo(syncId = "a", title = "Alpha", dueAt = timed, dueAllDay = false)),+        )+        assertEquals(1, provider.calendarIds.size)+        CalendarMirror.reconcile(context, enabled = false, todos = emptyList())+        assertTrue(provider.calendarIds.isEmpty())+        assertEquals(1, provider.calendarDeleteCount)+        // Already gone: nothing more to delete.+        CalendarMirror.reconcile(context, enabled = false, todos = emptyList())+        assertEquals(1, provider.calendarDeleteCount)+    }++    @Test fun reconcileSwallowsProviderFailures() {+        provider.throwOnQuery = true+        // Must not throw even though every provider query fails.+        CalendarMirror.reconcile(+            context, enabled = true,+            todos = listOf(Todo(syncId = "a", title = "Alpha", dueAt = System.currentTimeMillis(), dueAllDay = false)),+        )+        assertTrue(provider.events.isEmpty())+        assertNull(provider.calendarIds.singleOrNull())+    }+}