Modern Apps git

← Modern-Apps.git

parentalcontrols: add tests for windows, PIN, rules, enforcer-adjacent state and screens

Commit
7528c857debb72e7d3f08864589b6d1f08459bcd
Author
Vayun Mathur <[email protected]>
When
2026-11-07 05:59 UTC (29 days ago)
Parents
8e4597d
Adds the module's first tests (9 files): TimeWindow and schedule
window semantics (same-day, cross-midnight, day masks), Room DAO and
SupervisionRules round-trips on in-memory databases, platform state
(SupervisionMaster, WebContentFilters, LimitState, BedtimeScheduler
alarms, AppLimits with no usage access, UsageAccess, SupervisionApis,
SupervisionCaller), the full ParentPin lifecycle (set, verify,
failure lockout, clear) against a test-only in-memory AndroidKeyStore
JCA provider since Robolectric has none, SupervisionViewModel edits
against a real repository, the supervision Messenger service
(denied strangers, answers for the Settings uid, unknown APIs), lock
notifications, Robolectric Compose tests for every screen (PIN gate
and setup, lock screens, dashboard, bedtime, app limits, daily limit,
window schedules, web filters), and activity tests including the
PIN-gated editors unlocked through a delivered gate result.

Coverage (merged INSTRUCTION): 0% (no tests; the merged task
produced no report) -> 80.1% (11892/14853).

Untestable remainder: Enforcer (1070 instructions), SupervisionPolicies
and ParentalControlsAppService - all require the MaOS-only
android.app.supervision framework classes, which are compileOnly
stubs and absent from Robolectric's android-all, so Enforcer cannot
even be constructed on the JVM; also the receivers' Enforcer-bound
async bodies, the lock-screen bonus grant (same path), ParentPin's
hardware-keystore storage on a real device, and Room migration 1->2.

Verified: :parentalcontrols:testDevUnitTest passes (two full runs)
and :parentalcontrols:lint passes.
(cherry picked from commit 08a9f8519151d28310793ed65b38ece7b627a4bc)

Diff

parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabaseTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabaseTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabaseTest.ktnew file mode 100644index 0000000000..4903f69766--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/ParentalControlsDatabaseTest.kt@@ -0,0 +1,80 @@+package com.vayunmathur.parentalcontrols.data++import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class ParentalControlsDatabaseTest {++    private lateinit var db: ParentalControlsDatabase++    @BeforeTest+    fun setUp() {+        val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()+        db = Room.inMemoryDatabaseBuilder(ctx, ParentalControlsDatabase::class.java)+            .setSingleConnectionPool()+            .allowMainThreadQueries().build()+    }++    // No close(): Robolectric's in-memory SQLite store is shared per sandbox, and closing+    // one Room instance drops the tables under the repository's cached instance.++    @Test+    fun appRuleCrudAndOrdering() = runTest {+        val dao = db.appRuleDao()+        assertTrue(dao.all().isEmpty())+        dao.upsert(AppRule("com.zeta", dailyLimitMinutes = 30))+        dao.upsert(AppRule("com.alpha", blockedAtBedtime = true))+        dao.upsert(AppRule("com.mid", allowedInDowntime = true))+        assertEquals(listOf("com.alpha", "com.mid", "com.zeta"), dao.allFlow().first().map { it.packageName })+        assertEquals(30, dao.byPackage("com.zeta")?.dailyLimitMinutes)+        assertNull(dao.byPackage("com.missing"))+        dao.upsert(AppRule("com.zeta", dailyLimitMinutes = 45))+        assertEquals(45, dao.byPackage("com.zeta")?.dailyLimitMinutes)+        dao.delete(AppRule("com.zeta"))+        assertNull(dao.byPackage("com.zeta"))+        assertEquals(2, dao.all().size)+    }++    @Test+    fun scheduleDaosRoundTripSingletons() = runTest {+        assertNull(db.bedtimeDao().schedule())+        db.bedtimeDao().upsert(BedtimeSchedule(enabled = true, startMinute = 1200, endMinute = 400))+        assertEquals(1200, db.bedtimeDao().schedule()?.startMinute)+        assertEquals(1200, db.bedtimeDao().scheduleFlow().first()?.startMinute)+        db.downtimeDao().upsert(DowntimeSchedule(enabled = true, daysMask = 3))+        assertEquals(3, db.downtimeDao().scheduleFlow().first()?.daysMask)+        db.schoolTimeDao().upsert(SchoolTimeSchedule(enabled = true, endMinute = 800))+        assertEquals(800, db.schoolTimeDao().schedule()?.endMinute)+        // Upsert replaces the singleton row.+        db.bedtimeDao().upsert(BedtimeSchedule(enabled = false))+        assertEquals(false, db.bedtimeDao().schedule()?.enabled)+    }++    @Test+    fun dailyLimitAndBonusGrants() = runTest {+        assertNull(db.dailyLimitDao().limit())+        db.dailyLimitDao().upsert(DailyLimit(dailyLimitMinutes = 120))+        assertEquals(120, db.dailyLimitDao().limitFlow().first()?.dailyLimitMinutes)+        db.dailyLimitDao().upsert(DailyLimit(dailyLimitMinutes = null))+        assertNull(db.dailyLimitDao().limit()?.dailyLimitMinutes)++        val bonus = db.bonusGrantDao()+        bonus.upsert(BonusGrant(packageName = "com.a", bonusMinutes = 15, day = "2026-11-06"))+        bonus.upsert(BonusGrant(packageName = null, bonusMinutes = 30, day = "2026-11-06"))+        bonus.upsert(BonusGrant(packageName = "com.a", bonusMinutes = 99, day = "2026-11-05"))+        assertEquals(2, bonus.forDay("2026-11-06").size)+        bonus.pruneForeignDays("2026-11-06")+        assertTrue(bonus.forDay("2026-11-05").isEmpty())+        assertEquals(45, bonus.forDay("2026-11-06").sumOf { it.bonusMinutes })+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/SupervisionRulesTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/SupervisionRulesTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/SupervisionRulesTest.ktnew file mode 100644index 0000000000..2d58d7b046--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/data/SupervisionRulesTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.parentalcontrols.data++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class SupervisionRulesTest {++    companion object {+        private var sharedDb: ParentalControlsDatabase? = null+    }++    private lateinit var rules: SupervisionRules++    @BeforeTest+    fun setUp() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        val mem = sharedDb ?: Room.inMemoryDatabaseBuilder(app, ParentalControlsDatabase::class.java)+            .setSingleConnectionPool()+            .setSingleConnectionPool()+            .allowMainThreadQueries().build().also { sharedDb = it }+        synchronized(databases) { databases[ParentalControlsDatabase::class] = mem }+        rules = SupervisionRules.get(app)+    }++    @Test+    fun rulesCrudAndLimitedFilter() = runBlocking {+        rules.upsert(AppRule("com.rules.a", dailyLimitMinutes = 20))+        rules.upsert(AppRule("com.rules.b", blockedAtBedtime = true))+        assertEquals(20, rules.rule("com.rules.a")?.dailyLimitMinutes)+        assertTrue(rules.allRulesNow().any { it.packageName == "com.rules.b" })+        assertEquals(listOf("com.rules.a"), rules.limitedRules.first().map { it.packageName })+        assertTrue(rules.allRules.first().size >= 2)+        rules.delete(AppRule("com.rules.b"))+        assertNull(rules.rule("com.rules.b"))+    }++    @Test+    fun schedulesDefaultAndPersist() = runBlocking {+        // A row always comes back (defaulted in the DAO layer when unset, never null).+        val initial = rules.scheduleNow()+        assertEquals(BedtimeSchedule.SINGLETON_ID, initial.id)+        rules.setSchedule(BedtimeSchedule(enabled = true, startMinute = 1300, endMinute = 300))+        assertEquals(1300, rules.scheduleNow().startMinute)+        assertEquals(1300, rules.schedule.first().startMinute)+        rules.setDowntime(DowntimeSchedule(enabled = true, daysMask = 5))+        assertEquals(5, rules.downtimeNow().daysMask)+        assertEquals(5, rules.downtimeSchedule.first().daysMask)+        rules.setSchoolTime(SchoolTimeSchedule(enabled = true, endMinute = 777))+        assertEquals(777, rules.schoolTimeNow().endMinute)+        assertEquals(777, rules.schoolTimeSchedule.first().endMinute)+        assertEquals("parentalcontrols-db", DB_NAME)+    }++    @Test+    fun dailyLimitAndBonusesWithPruning() = runBlocking {+        assertNull(rules.dailyLimitNow())+        rules.setDailyLimit(90)+        assertEquals(90, rules.dailyLimitNow())+        assertEquals(90, rules.dailyLimitMinutes.first())+        rules.setDailyLimit(null)+        assertNull(rules.dailyLimitNow())+        rules.grantBonus(BonusGrant(packageName = "com.rules.a", bonusMinutes = 10, day = "2026-01-01"))+        rules.grantBonus(BonusGrant(packageName = null, bonusMinutes = 5, day = "2026-01-02"))+        // bonusesToday prunes the foreign-day row first.+        val today = rules.bonusesToday("2026-01-02")+        assertEquals(1, today.size)+        assertEquals(5, today.single().bonusMinutes)+        assertTrue(rules.bonusesToday("2026-01-01").isEmpty())+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/TimeWindowTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/TimeWindowTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/TimeWindowTest.ktnew file mode 100644index 0000000000..dbd92bf0b4--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/TimeWindowTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.parentalcontrols.domain++import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.DailyLimit+import com.vayunmathur.parentalcontrols.data.DowntimeSchedule+import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++class TimeWindowTest {++    @Test+    fun disabledWindowContainsNothing() {+        val window = TimeWindow(enabled = false, startMinute = 0, endMinute = 1439)+        assertFalse(window.contains(0, 0))+        assertFalse(window.contains(3, 720))+    }++    @Test+    fun sameDayWindowBoundaries() {+        // Monday=0. 09:00 (540) to 17:00 (1020), all days.+        val window = TimeWindow(enabled = true, startMinute = 540, endMinute = 1020)+        assertFalse(window.contains(0, 539))+        assertTrue(window.contains(0, 540))+        assertTrue(window.contains(0, 1019))+        assertFalse(window.contains(0, 1020))+    }++    @Test+    fun dayMaskRestrictsDays() {+        val weekdays = TimeWindow(enabled = true, startMinute = 0, endMinute = 60, daysMask = TimeWindow.WEEKDAYS)+        assertTrue(weekdays.contains(0, 30)) // Monday+        assertTrue(weekdays.contains(4, 30)) // Friday+        assertFalse(weekdays.contains(5, 30)) // Saturday+        assertFalse(weekdays.contains(6, 30)) // Sunday+        assertTrue(weekdays.isDaySet(0))+        assertFalse(weekdays.isDaySet(6))+    }++    @Test+    fun crossMidnightWindowEveningAndMorningHalves() {+        // Friday (4) 21:00 -> 07:00.+        val fridayOnly = 1 shl 4+        val window = TimeWindow(enabled = true, startMinute = 21 * 60, endMinute = 7 * 60, daysMask = fridayOnly)+        assertTrue(window.contains(4, 21 * 60)) // Friday evening opens+        assertTrue(window.contains(4, 23 * 60 + 59))+        assertFalse(window.contains(4, 20 * 60 + 59))+        assertFalse(window.contains(4, 2 * 60)) // Friday 02:00 belongs to Thursday's window+        assertTrue(window.contains(5, 2 * 60)) // Saturday 02:00 is Friday window's morning half+        assertTrue(window.contains(5, 6 * 60 + 59))+        assertFalse(window.contains(5, 7 * 60))+        assertFalse(window.contains(5, 22 * 60)) // Saturday evening is not Friday's window+    }++    @Test+    fun constantsAndDefaults() {+        assertEquals(7, TimeWindow.DAYS_IN_WEEK)+        assertEquals(127, TimeWindow.ALL_DAYS)+        assertEquals(31, TimeWindow.WEEKDAYS)+        assertEquals(1440, TimeWindow.MINUTES_PER_DAY)+        val bedtime = BedtimeSchedule()+        assertEquals(0, bedtime.id)+        assertEquals(21 * 60, bedtime.startMinute)+        assertEquals(7 * 60, bedtime.endMinute)+        assertFalse(bedtime.enabled)+        assertEquals(12 * 60, DowntimeSchedule().startMinute)+        assertEquals(14 * 60, DowntimeSchedule().endMinute)+        val school = SchoolTimeSchedule()+        assertEquals(8 * 60, school.startMinute)+        assertEquals(15 * 60, school.endMinute)+        assertEquals(TimeWindow.WEEKDAYS, school.daysMask)+        assertEquals(null, DailyLimit().dailyLimitMinutes)+    }++    @Test+    fun schedulesDelegateToWindowSemantics() {+        val bedtime = BedtimeSchedule(enabled = true) // 21:00-07:00 all days+        assertTrue(bedtime.contains(0, 22 * 60))+        assertTrue(bedtime.contains(1, 3 * 60)) // morning half of Monday's window+        assertFalse(bedtime.contains(0, 12 * 60))+        assertTrue(bedtime.isDaySet(6))+        val downtime = DowntimeSchedule(enabled = true) // 12:00-14:00+        assertTrue(downtime.contains(2, 13 * 60))+        assertFalse(downtime.contains(2, 14 * 60))+        val school = SchoolTimeSchedule(enabled = true) // weekdays 08:00-15:00+        assertTrue(school.contains(0, 9 * 60))+        assertFalse(school.contains(5, 9 * 60)) // Saturday+        // Disabled schedules contain nothing.+        assertFalse(BedtimeSchedule().contains(0, 22 * 60))+        assertFalse(DowntimeSchedule().contains(0, 13 * 60))+        assertFalse(SchoolTimeSchedule().contains(0, 9 * 60))+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/FakeAndroidKeyStore.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/FakeAndroidKeyStore.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..75d6ceaeb1--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/FakeAndroidKeyStore.kt@@ -0,0 +1,77 @@+package com.vayunmathur.parentalcontrols.platform++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * A minimal in-memory `AndroidKeyStore` JCA provider for Robolectric, which has no+ * AndroidKeyStore implementation. It only supports what [com.vayunmathur.library.util.DatabaseHelper]+ * (and therefore the parent PIN) touches: storing one AES key per alias and handing it+ * back for standard SunJCE AES/GCM ciphers. Install once per test class with+ * [installFakeAndroidKeyStore].+ */+object FakeAndroidKeyStore {+    val keys = mutableMapOf<String, SecretKey>()++    @Synchronized+    fun install() {+        if (Security.getProvider("AndroidKeyStore") == null) {+            Security.addProvider(FakeAndroidKeyStoreProvider())+        }+    }+}++class FakeAndroidKeyStoreProvider : Provider("AndroidKeyStore", 1.0, "test-only in-memory AndroidKeyStore") {+    init {+        put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+        put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+    }+}++class FakeKeyStoreSpi : KeyStoreSpi() {+    override fun engineGetKey(alias: String, password: CharArray?): Key? = FakeAndroidKeyStore.keys[alias]+    override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+    override fun engineGetCertificate(alias: String): Certificate? = null+    override fun engineGetCreationDate(alias: String): Date = Date()+    override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+        FakeAndroidKeyStore.keys[alias] = key as SecretKey+    }+    override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) {+        FakeAndroidKeyStore.keys[alias] = SecretKeySpec(key, "AES")+    }+    override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+    override fun engineDeleteEntry(alias: String) { FakeAndroidKeyStore.keys.remove(alias) }+    override fun engineAliases(): Enumeration<String> = java.util.Collections.enumeration(FakeAndroidKeyStore.keys.keys)+    override fun engineContainsAlias(alias: String): Boolean = FakeAndroidKeyStore.keys.containsKey(alias)+    override fun engineSize(): Int = FakeAndroidKeyStore.keys.size+    override fun engineIsKeyEntry(alias: String): Boolean = FakeAndroidKeyStore.keys.containsKey(alias)+    override fun engineIsCertificateEntry(alias: String): Boolean = false+    override fun engineGetCertificateAlias(cert: Certificate): String? = null+    override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+    override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+}++class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+    private var alias: String = "key"+    override fun engineInit(random: SecureRandom) = Unit+    override fun engineInit(keysize: Int, random: SecureRandom) = Unit+    override fun engineInit(params: java.security.spec.AlgorithmParameterSpec?, random: SecureRandom) {+        if (params is KeyGenParameterSpec) alias = params.keystoreAlias+    }+    override fun engineGenerateKey(): SecretKey {+        val bytes = ByteArray(32).also { SecureRandom().nextBytes(it) }+        return SecretKeySpec(bytes, "AES").also { FakeAndroidKeyStore.keys[alias] = it }+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.ktnew file mode 100644index 0000000000..d495ea3a34--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt@@ -0,0 +1,78 @@+package com.vayunmathur.parentalcontrols.platform++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import com.vayunmathur.parentalcontrols.auth.ParentPin+import com.vayunmathur.parentalcontrols.data.AppRule+import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.ParentalControlsDatabase+import com.vayunmathur.parentalcontrols.data.SupervisionRules+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertSame+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class ParentPinTest {++    companion object {+        private var sharedDb: ParentalControlsDatabase? = null+    }++    private lateinit var app: Application+    private lateinit var rules: SupervisionRules++    @BeforeTest+    fun setUp() {+        app = ApplicationProvider.getApplicationContext<Application>()+        val mem = sharedDb ?: Room.inMemoryDatabaseBuilder(app, ParentalControlsDatabase::class.java)+            .setSingleConnectionPool()+            .setSingleConnectionPool()+            .allowMainThreadQueries().build().also { sharedDb = it }+        synchronized(databases) { databases[ParentalControlsDatabase::class] = mem }+        rules = SupervisionRules.get(app)+    }++    @Test+    fun parentPinSetVerifyLockoutAndClear() {+        FakeAndroidKeyStore.install()+        val pin = ParentPin.get(app)+        pin.clear()+        assertFalse(pin.isSet())+        assertFalse(pin.verify("1234")) // nothing set yet+        pin.set("1234")+        assertTrue(pin.isSet())+        assertTrue(pin.verify("1234"))+        assertFalse(pin.verify("0000"))+        assertTrue(pin.verify("1234")) // a success resets the failure counter+        // Five wrong attempts trigger the one-minute lockout.+        repeat(5) { assertFalse(pin.verify("9999")) }+        assertTrue(pin.isLockedOut())+        assertTrue(pin.lockoutRemainingMillis() > 0L)+        assertFalse(pin.verify("1234")) // even the right PIN is refused while locked out+        pin.clear()+        assertFalse(pin.isSet())+    }++    @Test+    fun parentPinSingletonAndShortPinGuard() {+        val pin = ParentPin.get(app)+        assertSame(pin, ParentPin.get(app))+        assertEquals(4, ParentPin.MIN_LENGTH)+        assertEquals("parentalcontrols_pin", ParentPin.PREFS)+        // Too-short PINs are rejected before any keystore work happens.+        val error = assertFailsWith<IllegalArgumentException> { pin.set("123") }+        assertEquals("PIN too short", error.message)+        // No lockout is recorded on a fresh install.+        assertEquals(0L, pin.lockoutRemainingMillis())+        assertFalse(pin.isLockedOut())+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.ktnew file mode 100644index 0000000000..b62719ce5c--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt@@ -0,0 +1,154 @@+package com.vayunmathur.parentalcontrols.platform++import android.app.AlarmManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.DowntimeSchedule+import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule+import java.time.Duration+import java.time.LocalDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class PlatformStateTest {++    private val ctx: Context = ApplicationProvider.getApplicationContext()++    @Test+    fun masterSwitchDefaultsOnAndPersists() {+        assertTrue(SupervisionMaster.isEnabled(ctx))+        SupervisionMaster.setEnabled(ctx, false)+        assertFalse(SupervisionMaster.isEnabled(ctx))+        SupervisionMaster.setEnabled(ctx, true)+        assertTrue(SupervisionMaster.isEnabled(ctx))+    }++    @Test+    fun webContentFiltersDefaultOffAndPersist() {+        assertFalse(WebContentFilters.isEnabled(ctx))+        WebContentFilters.setEnabled(ctx, true)+        assertTrue(WebContentFilters.isEnabled(ctx))+        WebContentFilters.setEnabled(ctx, false)+        assertFalse(WebContentFilters.isEnabled(ctx))+    }++    @Test+    fun limitStateMarksPrunesAndResetsByDay() {+        val state = LimitState(ctx)+        state.pruneToToday()+        assertFalse(state.hasReached("com.example.game"))+        state.markReached("com.example.game")+        state.markReached("com.example.video")+        state.markReached("com.example.game") // idempotent+        assertTrue(state.hasReached("com.example.game"))+        assertTrue(state.hasReached("com.example.video"))+        assertFalse(state.hasReached("com.example.other"))+        state.pruneToToday() // same day: no reset+        assertTrue(state.hasReached("com.example.game"))+    }++    @Test+    fun activeAtMapsLocalDateTimeToWindow() {+        // Monday 2026-11-02 is a Monday; 22:00 local.+        val mondayNight = LocalDateTime.of(2026, 11, 2, 22, 0)+        val bedtime = BedtimeSchedule(enabled = true) // 21:00-07:00+        assertTrue(bedtime.activeAt(mondayNight))+        assertFalse(bedtime.activeAt(LocalDateTime.of(2026, 11, 2, 12, 0)))+        val downtime = DowntimeSchedule(enabled = true) // 12:00-14:00+        assertTrue(downtime.activeAt(LocalDateTime.of(2026, 11, 2, 13, 0)))+        assertFalse(downtime.activeAt(mondayNight))+        val school = SchoolTimeSchedule(enabled = true) // weekdays 08:00-15:00+        assertTrue(school.activeAt(LocalDateTime.of(2026, 11, 2, 9, 0)))+        assertFalse(school.activeAt(LocalDateTime.of(2026, 11, 7, 9, 0))) // Saturday+    }++    @Test+    fun bedtimeSchedulerArmsAndCancels() {+        val scheduler = BedtimeScheduler(ctx)+        val alarmManager = ctx.getSystemService(AlarmManager::class.java)+        val shadow = shadowOf(alarmManager)+        // Disabled schedules cancel and arm nothing.+        scheduler.arm(BedtimeSchedule(enabled = false))+        scheduler.armAll(+            BedtimeSchedule(enabled = false),+            DowntimeSchedule(enabled = false),+            SchoolTimeSchedule(enabled = false),+        )+        assertTrue(shadow.scheduledAlarms.isEmpty())+        // An enabled cross-midnight window always has a next boundary within a week.+        scheduler.arm(BedtimeSchedule(enabled = true))+        assertTrue(shadow.scheduledAlarms.isNotEmpty())+        // Disabling again cancels the pending alarm.+        scheduler.arm(BedtimeSchedule(enabled = false))+        // An always-on same-day window (00:00-00:00 wraps to all day via start>end? use full mask window)+        scheduler.armAll(+            BedtimeSchedule(enabled = true),+            DowntimeSchedule(enabled = true),+            SchoolTimeSchedule(enabled = true),+        )+        assertTrue(shadow.scheduledAlarms.isNotEmpty())+    }++    @Test+    fun appLimitsWithNoUsageAccessMeasureZero() {+        val limits = AppLimits(ctx)+        assertEquals(Duration.ZERO, limits.timeUsedToday("com.example.game"))+        assertEquals(Duration.ZERO, limits.totalUsedToday())+        limits.unregister("com.example.game")+        // Hidden register method is unreachable on a plain JVM build; sync must not throw.+        limits.sync(+            listOf(+                com.vayunmathur.parentalcontrols.data.AppRule("com.example.game", dailyLimitMinutes = 30),+                com.vayunmathur.parentalcontrols.data.AppRule("com.example.free"),+            ),+            listOf(com.vayunmathur.parentalcontrols.data.BonusGrant(packageName = "com.example.game", bonusMinutes = 10, day = "2026-11-06")),+        )+        assertEquals("android.app.usage.extra.OBSERVER_ID", LimitExtras.OBSERVER_ID)+        assertEquals("com.vayunmathur.parentalcontrols.extra.PACKAGE_NAME", EXTRA_PACKAGE_NAME)+    }++    @Test+    fun usageAccessReportsAStatus() {+        val status = UsageAccess.ensure(ctx)+        // On a JVM harness the op is either granted by the shadow or denied; either way the+        // cheap check must agree with a denied post-attempt state.+        assertTrue(status == UsageAccess.Status.GRANTED || status == UsageAccess.Status.DENIED)+        assertEquals(status == UsageAccess.Status.GRANTED, UsageAccess.isGranted(ctx) || status == UsageAccess.Status.GRANTED)+    }++    @Test+    fun supervisionApisAnswerEmptyAndNotSupervisor() {+        assertTrue(SupervisionApis.preferenceData(null).isEmpty)+        assertTrue(SupervisionApis.supportedApps(null).isEmpty)+        assertFalse(SupervisionApis.isSupervisorAccount().getBoolean("is_supervisor_account"))+        assertEquals(1, SupervisionApis.PREFERENCE_DATA)+        assertEquals(2, SupervisionApis.SUPPORTED_APPS)+        assertEquals(3, SupervisionApis.IS_SUPERVISOR_ACCOUNT)+        val withRequest = SupervisionApis.preferenceData(android.os.Bundle().apply { putString("k", "v") })+        assertTrue(withRequest.isEmpty)+    }++    @Test+    fun supervisionCallerTrustsSystemAndRejectsStrangers() {+        val caller = SupervisionCaller(ctx)+        assertTrue(caller.isSettings(android.os.Process.SYSTEM_UID))+        // Settings is not installed in the harness, so a random app uid is rejected.+        assertFalse(caller.isSettings(10_999))+        assertFalse(caller.isSettings(-1))+    }++    @Test+    fun blockReasonPrecedenceEnumOrder() {+        assertEquals(+            listOf("Bedtime", "Downtime", "SchoolTime", "DailyLimit", "AppLimit"),+            Enforcer.BlockReason.entries.map { it.name },+        )+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ReceiversNotifierServiceTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ReceiversNotifierServiceTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ReceiversNotifierServiceTest.ktnew file mode 100644index 0000000000..78344cfbe6--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ReceiversNotifierServiceTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.parentalcontrols.platform++import android.app.NotificationManager+import android.content.Context+import android.content.Intent+import android.os.Handler+import android.os.HandlerThread+import android.os.Message+import android.os.Messenger+import android.os.Process+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.parentalcontrols.notifications.LockNotifier+import com.vayunmathur.parentalcontrols.receiver.BedtimeReceiver+import com.vayunmathur.parentalcontrols.receiver.BootReceiver+import com.vayunmathur.parentalcontrols.receiver.LimitReachedReceiver+import com.vayunmathur.parentalcontrols.service.SupervisionMessengerService+import java.util.concurrent.CountDownLatch+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class ReceiversNotifierServiceTest {++    private val ctx: Context = ApplicationProvider.getApplicationContext()++    @Test+    fun receiverIntentBuilders() {+        val limit = LimitReachedReceiver.intent(ctx, "com.example.game")+        assertEquals("com.example.game", limit.getStringExtra(EXTRA_PACKAGE_NAME))+        assertEquals(LimitReachedReceiver::class.java.name, limit.component?.className)+        val bedtime = BedtimeReceiver.intent(ctx)+        assertEquals(BedtimeReceiver::class.java.name, bedtime.component?.className)+        assertEquals(+            "android.app.supervision.action.SUPERVISION_MESSENGER_SERVICE",+            SupervisionMessengerService.SUPERVISION_BIND_ACTION,+        )+    }++    @Test+    fun receiversIgnoreIrrelevantBroadcasts() {+        // Wrong action: boot receiver returns before doing any async work.+        BootReceiver().onReceive(ctx, Intent("com.example.WRONG_ACTION"))+        BootReceiver().onReceive(ctx, Intent(Intent.ACTION_VIEW))+        // A limit callback without a package is dropped.+        LimitReachedReceiver().onReceive(ctx, Intent())+        assertFalse(LimitState(ctx).hasReached("com.example.game"))+    }++    @Test+    fun lockNotifierPostsAndCancelsPerReason() {+        val nm = ctx.getSystemService(NotificationManager::class.java)+        val shadow = shadowOf(nm)+        val before = shadow.allNotifications.size+        for (reason in Enforcer.BlockReason.entries) {+            LockNotifier.notifyLocked(ctx, reason, "com.example.game")+        }+        assertEquals(before + Enforcer.BlockReason.entries.size, shadow.allNotifications.size)+        assertTrue(shadow.allNotifications.all { it != null })+        LockNotifier.cancel(ctx, Enforcer.BlockReason.Bedtime)+        assertEquals(before + Enforcer.BlockReason.entries.size - 1, shadow.allNotifications.size)+        // A device-wide lock carries no package.+        LockNotifier.notifyLocked(ctx, Enforcer.BlockReason.DailyLimit, null)+        assertNotNull(shadow.allNotifications.lastOrNull())+    }++    @Test+    fun messengerServiceRepliesDeniedToNonSettingsCallers() {+        val controller = Robolectric.buildService(SupervisionMessengerService::class.java).create()+        val service = controller.get()+        val binder = service.onBind(Intent(ctx, SupervisionMessengerService::class.java))+        assertNotNull(binder)+        val client = Messenger(binder)++        val replies = mutableListOf<Message>()+        val latch = CountDownLatch(2)+        val replyThread = HandlerThread("reply-test").apply { start() }+        val replyMessenger = Messenger(object : Handler(replyThread.looper) {+            override fun handleMessage(msg: Message) {+                replies.add(Message.obtain(msg).also { it.data = msg.peekData() })+                latch.countDown()+            }+        })++        fun request(apiId: Int, uid: Int) {+            val msg = Message.obtain(null, apiId, 42, 0)+            msg.sendingUid = uid+            msg.replyTo = replyMessenger+            client.send(msg)+        }+        // The binder delivery stamps the caller's real uid, so neither a stranger uid nor a+        // forged system uid survives as Settings: both are refused with arg2 = 1, and the+        // api id / transaction id are echoed for correlation.+        request(SupervisionApis.IS_SUPERVISOR_ACCOUNT, 10_999)+        request(SupervisionApis.PREFERENCE_DATA, Process.SYSTEM_UID)+        assertTrue(latch.await(10, TimeUnit.SECONDS), "no replies: $replies")+        assertEquals(2, replies.size)+        assertTrue(replies.all { it.arg2 == 1 })+        assertEquals(setOf(SupervisionApis.IS_SUPERVISOR_ACCOUNT, SupervisionApis.PREFERENCE_DATA), replies.map { it.what }.toSet())+        assertTrue(replies.all { it.arg1 == 42 })+        controller.destroy()+    }++    @Test+    fun messengerServiceAnswersSettingsUidForKnownAndUnknownApis() {+        // Register a fake Settings package whose uid is this process's uid; binder delivery+        // stamps the real calling uid, so the caller check then passes honestly.+        val pm = ctx.packageManager+        val settingsInfo = android.content.pm.PackageInfo().apply {+            packageName = "com.android.settings"+            applicationInfo = android.content.pm.ApplicationInfo().apply {+                packageName = "com.android.settings"+                uid = Process.myUid()+            }+        }+        shadowOf(pm).installPackage(settingsInfo)+        val controller = Robolectric.buildService(SupervisionMessengerService::class.java).create()+        val service = controller.get()+        val client = Messenger(service.onBind(Intent()))++        val replies = mutableListOf<Message>()+        val latch = CountDownLatch(3)+        val replyThread = HandlerThread("reply-test-ok").apply { start() }+        val replyMessenger = Messenger(object : Handler(replyThread.looper) {+            override fun handleMessage(msg: Message) {+                replies.add(Message.obtain(msg).also { it.data = msg.peekData() })+                latch.countDown()+            }+        })+        fun request(apiId: Int) {+            val msg = Message.obtain(null, apiId, 5, 0)+            msg.replyTo = replyMessenger+            client.send(msg)+        }+        request(SupervisionApis.PREFERENCE_DATA)+        request(SupervisionApis.SUPPORTED_APPS)+        request(SupervisionApis.IS_SUPERVISOR_ACCOUNT)+        assertTrue(latch.await(10, TimeUnit.SECONDS), "replies=$replies")+        assertEquals(3, replies.size)+        assertTrue(replies.all { it.arg2 == 0 && it.arg1 == 5 })+        val supervisor = replies.first { it.what == SupervisionApis.IS_SUPERVISOR_ACCOUNT }+        assertFalse(supervisor.peekData()?.getBoolean("is_supervisor_account") ?: true)+        controller.destroy()+    }++    @Test+    fun messengerServiceUnknownApiAndNoReplyTo() {+        val controller = Robolectric.buildService(SupervisionMessengerService::class.java).create()+        val service = controller.get()+        val client = Messenger(service.onBind(Intent()))++        val replies = mutableListOf<Message>()+        val latch = CountDownLatch(1)+        val replyThread = HandlerThread("reply-test-2").apply { start() }+        val replyMessenger = Messenger(object : Handler(replyThread.looper) {+            override fun handleMessage(msg: Message) {+                replies.add(Message.obtain(msg))+                latch.countDown()+            }+        })+        // No replyTo: ignored, must not throw.+        client.send(Message.obtain(null, SupervisionApis.PREFERENCE_DATA, 1, 0))+        val unknown = Message.obtain(null, 999, 7, 0)+        unknown.sendingUid = Process.SYSTEM_UID+        unknown.replyTo = replyMessenger+        client.send(unknown)+        assertTrue(latch.await(10, TimeUnit.SECONDS))+        assertEquals(1, replies.single().arg2) // denied before the unknown-api dispatch+        assertEquals(7, replies.single().arg1)+        controller.destroy()+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModelTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModelTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModelTest.ktnew file mode 100644index 0000000000..4e7402cdaa--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModelTest.kt@@ -0,0 +1,168 @@+package com.vayunmathur.parentalcontrols.platform++import android.app.Application+import android.os.Looper+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import com.vayunmathur.parentalcontrols.data.AppRule+import com.vayunmathur.parentalcontrols.data.ParentalControlsDatabase+import com.vayunmathur.parentalcontrols.data.SupervisionRules+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [35])+class SupervisionViewModelTest {++    companion object {+        private var sharedDb: ParentalControlsDatabase? = null+    }++    private lateinit var app: Application+    private lateinit var rules: SupervisionRules+    private lateinit var vm: SupervisionViewModel++    @BeforeTest+    fun setUp() {+        app = ApplicationProvider.getApplicationContext<Application>()+        val mem = sharedDb ?: Room.inMemoryDatabaseBuilder(app, ParentalControlsDatabase::class.java)+            .setSingleConnectionPool()+            .setSingleConnectionPool()+            .allowMainThreadQueries().build().also { sharedDb = it }+        synchronized(databases) { databases[ParentalControlsDatabase::class] = mem }+        rules = SupervisionRules.get(app)+        vm = SupervisionViewModel(app)+        val scope = CoroutineScope(Dispatchers.Default + Job())+        scope.launch { vm.state.collect {} }+        await("initial state") { true }+    }++    @AfterTest+    fun absorbReconcileLinkageErrors() {+        // Every edit reconciles through Enforcer, whose SupervisionManager class only exists+        // in the MaOS framework (compileOnly stubs), so on this JVM those fire-and-forget+        // coroutines die with a linkage error. Give them a moment to land, then enter a+        // throwaway test scope to drain the uncaught-exception collector here instead of+        // letting it fail the next Compose test in this JVM.+        shadowOf(Looper.getMainLooper()).idle()+        Thread.sleep(250)+        runCatching { kotlinx.coroutines.test.runTest { } }+    }++    private fun await(label: String, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 20_000+        while (System.currentTimeMillis() < deadline) {+            shadowOf(Looper.getMainLooper()).idle()+            if (condition()) return+            Thread.sleep(50)+        }+        error("timed out waiting for $label: state=${vm.state.value}")+    }++    @Test+    fun scheduleEditsPersist() {+        vm.setScheduleEnabled(true)+        await("bedtime enabled") { runBlocking { rules.scheduleNow().enabled } }+        vm.setStart(20, 30)+        await("bedtime start") { runBlocking { rules.scheduleNow().startMinute } == 20 * 60 + 30 }+        vm.setEnd(6, 15)+        await("bedtime end") { runBlocking { rules.scheduleNow().endMinute } == 6 * 60 + 15 }+        val before = runBlocking { rules.scheduleNow().daysMask }+        vm.toggleDay(3)+        await("bedtime day toggled") { runBlocking { rules.scheduleNow().daysMask } == (before xor (1 shl 3)) }+        vm.toggleDay(3)+        await("bedtime day restored") { runBlocking { rules.scheduleNow().daysMask } == before }+        await("state reflects schedule") { vm.state.value.schedule.enabled }+    }++    @Test+    fun downtimeAndSchoolEditsPersist() {+        vm.setDowntimeEnabled(true)+        await("downtime enabled") { runBlocking { rules.downtimeNow().enabled } }+        vm.setDowntimeStart(11, 0)+        await("downtime start") { runBlocking { rules.downtimeNow().startMinute } == 660 }+        vm.setDowntimeEnd(13, 30)+        await("downtime edited") {+            runBlocking { rules.downtimeNow() }.let { it.enabled && it.startMinute == 660 && it.endMinute == 810 }+        }+        val mask = runBlocking { rules.downtimeNow().daysMask }+        vm.toggleDowntimeDay(0)+        await("downtime day") { runBlocking { rules.downtimeNow().daysMask } == (mask xor 1) }+        vm.setSchoolTimeEnabled(true)+        await("school enabled") { runBlocking { rules.schoolTimeNow().enabled } }+        vm.setSchoolTimeStart(7, 45)+        await("school start") { runBlocking { rules.schoolTimeNow().startMinute } == 465 }+        vm.setSchoolTimeEnd(14, 45)+        await("school edited") {+            runBlocking { rules.schoolTimeNow() }.let { it.enabled && it.startMinute == 465 && it.endMinute == 885 }+        }+        val schoolMask = runBlocking { rules.schoolTimeNow().daysMask }+        vm.toggleSchoolTimeDay(6)+        await("school day") { runBlocking { rules.schoolTimeNow().daysMask } == (schoolMask xor (1 shl 6)) }+    }++    @Test+    fun ruleEditsCreateUpdateAndDeleteRows() {+        vm.setDailyLimit("com.vm.game", 30)+        await("rule created") { runBlocking { rules.rule("com.vm.game")?.dailyLimitMinutes } == 30 }+        vm.setBedtimeBlocked("com.vm.game", true)+        await("bedtime flag") { runBlocking { rules.rule("com.vm.game")?.blockedAtBedtime } == true }+        vm.setAllowedInDowntime("com.vm.game", true)+        await("downtime flag") { runBlocking { rules.rule("com.vm.game")?.allowedInDowntime } == true }+        // Clearing every restriction deletes the row (it no longer supervises anything).+        vm.setAllowedInDowntime("com.vm.game", false)+        await("downtime flag cleared") { runBlocking { rules.rule("com.vm.game")?.allowedInDowntime } == false }+        vm.setBedtimeBlocked("com.vm.game", false)+        await("flags cleared but limit remains") {+            runBlocking { rules.rule("com.vm.game") }.let { it != null && it.dailyLimitMinutes == 30 && !it.blockedAtBedtime }+        }+        vm.setDailyLimit("com.vm.game", null)+        await("rule deleted") { runBlocking { rules.rule("com.vm.game") } == null }+        assertNull(runBlocking { rules.rule("com.vm.game") })+    }++    @Test+    fun deviceDailyLimitAndMasterSwitch() {+        vm.setDeviceDailyLimit(120)+        await("device limit") { runBlocking { rules.dailyLimitNow() } == 120 }+        await("state device limit") { vm.state.value.dailyLimitMinutes == 120 }+        vm.setDeviceDailyLimit(null)+        await("device limit cleared") { runBlocking { rules.dailyLimitNow() } == null }+        vm.setControlsEnabled(false)+        await("controls off in state") { !vm.state.value.controlsEnabled }+        assertFalse(SupervisionMaster.isEnabled(app))+        vm.setControlsEnabled(true)+        await("controls on in state") { vm.state.value.controlsEnabled }+        assertTrue(SupervisionMaster.isEnabled(app))+    }++    @Test+    fun supervisableAppDerivedState() {+        val supervised = SupervisableApp("com.a", "Alpha", AppRule("com.a", dailyLimitMinutes = 5))+        assertTrue(supervised.isSupervised)+        assertEquals("Alpha", supervised.label)+        val free = SupervisableApp("com.b", "Beta", null)+        assertFalse(free.isSupervised)+        assertEquals(+            SupervisionUiState().apps,+            emptyList(),+        )+        assertTrue(SupervisionUiState().loading)+        assertTrue(SupervisionUiState().controlsEnabled)+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.ktnew file mode 100644index 0000000000..e46f0342f7--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt@@ -0,0 +1,216 @@+package com.vayunmathur.parentalcontrols.ui++import android.app.Application+import android.content.Intent+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createEmptyComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextInput+import androidx.room3.Room+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import com.vayunmathur.parentalcontrols.data.ParentalControlsDatabase+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class ParentalActivitiesTest {++    @get:Rule+    val composeRule = createEmptyComposeRule()++    companion object {+        private var sharedDb: ParentalControlsDatabase? = null+    }++    private fun seedDatabase() {+        val app = ApplicationProvider.getApplicationContext<Application>()+        val mem = sharedDb ?: Room.inMemoryDatabaseBuilder(app, ParentalControlsDatabase::class.java)+            .setSingleConnectionPool()+            .setSingleConnectionPool()+            .allowMainThreadQueries().build().also { sharedDb = it }+        synchronized(databases) { databases[ParentalControlsDatabase::class] = mem }+    }++    @Test+    fun dashboardActivityShowsDashboardAndOpensEditors() {+        seedDatabase()+        ActivityScenario.launch(DashboardActivity::class.java).use { scenario ->+            composeRule.onNodeWithText("Parental controls").assertIsDisplayed()+            composeRule.onNodeWithText("Controls for this phone").assertIsDisplayed()+            var started: Intent? = null+            scenario.onActivity { started = shadowOf(it).nextStartedActivity }+            composeRule.onNodeWithText("Daily limit").performClick()+            scenario.onActivity { started = shadowOf(it).peekNextStartedActivity() }+            assertEquals(DailyLimitActivity::class.java.name, started?.component?.className)+            composeRule.onNodeWithText("App limits").performClick()+            scenario.onActivity { started = shadowOf(it).peekNextStartedActivity() }+            assertEquals(AppLimitsActivity::class.java.name, started?.component?.className)+        }+    }++    @Test+    fun pinGateActivityRendersAndCancels() {+        ActivityScenario.launch(PinGateActivity::class.java).use {+            composeRule.onNodeWithText("Parent PIN").assertIsDisplayed()+            composeRule.onNodeWithText("Enter the parent PIN to change these settings.").assertIsDisplayed()+            composeRule.onNodeWithText("Cancel").performClick()+            it.onActivity { activity -> assertTrue(activity.isFinishing) }+        }+    }++    @Test+    fun pinSetupActivityRendersAndCancels() {+        ActivityScenario.launch(PinSetupActivity::class.java).use {+            composeRule.onNodeWithText("Set parent PIN").assertIsDisplayed()+            composeRule.onNodeWithText("New PIN").assertIsDisplayed()+            composeRule.onNodeWithText("Cancel").performClick()+            it.onActivity { activity -> assertTrue(activity.isFinishing) }+        }+    }++    @Test+    fun lockActivitiesRenderTheirReasonAndClose() {+        val cases = listOf(+            BedtimeLockActivity::class.java to "Bedtime",+            DowntimeLockActivity::class.java to "Downtime",+            SchoolTimeLockActivity::class.java to "School time",+            DailyLimitLockActivity::class.java to "Daily limit reached",+            AppLimitLockActivity::class.java to "App limit reached",+        )+        for ((activity, title) in cases) {+            val intent = BaseLockActivity.intent(+                ApplicationProvider.getApplicationContext(),+                activity,+                "com.example.game",+            )+            ActivityScenario.launch<android.app.Activity>(intent).use {+                composeRule.onNodeWithText(title).assertIsDisplayed()+                composeRule.onNodeWithText("OK").performClick()+                it.onActivity { launched -> assertTrue(launched.isFinishing) }+            }+        }+    }++    @Test+    fun pinGatedActivitiesShowContentAfterVerification() {+        seedDatabase()+        com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+        com.vayunmathur.parentalcontrols.auth.ParentPin.get(+            ApplicationProvider.getApplicationContext(),+        ).set("1234")+        val cases = listOf(+            BedtimeActivity::class.java to "Child bedtime",+            AppLimitsActivity::class.java to "App limits",+            DailyLimitActivity::class.java to "Daily limit",+            DowntimeActivity::class.java to "Downtime",+            SchoolTimeActivity::class.java to "School time",+            WebContentFiltersActivity::class.java to "Web content filters",+        )+        for ((activity, title) in cases) {+            ActivityScenario.launch<android.app.Activity>(Intent(ApplicationProvider.getApplicationContext(), activity)).use { scenario ->+                var delivered = false+                scenario.onActivity { launched ->+                    val shadow = shadowOf(launched)+                    val forResult = shadow.nextStartedActivityForResult+                    if (forResult != null) {+                        shadow.receiveResult(forResult.intent, PinGateActivity.RESULT_VERIFIED, null)+                        delivered = true+                    }+                }+                assertTrue(delivered, "no gate launched for $activity")+                composeRule.onNodeWithText(title).assertIsDisplayed()+            }+        }+    }++    @Test+    fun pinGatedActivityFinishesWhenGateCancelled() {+        seedDatabase()+        com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+        com.vayunmathur.parentalcontrols.auth.ParentPin.get(+            ApplicationProvider.getApplicationContext(),+        ).set("1234")+        ActivityScenario.launch(BedtimeActivity::class.java).use { scenario ->+            scenario.onActivity { launched ->+                val shadow = shadowOf(launched)+                val forResult = shadow.nextStartedActivityForResult+                shadow.receiveResult(forResult.intent, android.app.Activity.RESULT_CANCELED, null)+            }+            scenario.onActivity { launched -> assertTrue(launched.isFinishing) }+        }+    }++    @Test+    fun pinGateActivityVerifiesCorrectPinAndReturnsVerified() {+        com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+        com.vayunmathur.parentalcontrols.auth.ParentPin.get(+            ApplicationProvider.getApplicationContext(),+        ).set("1234")+        ActivityScenario.launch(PinGateActivity::class.java).use { scenario ->+            composeRule.onNodeWithText("PIN").performTextInput("1234")+            composeRule.onNodeWithText("Unlock").performClick()+            // Verification is asynchronous; wait for the activity to finish with the result.+            val deadline = System.currentTimeMillis() + 10_000+            var resultCode = Int.MIN_VALUE+            while (System.currentTimeMillis() < deadline) {+                scenario.onActivity { resultCode = shadowOf(it).resultCode }+                if (resultCode == PinGateActivity.RESULT_VERIFIED) break+                Thread.sleep(50)+            }+            assertEquals(PinGateActivity.RESULT_VERIFIED, resultCode)+        }+    }++    @Test+    fun pinGateActivityWrongPinShowsError() {+        com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+        com.vayunmathur.parentalcontrols.auth.ParentPin.get(+            ApplicationProvider.getApplicationContext(),+        ).set("1234")+        ActivityScenario.launch(PinGateActivity::class.java).use {+            composeRule.onNodeWithText("PIN").performTextInput("0000")+            composeRule.onNodeWithText("Unlock").performClick()+            val deadline = System.currentTimeMillis() + 10_000+            var sawError = false+            while (System.currentTimeMillis() < deadline && !sawError) {+                sawError = runCatching {+                    composeRule.onNodeWithText("Wrong PIN. Try again.").assertIsDisplayed(); true+                }.getOrDefault(false)+                if (!sawError) Thread.sleep(50)+            }+            assertTrue(sawError)+        }+    }++    @Test+    fun setupActivityHandsOffAndFinishes() {+        com.vayunmathur.parentalcontrols.platform.FakeAndroidKeyStore.install()+        val controller = org.robolectric.Robolectric.buildActivity(SetupActivity::class.java).create()+        assertTrue(controller.get().isFinishing)+    }++    @Test+    fun lockActivityIntentCarriesPackage() {+        val intent = BaseLockActivity.intent(+            ApplicationProvider.getApplicationContext(),+            AppLimitLockActivity::class.java,+            "com.example.game",+        )+        assertEquals("com.example.game", intent.getStringExtra(BaseLockActivity.EXTRA_PACKAGE))+        assertEquals(15, BaseLockActivity.BONUS_MINUTES)+        val deviceWide = BaseLockActivity.intent(+            ApplicationProvider.getApplicationContext(),+            DailyLimitLockActivity::class.java,+            null,+        )+        assertEquals(null, deviceWide.getStringExtra(BaseLockActivity.EXTRA_PACKAGE))+    }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.ktnew file mode 100644index 0000000000..27bfd59d9c--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt@@ -0,0 +1,366 @@+package com.vayunmathur.parentalcontrols.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsNotEnabled+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performScrollTo+import androidx.compose.ui.test.performTextInput+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeUp+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.parentalcontrols.data.AppRule+import com.vayunmathur.parentalcontrols.data.BedtimeSchedule+import com.vayunmathur.parentalcontrols.data.DowntimeSchedule+import com.vayunmathur.parentalcontrols.platform.Enforcer+import com.vayunmathur.parentalcontrols.platform.SupervisableApp+import com.vayunmathur.parentalcontrols.platform.SupervisionUiState+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class ParentalControlsScreensTest {++    @get:Rule+    val rule = createComposeRule()++    // ---- PIN gate / setup ----++    @Test+    fun pinGateFiltersNonDigitsAndUnlocks() {+        var verified: String? = null; var cancelled = false+        val actions = PinGateActions(onVerify = { verified = it; true }, onCancel = { cancelled = true })+        rule.setContent { DynamicTheme { PinGateScreen(error = null, lockedOut = false, actions = actions) } }+        rule.onNodeWithText("Parent PIN").assertIsDisplayed()+        rule.onNodeWithText("Enter the parent PIN to change these settings.").assertIsDisplayed()+        rule.onNodeWithText("PIN").performTextInput("12a34")+        rule.onNodeWithText("Unlock").performClick()+        assertEquals("1234", verified)+        rule.onNodeWithText("Cancel").performClick()+        assertTrue(cancelled)+    }++    @Test+    fun pinGateShortEntryCannotUnlockAndErrorShows() {+        var called = false+        val actions = PinGateActions(onVerify = { called = true; false }, onCancel = {})+        rule.setContent { DynamicTheme { PinGateScreen(error = "Wrong PIN. Try again.", lockedOut = false, actions = actions) } }+        rule.onNodeWithText("Wrong PIN. Try again.").assertIsDisplayed()+        rule.onNodeWithText("PIN").performTextInput("12")+        rule.onNodeWithText("Unlock").assertIsNotEnabled()+        assertTrue(!called)+    }++    @Test+    fun pinGateLockedOutDisablesEntry() {+        rule.setContent {+            DynamicTheme { PinGateScreen(error = "Too many tries. Try again later.", lockedOut = true, actions = PinGateActions({ true }, {})) }+        }+        rule.onNodeWithText("Too many tries. Try again later.").assertIsDisplayed()+        rule.onNodeWithText("Unlock").assertIsNotEnabled()+    }++    @Test+    fun pinSetupRequiresMatchingEntries() {+        var saved: String? = null+        val actions = PinSetupActions(onSet = { saved = it; true }, onCancel = {})+        rule.setContent { DynamicTheme { PinSetupScreen(actions) } }+        rule.onNodeWithText("Set parent PIN").assertIsDisplayed()+        rule.onNodeWithText("New PIN").performTextInput("1234")+        rule.onNodeWithText("Repeat PIN").performTextInput("9999")+        rule.onNodeWithText("PINs do not match.").assertIsDisplayed()+        rule.onNodeWithText("Save").assertIsNotEnabled()+        // Correct the confirmation: clear via replacement semantics of the field is not+        // available, so this test only pins the mismatch state; matching flow below.+        assertEquals(null, saved)+    }++    @Test+    fun pinSetupMatchingEntriesSave() {+        var saved: String? = null; var cancelled = false+        val actions = PinSetupActions(onSet = { saved = it; true }, onCancel = { cancelled = true })+        rule.setContent { DynamicTheme { PinSetupScreen(actions) } }+        rule.onNodeWithText("New PIN").performTextInput("2468")+        rule.onNodeWithText("Repeat PIN").performTextInput("2468")+        rule.onNodeWithText("Save").performClick()+        assertEquals("2468", saved)+        rule.onNodeWithText("Cancel").performClick()+        assertTrue(cancelled)+    }++    // ---- Lock screens ----++    @Test+    fun lockScreenBedtimeHasNoBonus() {+        var asked = false; var closed = false+        rule.setContent {+            DynamicTheme { LockScreen(Enforcer.BlockReason.Bedtime, "Game", LockActions({ asked = true }, { closed = true })) }+        }+        rule.onNodeWithText("Bedtime").assertIsDisplayed()+        rule.onNodeWithText("Game").assertIsDisplayed()+        rule.onNodeWithText("This app is unavailable during bedtime hours.").assertIsDisplayed()+        rule.onNodeWithText("Ask a parent for more time").assertDoesNotExist()+        rule.onNodeWithText("OK").performClick()+        assertTrue(closed)+        assertTrue(!asked)+    }++    @Test+    fun lockScreenAppLimitOffersBonus() {+        var asked = false+        rule.setContent {+            DynamicTheme { LockScreen(Enforcer.BlockReason.AppLimit, null, LockActions({ asked = true }, {})) }+        }+        rule.onNodeWithText("App limit reached").assertIsDisplayed()+        rule.onNodeWithText("Ask a parent for more time").performClick()+        assertTrue(asked)+    }++    @Test+    fun lockScreenOtherReasonsShowTheirCopy() {+        rule.setContent {+            DynamicTheme { LockScreen(Enforcer.BlockReason.SchoolTime, "Reader", LockActions({}, {})) }+        }+        rule.onNodeWithText("School time").assertIsDisplayed()+        rule.onNodeWithText("Reader").assertIsDisplayed()+    }++    // ---- Dashboard ----++    private fun dashboardActions(record: MutableList<String>) = DashboardActions(+        onSetControls = { record.add("controls:$it") },+        onOpenDailyLimit = { record.add("daily") },+        onOpenAppLimits = { record.add("apps") },+        onOpenDowntime = { record.add("downtime") },+        onOpenWebFilters = { record.add("web") },+        onOpenPin = { record.add("pin") },+    )++    @Test+    fun dashboardShowsSummariesAndNavigates() {+        val record = mutableListOf<String>()+        val state = SupervisionUiState(+            controlsEnabled = true,+            dailyLimitMinutes = 90,+            downtime = DowntimeSchedule(enabled = true, startMinute = 12 * 60, endMinute = 14 * 60),+            apps = listOf(SupervisableApp("com.a", "Alpha", AppRule("com.a", dailyLimitMinutes = 30))),+            loading = false,+        )+        rule.setContent { DynamicTheme { DashboardScreen(state, dashboardActions(record)) } }+        rule.onNodeWithText("Parental controls").assertIsDisplayed()+        rule.onNodeWithText("Controls for this phone").assertIsDisplayed()+        rule.onNodeWithText("1 h 30 min").assertIsDisplayed()+        rule.onNodeWithText("App limits set").assertIsDisplayed()+        rule.onNodeWithText("12:00 PM – 2:00 PM").assertIsDisplayed()+        rule.onNodeWithText("Daily limit").performClick()+        rule.onNodeWithText("App limits").performClick()+        rule.onRoot().performTouchInput { swipeUp() }+        rule.onNodeWithText("Downtime").performClick()+        rule.onNodeWithText("Web content filters").performClick()+        rule.onRoot().performTouchInput { swipeUp() }+        rule.onNodeWithText("Manage your PIN").performClick()+        assertEquals(listOf("daily", "apps", "downtime", "web", "pin"), record)+    }++    @Test+    fun dashboardDefaultsSummaries() {+        val record = mutableListOf<String>()+        rule.setContent { DynamicTheme { DashboardScreen(SupervisionUiState(loading = false), dashboardActions(record)) } }+        rule.onNodeWithText("Not set").assertIsDisplayed()+        rule.onNodeWithText("No app limits").assertIsDisplayed()+        rule.onNodeWithText("Off").assertIsDisplayed()+        rule.onNodeWithText("Controls for this phone").performClick()+        assertEquals(listOf("controls:false"), record)+    }++    // ---- App limits / daily limit pickers ----++    @Test+    fun appLimitsPickerSetsAndClearsLimit() {+        var change: Pair<String, Int?>? = null+        val state = SupervisionUiState(+            apps = listOf(+                SupervisableApp("com.a", "Alpha", AppRule("com.a", dailyLimitMinutes = 30)),+                SupervisableApp("com.b", "Beta", null),+            ),+            loading = false,+        )+        rule.setContent { DynamicTheme { AppLimitsScreen(state, AppLimitsActions { p, m -> change = p to m }) } }+        rule.onNodeWithText("App limits").assertIsDisplayed()+        rule.onNodeWithText("Alpha").assertIsDisplayed()+        rule.onNodeWithText("30 min").assertIsDisplayed()+        rule.onNodeWithText("Beta").performClick()+        rule.onNodeWithText("1 h").performClick()+        assertEquals("com.b" to 60, change)+        rule.onNodeWithText("Alpha").performClick()+        // "No limit" appears both as the row summary and the dialog option; the dialog one is last.+        val nodes = rule.onAllNodesWithText("No limit").fetchSemanticsNodes()+        rule.onAllNodesWithText("No limit")[nodes.size - 1].performClick()+        assertEquals("com.a" to null, change)+    }++    @Test+    fun appLimitsLoadingState() {+        rule.setContent { DynamicTheme { AppLimitsScreen(SupervisionUiState(), AppLimitsActions { _, _ -> }) } }+        rule.onNodeWithText("Loading apps…").assertIsDisplayed()+    }++    @Test+    fun dailyLimitPickerSetsBudget() {+        var change: Int? = -1; var called = false+        rule.setContent {+            DynamicTheme { DailyLimitScreen(null, DailyLimitActions { called = true; change = it }) }+        }+        rule.onNodeWithText("Daily limit").assertIsDisplayed()+        rule.onNodeWithText("No limit").assertIsDisplayed()+        rule.onNodeWithText("Daily budget").performClick()+        rule.onNodeWithText("2 h").performClick()+        assertTrue(called)+        assertEquals(120, change)+    }++    @Test+    fun dailyLimitShowsCurrentBudget() {+        rule.setContent { DynamicTheme { DailyLimitScreen(45, DailyLimitActions {}) } }+        rule.onNodeWithText("45 min").assertIsDisplayed()+    }++    // ---- Window schedule (downtime/school shared) ----++    @Test+    fun windowScheduleTogglesDaysAndApps() {+        var day = -1; var appChange: Pair<String, Boolean>? = null; var enabledChange: Boolean? = null+        val actions = WindowScheduleActions(+            onEnabledChange = { enabledChange = it },+            onStartChange = { _, _ -> },+            onEndChange = { _, _ -> },+            onToggleDay = { day = it },+            onAppAllowChange = { p, a -> appChange = p to a },+        )+        rule.setContent {+            DynamicTheme {+                WindowScheduleScreen(+                    title = "Downtime", enableLabel = "Use a downtime schedule", enableHint = "hint",+                    startLabel = "Starts at", endLabel = "Ends at", daysLabel = "Days", appsLabel = "Approved apps",+                    dayInitials = "M,T,W,T,F,S,S",+                    enabled = true, startMinute = 720, endMinute = 840, daysMask = 127,+                    apps = listOf(SupervisableApp("com.a", "Alpha", AppRule("com.a", allowedInDowntime = true))),+                    loading = false, actions = actions,+                )+            }+        }+        rule.onNodeWithText("Downtime").assertIsDisplayed()+        rule.onNodeWithText("12:00").assertIsDisplayed()+        rule.onNodeWithText("14:00").assertIsDisplayed()+        rule.onNodeWithText("Use a downtime schedule").performClick()+        assertEquals(false, enabledChange)+        // First day chip (Monday) toggles day 0. Chips share single-letter labels, pick the first.+        rule.onAllNodesWithText("M")[0].performClick()+        assertEquals(0, day)+        rule.onRoot().performTouchInput { swipeUp() }+        rule.onNodeWithText("Alpha").performClick()+        assertEquals("com.a" to false, appChange)+    }++    @Test+    fun windowScheduleTimePickerSavesStart() {+        var start: Pair<Int, Int>? = null+        val actions = WindowScheduleActions({}, { h, m -> start = h to m }, { _, _ -> }, {}, { _, _ -> })+        rule.setContent {+            DynamicTheme {+                WindowScheduleScreen(+                    title = "School time", enableLabel = "Use", enableHint = "hint",+                    startLabel = "Starts at", endLabel = "Ends at", daysLabel = "Days", appsLabel = "Learning apps",+                    dayInitials = "M,T,W,T,F,S,S",+                    enabled = true, startMinute = 480, endMinute = 900, daysMask = 31,+                    apps = emptyList(), loading = false, actions = actions,+                )+            }+        }+        rule.onNodeWithText("Starts at").performClick()+        val saves = rule.onAllNodesWithText("Save").fetchSemanticsNodes()+        assertTrue(saves.isNotEmpty())+        rule.onAllNodesWithText("Save")[saves.size - 1].performClick()+        assertEquals(8 to 0, start)+    }++    // ---- Bedtime ----++    @Test+    fun bedtimeScreenShowsAppsAndToggles() {+        var toggledDay = -1; var appChange: Pair<String, Boolean>? = null; var enabledChange: Boolean? = null+        val actions = BedtimeActions(+            onEnabledChange = { enabledChange = it },+            onStartChange = { _, _ -> },+            onEndChange = { _, _ -> },+            onToggleDay = { toggledDay = it },+            onAppBedtimeChange = { p, b -> appChange = p to b },+        )+        val state = SupervisionUiState(+            schedule = BedtimeSchedule(enabled = true),+            apps = listOf(SupervisableApp("com.a", "Alpha", AppRule("com.a", blockedAtBedtime = true))),+            loading = false,+        )+        rule.setContent { DynamicTheme { BedtimeScreen(state, actions) } }+        rule.onNodeWithText("Child bedtime").assertIsDisplayed()+        rule.onNodeWithText("Use a bedtime schedule").assertIsDisplayed()+        rule.onRoot().performTouchInput { swipeUp() }+        rule.onNodeWithText("Alpha").assertIsDisplayed()+        rule.onNodeWithText("Alpha").performClick()+        assertEquals("com.a" to false, appChange)+        assertTrue(enabledChange == null)+        assertTrue(toggledDay == -1)+    }++    @Test+    fun bedtimeTimePickersSaveStartAndEnd() {+        var start: Pair<Int, Int>? = null; var end: Pair<Int, Int>? = null; var day = -1+        val actions = BedtimeActions(+            onEnabledChange = {},+            onStartChange = { h, m -> start = h to m },+            onEndChange = { h, m -> end = h to m },+            onToggleDay = { day = it },+            onAppBedtimeChange = { _, _ -> },+        )+        val state = SupervisionUiState(schedule = BedtimeSchedule(enabled = true), loading = false)+        rule.setContent { DynamicTheme { BedtimeScreen(state, actions) } }+        rule.onNodeWithText("Starts at").performClick()+        var saves = rule.onAllNodesWithText("Save").fetchSemanticsNodes()+        assertTrue(saves.isNotEmpty())+        rule.onAllNodesWithText("Save")[saves.size - 1].performClick()+        assertEquals(21 to 0, start)+        rule.onNodeWithText("Ends at").performClick()+        saves = rule.onAllNodesWithText("Save").fetchSemanticsNodes()+        rule.onAllNodesWithText("Save")[saves.size - 1].performClick()+        assertEquals(7 to 0, end)+        // Day chips: first chip is Monday (day 0).+        rule.onAllNodesWithText("M")[0].performClick()+        assertEquals(0, day)+    }++    // ---- Web filters ----++    @Test+    fun webFiltersHoistedToggle() {+        var change: Boolean? = null+        rule.setContent { DynamicTheme { WebContentFiltersScreen(enabled = false, onEnabledChange = { change = it }) } }+        rule.onNodeWithText("Web content filters").assertIsDisplayed()+        rule.onNodeWithText("Filter explicit sites").performClick()+        assertEquals(true, change)+    }++    @Test+    fun webFiltersSelfOwnedToggle() {+        rule.setContent { DynamicTheme { WebContentFiltersScreen() } }+        rule.onNodeWithText("Filter explicit sites").assertIsDisplayed()+        rule.onNodeWithText("Filter explicit sites").performClick()+        rule.onNodeWithText("Filter explicit sites").assertIsDisplayed()+    }+}