package com.cottondb.android.platform import android.app.AlarmManager import android.content.Intent import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class ScheduleChangeReceiverTest { @Test fun bootClearsLostOSClaimsThenEnqueuesWithoutDeletingAlarmHistory(): Unit = runBlocking { val boundary = RecordingBoundary() handleScheduleChange(Intent.ACTION_BOOT_COMPLETED, boundary) assertEquals(listOf("clearBoot", "enqueue"), boundary.calls) } @Test fun timezoneChangeCancelsHeldRemindersBeforeReconciliation(): Unit = runBlocking { val boundary = RecordingBoundary() handleScheduleChange(Intent.ACTION_TIMEZONE_CHANGED, boundary) assertEquals(listOf("cancelTimeZone", "enqueue"), boundary.calls) } @Test fun exactAlarmAccessChangeClearsPendingIdentitiesBeforeReconciliation(): Unit = runBlocking { val boundary = RecordingBoundary() handleScheduleChange(AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED, boundary) assertEquals(listOf("cancelAlarmClaims", "enqueue"), boundary.calls) } @Test fun ordinaryTimeChangeOnlyEnqueuesReconciliation(): Unit = runBlocking { val boundary = RecordingBoundary() handleScheduleChange(Intent.ACTION_TIME_CHANGED, boundary) assertEquals(listOf("enqueue"), boundary.calls) } @Test fun alarmClaimCleanupFailurePreventsReconciliation(): Unit = runBlocking { val boundary = RecordingBoundary(failAlarmCancellation = true) val failure = runCatching { handleScheduleChange(AlarmManager.ACTION_SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED, boundary) }.exceptionOrNull() assertEquals("could not cancel alarm claims", failure?.message) assertEquals(listOf("cancelAlarmClaims"), boundary.calls) } @Test fun cleanupFailurePreventsAStaleReconciliationPass(): Unit = runBlocking { val boundary = RecordingBoundary(failCancellation = true) val failure = runCatching { handleScheduleChange(Intent.ACTION_TIMEZONE_CHANGED, boundary) }.exceptionOrNull() assertEquals("could not cancel held reminders", failure?.message) assertEquals(listOf("cancelTimeZone"), boundary.calls) } private class RecordingBoundary( private val failCancellation: Boolean = false, private val failAlarmCancellation: Boolean = false, ) : ScheduleChangeBoundary { val calls = mutableListOf() override suspend fun clearBootClaims() { calls += "clearBoot" } override suspend fun cancelRemindersForTimeZoneChange() { calls += "cancelTimeZone" check(!failCancellation) { "could not cancel held reminders" } } override suspend fun cancelAlarmClaimsForAccessChange() { calls += "cancelAlarmClaims" check(!failAlarmCancellation) { "could not cancel alarm claims" } } override suspend fun enqueueReconciliation() { calls += "enqueue" } } }