145 lines · 6.0 KB · KotlinRaw
package com.cottondb.android.platformimport android.Manifestimport android.app.AlarmManagerimport android.app.PendingIntentimport android.content.Intentimport android.net.Uriimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.day.alarms.Alarmimport com.cottondb.android.reminders.NotificationPermissionimport com.cottondb.android.reminders.NotificationPrefsimport java.io.Fileimport java.time.Clockimport java.time.Instantimport java.time.ZoneIdimport java.time.ZoneOffsetimport java.util.UUIDimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNotNullimport org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Assume.assumeTrueimport org.junit.Testimport 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 }}