package com.cottondb.android.platform import android.Manifest import android.app.AlarmManager import android.app.PendingIntent import android.content.Intent import android.net.Uri import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.day.alarms.Alarm import com.cottondb.android.reminders.NotificationPermission import com.cottondb.android.reminders.NotificationPrefs import java.io.File import java.time.Clock import java.time.Instant import java.time.ZoneId import java.time.ZoneOffset import java.util.UUID import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assume.assumeTrue import org.junit.Test import org.junit.runner.RunWith /** Device boundary: uses the real AlarmManager and production PendingIntent identity. */ @androidx.test.filters.SdkSuppress(minSdkVersion = 31) @RunWith(AndroidJUnit4::class) class AndroidAlarmManagerTest { private val instrumentation = InstrumentationRegistry.getInstrumentation() private val context = instrumentation.targetContext private val manager = context.getSystemService(AlarmManager::class.java) private val directory = File(context.noBackupFilesDir, "alarm-manager-test-${UUID.randomUUID()}") private val ledger = File(directory, "ledger.json") private val clock = Clock.fixed(Instant.parse("2036-01-03T06:00:00Z"), ZoneOffset.UTC) @After fun removeLedgerAndAnyTestPendingIntent() { testPendingIntent(PendingIntent.FLAG_NO_CREATE)?.let { pending -> manager.cancel(pending) pending.cancel() } directory.deleteRecursively() } @Test fun realAlarmManagerSchedulesAlarmClockAndProductionCancellationRemovesPendingIntent() { val automation = instrumentation.uiAutomation val adopted = runCatching { automation.adoptShellPermissionIdentity(Manifest.permission.SCHEDULE_EXACT_ALARM) }.isSuccess try { // The shell identity is temporary and is always dropped below. Exact-alarm app-op // access may still be unavailable on a device image, in which case this boundary // test skips instead of changing persistent global state. assumeTrue("This device does not allow exact alarms for Cotton", manager.canScheduleExactAlarms()) val alarm = Alarm( id = TEST_ID, label = "Instrumentation alarm", hour = 7, minute = 0, repeatDays = emptyList(), enabled = true, sound = false, createdAt = null, updatedAt = null, ) val scheduler = AndroidAlarmScheduler( ledgerStore = AndroidAlarmLedgerStore( context = context, file = ledger, bootCount = { BootCountRead.Available(TEST_BOOT) }, ), platform = AndroidExactAlarmPlatform(context), clock = clock, ) val scheduled = scheduler.reconcile( alarms = listOf(alarm), zoneId = ZoneId.of("UTC"), prefs = NotificationPrefs(), notificationPermission = NotificationPermission.Granted, ) assertEquals(AlarmScheduleOutcome.Applied(1, 0, emptyList()), scheduled) val alarmClock = manager.nextAlarmClock assertNotNull("AlarmManager did not expose the scheduled AlarmClock", alarmClock) assertEquals(Instant.parse("2036-01-03T07:00:00Z").toEpochMilli(), alarmClock!!.triggerTime) assertNotNull("AlarmClock needs a show intent", alarmClock.showIntent) assertEquals(context.packageName, alarmClock.showIntent.creatorPackage) assertTrue("The production receiver PendingIntent was not created", testPendingIntent(PendingIntent.FLAG_NO_CREATE) != null) val cancelled = scheduler.reconcile( alarms = emptyList(), zoneId = ZoneId.of("UTC"), prefs = NotificationPrefs(), notificationPermission = NotificationPermission.Granted, ) assertEquals(AlarmScheduleOutcome.Applied(0, 1, emptyList()), cancelled) assertNull("Cancellation must also retire the PendingIntent identity", testPendingIntent(PendingIntent.FLAG_NO_CREATE)) } finally { if (adopted) automation.dropShellPermissionIdentity() } } private fun testPendingIntent(flags: Int): PendingIntent? { val firesAt = Instant.parse("2036-01-03T07:00:00Z").toEpochMilli() val key = "cotton:alarm:$TEST_ID" val token = alarmFireToken(alarmSignature(), firesAt) return PendingIntent.getBroadcast( context, key.hashCode() and Int.MAX_VALUE, Intent(context, AndroidAlarmReceiver::class.java) .setAction(AndroidExactAlarmPlatform.ACTION_FIRE) .setData(Uri.Builder().scheme("cotton").authority("alarm").appendPath(key).appendPath(token).build()) .putExtra(AndroidExactAlarmPlatform.EXTRA_KEY, key) .putExtra(AndroidExactAlarmPlatform.EXTRA_FIRE_TOKEN, token) .putExtra(AndroidExactAlarmPlatform.EXTRA_FIRES_AT, firesAt), flags or PendingIntent.FLAG_IMMUTABLE, ) } private fun alarmSignature(): String = com.cottondb.android.day.alarms.alarmSignature( Alarm( id = TEST_ID, label = "Instrumentation alarm", hour = 7, minute = 0, repeatDays = emptyList(), enabled = true, sound = false, createdAt = null, updatedAt = null, ), ZoneId.of("UTC"), ) private companion object { const val TEST_ID = "instrumented-alarm-manager" const val TEST_BOOT = 91 } }