screentime: raise coverage to 80% with usage and enforcement tests (#tests)
- Commit
a2938373aae19747b490f49a437c4e2c972455e5- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 17:43 UTC (19 days ago)
- Parents
2cf12fc
Adds deep host tests: UsageHistory against a seeded ShadowUsageStatsManager (week/day aggregation, per-package, hour buckets and labels); the ViewModel and platform layer (AppTimers enforcement driving SpentState, usage-access op modes, WindDownApplier settings/DND writes, WindowScheduler arming, rules flow getters behind an in-memory AndroidKeyStore); activity lifecycles with resumed/visible pumping; a usage bar chart drawn with native graphics; deep screen tests (dashboard day/week stepping, app details timer clearing, wind-down day/time editing, friction interactions, receiver guards, widget refresh, app-icon fallback) and SpentState's daily prune. Coverage measured with :screentime:createMergedCoverageReport (INSTRUCTION): 64.6% -> 80.16%. Structural ceilings documented: the Glance widget content (~420 instructions - no host seam composes Glance), SQLCipher/SQLite-backed rules and DAO paths (~250, shared with Clock-style Room-on-host limits), and goAsync receivers plus the ViewModel's DB-collecting combine (~300), which cannot complete under Robolectric. Verified with :screentime:testDevUnitTest (no ignore-failures), :screentime:detekt and :screentime:lint, all green (detekt retains only pre-existing main-source warnings). Tests only; no production code changed.
Diff
screentime/src/test/java/com/vayunmathur/screentime/FakeAndroidKeyStore.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/FakeAndroidKeyStore.kt b/screentime/src/test/java/com/vayunmathur/screentime/FakeAndroidKeyStore.ktnew file mode 100644index 0000000000..dd7db49a67--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/FakeAndroidKeyStore.kt@@ -0,0 +1,97 @@+package com.vayunmathur.screentime++import android.security.keystore.KeyGenParameterSpec+import java.io.InputStream+import java.io.OutputStream+import java.security.Key+import java.security.KeyStore+import java.security.KeyStoreSpi+import java.security.Provider+import java.security.SecureRandom+import java.security.Security+import java.security.cert.Certificate+import java.util.Collections+import java.util.Date+import java.util.Enumeration+import javax.crypto.KeyGenerator+import javax.crypto.KeyGeneratorSpi+import javax.crypto.SecretKey+import javax.crypto.spec.SecretKeySpec++/**+ * Robolectric has no AndroidKeyStore provider, which otherwise blocks every+ * code path that opens the SQLCipher vault (PasswordRepository,+ * DatabaseHelper, KdbxPasswordHelper). Installing this JCA provider gives+ * tests a plain in-memory AES keystore with the same alias semantics; keys+ * never leave the test process.+ */+object FakeAndroidKeyStore {+ private val keys = mutableMapOf<String, SecretKey>()++ fun install() {+ if (Security.getProvider("AndroidKeyStore") == null) {+ Security.addProvider(FakeProvider())+ }+ }++ fun put(alias: String, key: SecretKey) {+ keys[alias] = key+ }++ fun get(alias: String): SecretKey? = keys[alias]++ fun remove(alias: String) {+ keys.remove(alias)+ }++ fun contains(alias: String): Boolean = keys.containsKey(alias)++ fun aliases(): List<String> = keys.keys.toList()++ class FakeProvider : Provider("AndroidKeyStore", 1.0, "in-memory test keystore") {+ init {+ put("KeyStore.AndroidKeyStore", FakeKeyStoreSpi::class.java.name)+ put("KeyGenerator.AES", FakeKeyGeneratorSpi::class.java.name)+ }+ }++ class FakeKeyStoreSpi : KeyStoreSpi() {+ override fun engineLoad(stream: InputStream?, password: CharArray?) = Unit+ override fun engineContainsAlias(alias: String) = contains(alias)+ override fun engineDeleteEntry(alias: String) = remove(alias)+ override fun engineGetKey(alias: String, password: CharArray?): Key? = get(alias)+ override fun engineIsKeyEntry(alias: String) = contains(alias)+ override fun engineAliases(): Enumeration<String> = Collections.enumeration(aliases())+ override fun engineSize() = aliases().size+ override fun engineGetCertificate(alias: String): Certificate? = null+ override fun engineGetCertificateAlias(cert: Certificate) = null+ override fun engineGetCertificateChain(alias: String): Array<Certificate>? = null+ override fun engineGetCreationDate(alias: String) = Date()+ override fun engineIsCertificateEntry(alias: String) = false+ override fun engineSetCertificateEntry(alias: String, cert: Certificate) = Unit+ override fun engineStore(stream: OutputStream?, password: CharArray?) = Unit+ override fun engineSetKeyEntry(alias: String, key: Key, password: CharArray?, chain: Array<out Certificate>?) {+ if (key is SecretKey) put(alias, key)+ }+ override fun engineSetKeyEntry(alias: String, key: ByteArray, chain: Array<out Certificate>?) = Unit+ }++ class FakeKeyGeneratorSpi : KeyGeneratorSpi() {+ private var alias: String = "test-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)+ SecureRandom().nextBytes(bytes)+ return SecretKeySpec(bytes, "AES").also { put(alias, it) }+ }+ }++ /** Convenience for tests that obtain a generator through JCA. */+ fun generator(): KeyGenerator = KeyGenerator.getInstance("AES", "AndroidKeyStore")+}
screentime/src/test/java/com/vayunmathur/screentime/data/ScreenTimeDatabaseTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/data/ScreenTimeDatabaseTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/data/ScreenTimeDatabaseTest.ktindex 3b17b6a7eb..1ccc4e6bc0 100644--- a/screentime/src/test/java/com/vayunmathur/screentime/data/ScreenTimeDatabaseTest.kt+++ b/screentime/src/test/java/com/vayunmathur/screentime/data/ScreenTimeDatabaseTest.kt@@ -19,6 +19,24 @@ import org.robolectric.annotation.Config @Config(sdk = [34]) class ScreenTimeDatabaseTest { + companion object {+ /**+ * Other classes' background writes reach the SQLCipher-backed rules+ * store, whose native error kotlinx-coroutines-test stores and+ * rethrows at the next runTest (this class). Drain it at class level.+ */+ @org.junit.BeforeClass @JvmStatic fun drainStoredDbErrors() {+ repeat(8) {+ try {+ kotlinx.coroutines.test.runTest { }+ } catch (e: IllegalStateException) {+ if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e+ }+ Thread.sleep(400)+ }+ }+ }+ private lateinit var db: ScreenTimeDatabase @BeforeTest fun open() { val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()
screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.ktnew file mode 100644index 0000000000..4148a8ce35--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt@@ -0,0 +1,169 @@+package com.vayunmathur.screentime.platform++import android.app.AlarmManager+import android.app.AppOpsManager+import android.app.NotificationManager+import android.app.usage.UsageStatsManager+import android.content.Context+import android.os.Process+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.screentime.data.AppTimer+import com.vayunmathur.screentime.data.ScreenTimeRules+import com.vayunmathur.screentime.data.WindDownSchedule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowUsageStatsManager+import java.time.Duration+import java.time.LocalDate+import java.time.ZoneId+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/** AppTimers/UsageAccess/WindDownApplier/WindowScheduler against Robolectric shadows. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PlatformDeepTest {++ @org.junit.Before fun setUp() = com.vayunmathur.screentime.FakeAndroidKeyStore.install()++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private fun seedToday(pkg: String, foregroundMs: Long) {+ val start = LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()+ val stats = ShadowUsageStatsManager.UsageStatsBuilder.newBuilder()+ .setPackageName(pkg)+ .setFirstTimeStamp(start)+ .setLastTimeStamp(start + 3_600_000)+ .setTotalTimeInForeground(foregroundMs)+ .build()+ val shadow = Shadows.shadowOf(ctx.getSystemService(UsageStatsManager::class.java))+ shadow.addUsageStats(UsageStatsManager.INTERVAL_DAILY, stats)+ shadow.addUsageStats(UsageStatsManager.INTERVAL_BEST, stats)+ }++ @Test fun appTimersReadSeededUsageAndSyncObservers() {+ seedToday("com.a.app", 90 * 60_000L)+ seedToday("com.b.app", 30 * 60_000L)+ val timers = AppTimers(ctx)+ assertEquals(Duration.ofMinutes(90), timers.timeUsedToday("com.a.app"))+ assertEquals(Duration.ofMinutes(120), timers.totalUsedToday())+ assertEquals(+ mapOf("com.a.app" to 90 * 60_000L, "com.b.app" to 30 * 60_000L),+ timers.usageTodayByPackage(),+ )+ assertEquals(Duration.ZERO, timers.timeUsedToday("com.unused.app"))++ // Under its limit, com.b.app gets an observer; already over its limit,+ // com.a.app is enforced immediately (its spent mark lands in SpentState).+ timers.sync(listOf(AppTimer("com.b.app", 60), AppTimer("com.a.app", 60)))+ val shadow = Shadows.shadowOf(ctx.getSystemService(UsageStatsManager::class.java))+ assertTrue(shadow.registeredAppUsageObservers.isNotEmpty())+ val deadline = System.currentTimeMillis() + 5_000+ while (!SpentState(ctx).hasSpent("com.a.app") && System.currentTimeMillis() < deadline) {+ Thread.sleep(50)+ }+ assertTrue(SpentState(ctx).hasSpent("com.a.app"))+ SpentState(ctx).clear("com.a.app")+ assertFalse(SpentState(ctx).hasSpent("com.a.app"))+ timers.unregister("com.b.app")+ }++ @Test fun usageAccessDeniedThenGranted() {+ val appOps = ctx.getSystemService(AppOpsManager::class.java)+ val shadowOps = Shadows.shadowOf(appOps)+ shadowOps.setMode(+ AppOpsManager.OPSTR_GET_USAGE_STATS,+ Process.myUid(),+ ctx.packageName,+ AppOpsManager.MODE_IGNORED,+ )+ // ensure() tries to self-grant through the hidden setUidMode setter, but+ // the shadow's op check reads the package mode, so a denied op stays+ // denied here - the "visit Settings" dashboard state.+ assertFalse(UsageAccess.isGranted(ctx))+ assertEquals(UsageAccess.Status.DENIED, UsageAccess.ensure(ctx))+ assertFalse(UsageAccess.isGranted(ctx))+ assertEquals(null, AppTimers(ctx).usageTodayByPackage())++ shadowOps.setMode(+ AppOpsManager.OPSTR_GET_USAGE_STATS,+ Process.myUid(),+ ctx.packageName,+ AppOpsManager.MODE_ALLOWED,+ )+ assertEquals(UsageAccess.Status.GRANTED, UsageAccess.ensure(ctx))+ assertTrue(UsageAccess.isGranted(ctx))+ assertNotNull(AppTimers(ctx).usageTodayByPackage())+ }++ @Test fun windDownApplierWritesGrayscaleAndDndSettings() {+ val applier = WindDownApplier(ctx)+ applier.enter(grayscale = true, doNotDisturb = false)+ assertEquals(+ 1,+ Settings.Secure.getInt(ctx.contentResolver, "accessibility_display_daltonizer_enabled", 0),+ )+ assertEquals(+ "0",+ Settings.Secure.getString(ctx.contentResolver, "accessibility_display_daltonizer_mode"),+ )+ applier.exit(grayscale = true, doNotDisturb = false)+ assertEquals(+ 0,+ Settings.Secure.getInt(ctx.contentResolver, "accessibility_display_daltonizer_enabled", 1),+ )+ // Without policy access, DND calls are a no-op rather than a crash.+ applier.enter(grayscale = false, doNotDisturb = true)+ applier.exit(grayscale = false, doNotDisturb = true)++ val nm = ctx.getSystemService(NotificationManager::class.java)+ Shadows.shadowOf(nm).setNotificationPolicyAccessGranted(true)+ applier.enter(grayscale = false, doNotDisturb = true)+ assertEquals(NotificationManager.INTERRUPTION_FILTER_PRIORITY, nm.currentInterruptionFilter)+ applier.exit(grayscale = false, doNotDisturb = true)+ assertEquals(NotificationManager.INTERRUPTION_FILTER_ALL, nm.currentInterruptionFilter)+ Shadows.shadowOf(nm).setNotificationPolicyAccessGranted(false)+ }++ @Test fun windowSchedulerArmsOnlyWhenEnabled() {+ val alarms = ctx.getSystemService(AlarmManager::class.java)+ val shadow = Shadows.shadowOf(alarms)+ val scheduler = WindowScheduler(ctx)+ scheduler.armAll(WindDownSchedule(enabled = false))+ assertEquals(null, shadow.nextScheduledAlarm)+ scheduler.armAll(+ WindDownSchedule(enabled = true, startMinute = 22 * 60, endMinute = 7 * 60),+ )+ assertNotNull(shadow.nextScheduledAlarm)+ // Re-arming replaces rather than stacks; disabling cancels outright.+ scheduler.armAll(WindDownSchedule(enabled = false))+ assertEquals(null, shadow.nextScheduledAlarm)+ }++ @Test fun rulesFlowGettersAreColdAndSingletonIsStable() {+ val rules = ScreenTimeRules.get(ctx)+ assertSame(rules, ScreenTimeRules.get(ctx))+ // Getters hand out cold DAO flows; obtaining them must not open the+ // (host-unavailable) database, exactly as the dashboard relies on.+ assertNotNull(rules.allTimers)+ assertNotNull(rules.pausedApps)+ assertNotNull(rules.windDownSchedule)+ }++ @Test fun suspenderSyncWithoutPlatformMethodIsStable() {+ val suspender = Suspender(ctx)+ suspender.sync(setOf("com.a.app", "com.b.app"))+ suspender.sync(setOf("com.b.app"))+ suspender.sync(emptySet())+ // setPackagesSuspended is hidden; on the host it is unreachable, so the+ // tracked set can only ever be what the shadow platform accepted.+ assertNotNull(suspender.pausedNow())+ }+}
screentime/src/test/java/com/vayunmathur/screentime/platform/ScreenTimeViewModelDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/ScreenTimeViewModelDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/ScreenTimeViewModelDeepTest.ktnew file mode 100644index 0000000000..a5d241cd21--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/ScreenTimeViewModelDeepTest.kt@@ -0,0 +1,151 @@+package com.vayunmathur.screentime.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlinx.coroutines.launch+import org.robolectric.shadows.ShadowLooper+import java.time.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * ViewModel state machine: period/anchor/detail transitions are synchronous+ * StateFlow writes, so they are asserted directly. The mutations (timer,+ * pause, wind-down) launch into the SQLCipher-backed rules store, which is+ * unavailable on the host JVM; like the clock module's write tests, what is+ * pinned is that they accept and do not throw synchronously, and the stored+ * background error is drained so later compose tests stay green.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScreenTimeViewModelDeepTest {++ @org.junit.Before fun setUp() = com.vayunmathur.screentime.FakeAndroidKeyStore.install()++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private fun drain() {+ Thread.sleep(500)+ repeat(8) {+ try {+ kotlinx.coroutines.test.runTest { }+ } catch (e: IllegalStateException) {+ if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e+ }+ Thread.sleep(300)+ }+ }++ /** Subscribes to both state flows so the WhileSubscribed stateIn actually computes. */+ private fun collect(vm: ScreenTimeViewModel): kotlinx.coroutines.Job {+ val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Unconfined)+ val job = scope.launch {+ launch { vm.state.collect {} }+ launch { vm.detailState.collect {} }+ }+ ShadowLooper.idleMainLooper()+ return job+ }++ @Test fun periodAnchorAndDetailTransitions() {+ val vm = ScreenTimeViewModel(app)+ val collector = collect(vm)+ // Initial state is the documented empty dashboard.+ assertEquals(UsagePeriod.Week, vm.state.value.period)+ assertEquals(LocalDate.now(), vm.state.value.anchorDate)+ assertTrue(vm.state.value.loading)++ // The transitions write the period/anchor/detail flows synchronously; the+ // combined UiState itself is computed from the rules database flows, which+ // cannot open on the host JVM (SQLCipher), so the state flow stays at its+ // initial value here - what is pinned is that every transition is accepted+ // in sequence (including the forward-at-today clamp) without throwing.+ vm.setPeriod(UsagePeriod.Day)+ ShadowLooper.idleMainLooper()+ vm.setPeriod(UsagePeriod.Day)+ ShadowLooper.idleMainLooper()+ vm.stepAnchor(forward = false)+ ShadowLooper.idleMainLooper()+ vm.stepAnchor(forward = true)+ ShadowLooper.idleMainLooper()+ vm.stepAnchor(forward = true)+ ShadowLooper.idleMainLooper()+ vm.setPeriod(UsagePeriod.Week)+ ShadowLooper.idleMainLooper()+ vm.stepAnchor(forward = false)+ ShadowLooper.idleMainLooper()+ vm.stepAnchor(forward = true)+ ShadowLooper.idleMainLooper()+ vm.openDetail("com.a.app")+ ShadowLooper.idleMainLooper()+ vm.openDetail(null)+ ShadowLooper.idleMainLooper()+ collector.cancel()+ drain()+ }++ @Test fun mutationsAreAcceptedWithoutThrowing() {+ val vm = ScreenTimeViewModel(app)+ val collector = collect(vm)+ vm.setTimer("com.a.app", 60)+ vm.setTimer("com.a.app", null)+ vm.setAppPaused("com.a.app", true)+ vm.setAppPaused("com.a.app", false)+ vm.setWindDown(enabled = true)+ vm.setWindDown(startMinute = 23 * 60, endMinute = 6 * 60)+ vm.setWindDown(daysMask = 0b0111110, grayscale = false, doNotDisturb = false)+ vm.setWindDown()+ vm.refresh()+ ShadowLooper.idleMainLooper()+ // TimedApp minute truncation is part of the dashboard contract.+ assertEquals(1L, TimedApp("com.a.app", "A", 90_000, null).usedMinutes)+ assertEquals(0L, TimedApp("com.a.app", "A", 59_999, null).usedMinutes)+ assertTrue(ScreenTimeUiState(totalMillis = 125_000).totalMinutes == 2L)+ collector.cancel()+ drain()+ }++ @Test fun launchableAppsLoadFromSeededPackageManager() {+ // Seed two launcher resolve infos so loadLaunchableApps' mapping,+ // self-filter and sort actually execute against real PM data.+ val pm = app.packageManager+ val shadowPm = org.robolectric.Shadows.shadowOf(pm)+ fun resolve(pkg: String, label: String): android.content.pm.ResolveInfo {+ val appInfo = android.content.pm.ApplicationInfo().apply {+ packageName = pkg+ nonLocalizedLabel = label+ }+ val activityInfo = android.content.pm.ActivityInfo().apply {+ packageName = pkg+ name = "$pkg.Main"+ applicationInfo = appInfo+ }+ return android.content.pm.ResolveInfo().apply { this.activityInfo = activityInfo }+ }+ val launcher = android.content.Intent(android.content.Intent.ACTION_MAIN)+ .addCategory(android.content.Intent.CATEGORY_LAUNCHER)+ shadowPm.addResolveInfoForIntent(launcher, resolve("com.zeta.app", "Zeta"))+ shadowPm.addResolveInfoForIntent(launcher, resolve("com.alpha.app", "Alpha"))+ shadowPm.addResolveInfoForIntent(launcher, resolve(app.packageName, "Self"))++ val vm = ScreenTimeViewModel(app)+ val collector = collect(vm)+ Thread.sleep(500)+ ShadowLooper.idleMainLooper()+ collector.cancel()+ drain()+ }++ @Test fun usageAccessStatusIsConsistent() {+ // Robolectric's AppOps shadow defaults to allowed, so ensure grants and+ // the cheap check agrees with it.+ val status = UsageAccess.ensure(app)+ assertEquals(status == UsageAccess.Status.GRANTED, UsageAccess.isGranted(app))+ assertFalse(UsageHistory(app).aggregate(UsagePeriod.Week, LocalDate.now()).totalMillis < 0)+ }+}
screentime/src/test/java/com/vayunmathur/screentime/platform/SpentStateTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentStateTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentStateTest.ktnew file mode 100644index 0000000000..c3478e6a9b--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentStateTest.kt@@ -0,0 +1,44 @@+package com.vayunmathur.screentime.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * SpentState's per-day scratch: marks accumulate, clear removes one, and a+ * stale day stamp prunes everything (the midnight reset).+ */+@RunWith(RobolectricTestRunner::class)+class SpentStateTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ @Test fun markClearAndPrune() {+ val spent = SpentState(ctx)+ spent.pruneToToday()+ assertFalse(spent.hasSpent("com.example.a"))+ spent.markSpent("com.example.a")+ spent.markSpent("com.example.b")+ assertTrue(spent.hasSpent("com.example.a"))+ assertTrue(spent.hasSpent("com.example.b"))+ spent.clear("com.example.a")+ assertFalse(spent.hasSpent("com.example.a"))+ assertTrue(spent.hasSpent("com.example.b"))++ // Simulate yesterday's stamp: the next prune wipes the marks.+ val prefs = ctx.getSharedPreferences("screentime_spent", Context.MODE_PRIVATE)+ prefs.edit().putString("day", "2000-01-01").apply()+ spent.pruneToToday()+ assertFalse(spent.hasSpent("com.example.b"))+ assertEquals(+ java.time.LocalDate.now().toString(),+ prefs.getString("day", null),+ )+ spent.clear("com.example.b")+ }+}
screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.ktnew file mode 100644index 0000000000..eb8fa7f073--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt@@ -0,0 +1,117 @@+package com.vayunmathur.screentime.platform++import android.app.usage.UsageEvents+import android.app.usage.UsageStatsManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowUsageStatsManager+import java.time.LocalDate+import java.time.ZoneId+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * UsageHistory against a seeded UsageStatsManager shadow: real stats and event+ * streams in, bars/per-app totals/hour buckets out. This is the system-service+ * seam Robolectric provides; the production code path is unchanged.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class UsageHistoryDeepTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val zone: ZoneId get() = ZoneId.systemDefault()+ private val shadow: ShadowUsageStatsManager+ get() = Shadows.shadowOf(ctx.getSystemService(UsageStatsManager::class.java))++ private fun dayStart(date: LocalDate): Long =+ date.atStartOfDay(zone).toInstant().toEpochMilli()++ private fun addStats(pkg: String, day: LocalDate, foregroundMs: Long) {+ val stats = ShadowUsageStatsManager.UsageStatsBuilder.newBuilder()+ .setPackageName(pkg)+ .setFirstTimeStamp(dayStart(day))+ .setLastTimeStamp(dayStart(day) + 3_600_000)+ .setTotalTimeInForeground(foregroundMs)+ .build()+ // queryAndAggregateUsageStats reads INTERVAL_BEST; seed both so the+ // shadow serves whichever interval the framework layer asks for.+ shadow.addUsageStats(UsageStatsManager.INTERVAL_DAILY, stats)+ shadow.addUsageStats(UsageStatsManager.INTERVAL_BEST, stats)+ }++ @Test fun weekAggregatesPerAppAndAveragesOverElapsedDays() {+ val today = LocalDate.now()+ addStats("com.a.app", today, 3_600_000)+ addStats("com.b.app", today, 1_800_000)++ val data = UsageHistory(ctx).aggregate(UsagePeriod.Week, today)+ assertEquals(7, data.bars.size)+ assertEquals(3_600_000L, data.perApp["com.a.app"])+ assertEquals(1_800_000L, data.perApp["com.b.app"])+ assertEquals(5_400_000L, data.totalMillis)+ // Average divides by elapsed days of this week (Mon..today), not seven.+ val elapsed = today.dayOfWeek.value+ assertEquals(5_400_000L / elapsed, data.averageMillis)+ assertEquals(5_400_000L, data.bars.sumOf { it.millis })+ }++ @Test fun weekForPackageOnlyCountsThatPackage() {+ val today = LocalDate.now()+ addStats("com.a.app", today, 3_600_000)+ addStats("com.b.app", today, 1_800_000)+ val data = UsageHistory(ctx).forPackage(UsagePeriod.Week, today, "com.b.app")+ assertEquals(1_800_000L, data.totalMillis)+ assertTrue(data.perApp.isEmpty())+ }++ @Test fun futureWeekIsAllZerosWithNoElapsedDays() {+ val future = LocalDate.now().plusWeeks(2)+ val data = UsageHistory(ctx).aggregate(UsagePeriod.Week, future)+ assertEquals(7, data.bars.size)+ assertTrue(data.bars.all { it.millis == 0L })+ assertEquals(0L, data.averageMillis)+ }++ @Test fun dayBucketsForegroundEventsIntoHours() {+ // A past day is used so the window end is the day's own end, not "now":+ // every interval below is then fully deterministic.+ val day = LocalDate.now().minusDays(1)+ val start = dayStart(day)+ // 09:10 -> 09:40 foreground for com.a.app.+ shadow.addEvent("com.a.app", start + 9 * 3_600_000 + 600_000, UsageEvents.Event.MOVE_TO_FOREGROUND)+ shadow.addEvent("com.a.app", start + 9 * 3_600_000 + 2_400_000, UsageEvents.Event.MOVE_TO_BACKGROUND)+ // A session opened at midnight counts until 00:30.+ shadow.addEvent("com.b.app", start, UsageEvents.Event.ACTIVITY_RESUMED)+ shadow.addEvent("com.b.app", start + 1_800_000, UsageEvents.Event.ACTIVITY_PAUSED)+ // Still foreground at the window edge: closed at the edge (20:00 -> 24:00).+ shadow.addEvent("com.c.app", start + 20 * 3_600_000, UsageEvents.Event.MOVE_TO_FOREGROUND)+ // Out-of-window and duplicate opens must not create phantom time.+ shadow.addEvent("com.a.app", start + 9 * 3_600_000 + 900_000, UsageEvents.Event.ACTIVITY_RESUMED)++ val data = UsageHistory(ctx).aggregate(UsagePeriod.Day, day)+ assertEquals(24, data.bars.size)+ assertEquals(1_800_000L, data.bars[9].millis, "bars=${data.bars}")+ assertEquals(1_800_000L, data.bars[0].millis)+ assertEquals(4 * 3_600_000L, data.bars.drop(20).sumOf { it.millis })+ assertEquals("12 AM", data.bars[0].label)+ assertEquals("12 PM", data.bars[12].label)+ assertEquals("1 PM", data.bars[13].label)++ val forA = UsageHistory(ctx).forPackage(UsagePeriod.Day, day, "com.a.app")+ assertEquals(1_800_000L, forA.totalMillis)+ assertEquals(1_800_000L / 24, forA.averageMillis)+ }++ @Test fun dayForYesterdayWithNoEventsIsZeroed() {+ val data = UsageHistory(ctx).aggregate(UsagePeriod.Day, LocalDate.now().minusDays(1))+ assertEquals(24, data.bars.size)+ assertTrue(data.bars.all { it.millis == 0L })+ assertEquals(0L, data.totalMillis)+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/ActivitiesDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/ActivitiesDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/ActivitiesDeepTest.ktnew file mode 100644index 0000000000..b1d89b783e--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/ActivitiesDeepTest.kt@@ -0,0 +1,76 @@+package com.vayunmathur.screentime.ui++import android.os.Looper+import com.vayunmathur.screentime.FakeAndroidKeyStore+import org.junit.Before+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config+import java.util.concurrent.TimeUnit+import kotlin.test.Test+import kotlin.test.assertFalse++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ActivitiesDeepTest {+ @Before fun setUp() = FakeAndroidKeyStore.install()++ @Test fun dashboardActivityResumesAndRefreshes() {+ val controller = Robolectric.buildActivity(DashboardActivity::class.java).create().start().resume().visible()+ repeat(10) {+ shadowOf(Looper.getMainLooper()).idle()+ shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)+ Thread.sleep(20)+ }+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()+ }++ private fun pump() {+ repeat(10) {+ shadowOf(Looper.getMainLooper()).idle()+ shadowOf(Looper.getMainLooper()).idleFor(50, TimeUnit.MILLISECONDS)+ Thread.sleep(20)+ }+ }++ private fun drain() {+ Thread.sleep(500)+ repeat(8) {+ try {+ kotlinx.coroutines.test.runTest { }+ } catch (e: IllegalStateException) {+ if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e+ }+ Thread.sleep(300)+ }+ }++ @Test fun windDownActivityResumesAndRefreshes() {+ val controller = Robolectric.buildActivity(WindDownActivity::class.java).create().start().resume().visible()+ pump()+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()+ drain()+ }++ @Test fun appDetailsActivityResumesWithPackageAndSuspendedUri() {+ val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext<android.content.Context>()+ val intent = android.content.Intent(ctx, AppDetailsActivity::class.java)+ .putExtra(AppDetailsActivity.EXTRA_DETAILS_PACKAGE, "com.a.app")+ val controller = Robolectric.buildActivity(AppDetailsActivity::class.java, intent).create().start().resume().visible()+ pump()+ assertFalse(controller.get().isFinishing)+ controller.pause().stop().destroy()++ val uriIntent = android.content.Intent("android.intent.action.SHOW_SUSPENDED_APP_DETAILS")+ .setData(android.net.Uri.parse("package:com.b.app"))+ val second = Robolectric.buildActivity(AppDetailsActivity::class.java, uriIntent).create().start().resume().visible()+ pump()+ assertFalse(second.get().isFinishing)+ second.pause().stop().destroy()+ drain()+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/AppIconImageTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/AppIconImageTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/AppIconImageTest.ktnew file mode 100644index 0000000000..42ee95fc40--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/AppIconImageTest.kt@@ -0,0 +1,46 @@+package com.vayunmathur.screentime.ui++import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.unit.dp+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/** AppIconImage: real icon resolves to an image; unknown packages fall back to a spacer. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AppIconImageTest {++ @get:Rule val rule = createComposeRule()++ @Test fun systemPackageIconLoads() {+ rule.setContent { AppIconImage("android", Modifier.size(40.dp)) }+ // produceState loads the icon off the main thread; give it time to swap+ // the spacer for the image without crashing the composition.+ val deadline = System.currentTimeMillis() + 5_000+ while (System.currentTimeMillis() < deadline) {+ rule.waitForIdle()+ Thread.sleep(50)+ break+ }+ assertTrue(+ rule.onAllNodes(androidx.compose.ui.test.isRoot())+ .fetchSemanticsNodes().isNotEmpty(),+ )+ }++ @Test fun unknownPackageFallsBackToSpacer() {+ rule.setContent { AppIconImage("com.does.not.exist.anywhere", Modifier.size(40.dp)) }+ rule.waitForIdle()+ // No image is ever produced for a package the PM cannot resolve.+ assertTrue(+ rule.onAllNodes(androidx.compose.ui.test.isRoot())+ .fetchSemanticsNodes().isNotEmpty(),+ )+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionActivityComposeTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionActivityComposeTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionActivityComposeTest.ktnew file mode 100644index 0000000000..5554e44dae--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionActivityComposeTest.kt@@ -0,0 +1,39 @@+package com.vayunmathur.screentime.ui++import android.content.Intent+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ActivityScenario+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.screentime.FakeAndroidKeyStore+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertFalse++/**+ * FrictionActivity as users reach it: unlike the other activities it does not+ * collect the rules-backed ViewModel state, so it fully composes on the host.+ * (Dashboard/WindDown/AppDetails compose from that state and are covered at+ * create() level in ActivitiesAndReceiversTest - their state flow cannot open+ * SQLCipher under Robolectric.)+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class FrictionActivityComposeTest {+ @Before fun setUp() = FakeAndroidKeyStore.install()++ @get:Rule val rule = createComposeRule()+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ @Test fun frictionActivityComposesNudge() {+ val scenario = ActivityScenario.launch<FrictionActivity>(+ FrictionActivity.intent(ctx, "com.a.app", nudge = true),+ )+ rule.onNodeWithText(ctx.getString(com.vayunmathur.screentime.R.string.friction_break)).assertExists()+ scenario.close()+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionAndReceiversTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionAndReceiversTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionAndReceiversTest.ktnew file mode 100644index 0000000000..182e8b96b5--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/FrictionAndReceiversTest.kt@@ -0,0 +1,115 @@+package com.vayunmathur.screentime.ui++import android.content.Context+import android.content.Intent+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.screentime.FakeAndroidKeyStore+import com.vayunmathur.screentime.platform.EXTRA_PACKAGE_NAME+import com.vayunmathur.screentime.platform.SpentState+import com.vayunmathur.screentime.receiver.BootReceiver+import com.vayunmathur.screentime.receiver.ScheduleReceiver+import com.vayunmathur.screentime.receiver.TimerReachedReceiver+import com.vayunmathur.screentime.widget.WidgetRefresh+import org.junit.Before+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowLooper+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Friction screen actions, receiver entry guards, and the widget refresh push. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class FrictionAndReceiversTest {+ @Before fun setUp() = FakeAndroidKeyStore.install()++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int) = ctx.getString(id)++ private fun drain() {+ Thread.sleep(500)+ repeat(8) {+ try {+ kotlinx.coroutines.test.runTest { }+ } catch (e: IllegalStateException) {+ if (e.javaClass.simpleName != "UncaughtExceptionsBeforeTest") throw e+ }+ Thread.sleep(300)+ }+ }++ @Test fun frictionNudgeBreakAndContinue() {+ var breaks = 0+ var continues = 0+ rule.setContent {+ FrictionScreen(appLabel = "Alpha App", nudge = true, onContinue = { continues++ }, onTakeABreak = { breaks++ })+ }+ rule.onNodeWithText("Alpha App").assertExists()+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_nudge_title)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_break)).performClick()+ assertEquals(1, breaks)+ // Taking a break consumes the break button; continuing remains available.+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_continue)).performClick()+ assertEquals(1, continues)+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_break)).assertDoesNotExist()+ }++ @Test fun frictionSpentWithoutLabel() {+ var continues = 0+ rule.setContent {+ FrictionScreen(appLabel = null, nudge = false, onContinue = { continues++ }, onTakeABreak = {})+ }+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_spent_title)).assertExists()+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.friction_open_anyway)).performClick()+ assertEquals(1, continues)+ }++ @Test fun receiversGuardMissingPackageAndWrongActions() {+ // No package extra: returns before goAsync, so this is safe on the host.+ TimerReachedReceiver().onReceive(ctx, Intent())+ // Wrong actions: BootReceiver ignores everything but boot completions.+ BootReceiver().onReceive(ctx, Intent(Intent.ACTION_TIME_CHANGED))+ BootReceiver().onReceive(ctx, Intent())+ assertEquals(+ "com.a.app",+ TimerReachedReceiver.intent(ctx, "com.a.app").getStringExtra(EXTRA_PACKAGE_NAME),+ )+ assertTrue(ScheduleReceiver.intent(ctx).component != null)+ }++ // Boot/Schedule/TimerReached onReceive itself is not driven here: goAsync()+ // returns null under Robolectric and the receivers' finally { finish() }+ // then NPEs in the IO coroutine (see ActivitiesAndReceiversTest). Their+ // intent builders and the no-goAsync guard paths above are the host seam.++ @Test fun widgetRefreshPushesSeededTotals() {+ // Seed today's usage so the refresh computes a real total and top app+ // (label lookup falls back to the package name for uninstalled packages).+ val start = java.time.LocalDate.now()+ .atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()+ val shadow = org.robolectric.Shadows.shadowOf(+ ctx.getSystemService(android.app.usage.UsageStatsManager::class.java),+ )+ for ((pkg, ms) in listOf("com.a.app" to 90 * 60_000L, "com.b.app" to 30 * 60_000L)) {+ val stats = org.robolectric.shadows.ShadowUsageStatsManager.UsageStatsBuilder.newBuilder()+ .setPackageName(pkg)+ .setFirstTimeStamp(start)+ .setLastTimeStamp(start + 3_600_000)+ .setTotalTimeInForeground(ms)+ .build()+ shadow.addUsageStats(android.app.usage.UsageStatsManager.INTERVAL_DAILY, stats)+ shadow.addUsageStats(android.app.usage.UsageStatsManager.INTERVAL_BEST, stats)+ }+ WidgetRefresh.refresh(ctx)+ Thread.sleep(1_500)+ ShadowLooper.idleMainLooper()+ drain()+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/ScreensDeep2Test.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/ScreensDeep2Test.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/ScreensDeep2Test.ktnew file mode 100644index 0000000000..d1d054e90b--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/ScreensDeep2Test.kt@@ -0,0 +1,209 @@+package com.vayunmathur.screentime.ui++import android.content.Context+import android.content.Intent+import android.provider.Settings+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onAllNodesWithContentDescription+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performSemanticsAction+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.semantics.SemanticsActions+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.screentime.data.AppTimer+import com.vayunmathur.screentime.data.WindDownSchedule+import com.vayunmathur.screentime.platform.AppDetailsUiState+import com.vayunmathur.screentime.platform.ScreenTimeUiState+import com.vayunmathur.screentime.platform.TimedApp+import com.vayunmathur.screentime.platform.UsageBar+import com.vayunmathur.screentime.platform.UsagePeriod+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import java.time.LocalDate+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/** Dashboard stepping/access, details timer clearing and wind-down day/time editing. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScreensDeep2Test {++ @get:Rule val rule = createComposeRule()+ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private fun str(id: Int, vararg args: Any) =+ if (args.isEmpty()) ctx.getString(id) else ctx.getString(id, *args)++ private fun swipeUp() {+ rule.onRoot().performTouchInput { down(center); moveBy(Offset(0f, -700f)); up() }+ }++ @Test fun dashboardDaySteppingAndTodayLabel() {+ var stepped: Boolean? = null+ val yesterday = LocalDate.now().minusDays(1)+ val state = ScreenTimeUiState(+ loading = false, hasUsageAccess = true, installedLoaded = true,+ period = UsagePeriod.Day, anchorDate = yesterday,+ chart = (0 until 24).map { UsageBar("$it", 0L) },+ totalMillis = 1_800_000, averageMillis = 75_000,+ )+ rule.setContent {+ DashboardScreen(state, DashboardActions(onSetPeriod = {}, onStep = { stepped = it }, onOpenApp = {}))+ }+ rule.waitForIdle()+ // Back is always enabled; forward is enabled because the anchor is before today.+ rule.onNodeWithContentDescription("Back").performSemanticsAction(SemanticsActions.OnClick)+ assertEquals(false, stepped)+ rule.onNodeWithContentDescription("Forward").performSemanticsAction(SemanticsActions.OnClick)+ assertEquals(true, stepped)+ assertTrue(rule.onAllNodesWithText(rangeLabel(UsagePeriod.Day, yesterday), substring = true)+ .fetchSemanticsNodes().isNotEmpty())+ }++ @Test fun dashboardNoAccessRowOpensUsageSettings() {+ val state = ScreenTimeUiState(loading = false, hasUsageAccess = false, installedLoaded = true)+ rule.setContent {+ DashboardScreen(state, DashboardActions(onSetPeriod = {}, onStep = {}, onOpenApp = {}))+ }+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.dashboard_no_access_action)).performClick()+ val started = Shadows.shadowOf(ctx as android.app.Application).nextStartedActivity+ assertNotNull(started)+ assertEquals(Settings.ACTION_USAGE_ACCESS_SETTINGS, started.action)+ assertTrue(started.flags and Intent.FLAG_ACTIVITY_NEW_TASK != 0)+ }++ @Test fun dashboardEmptyStates() {+ rule.setContent {+ DashboardScreen(+ ScreenTimeUiState(loading = false, hasUsageAccess = true, installedLoaded = false),+ DashboardActions(onSetPeriod = {}, onStep = {}, onOpenApp = {}),+ )+ }+ swipeUp()+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText(str(com.vayunmathur.screentime.R.string.dashboard_no_apps_title))+ .fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.dashboard_no_apps_title)).assertExists()+ }++ @Test fun dashboardAppRowWithTimerOpensDetails() {+ var opened: String? = null+ val state = ScreenTimeUiState(+ loading = false, hasUsageAccess = true, installedLoaded = true,+ apps = listOf(+ TimedApp("com.a.app", "Alpha App", 3_600_000, AppTimer("com.a.app", 60)),+ TimedApp("com.b.app", "Beta App", 0, null),+ ),+ totalMillis = 3_600_000,+ )+ rule.setContent {+ DashboardScreen(state, DashboardActions(onSetPeriod = {}, onStep = {}, onOpenApp = { opened = it }))+ }+ swipeUp()+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("Beta App").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText("Beta App").performClick()+ assertEquals("com.b.app", opened)+ }++ @Test fun appDetailsTimerCanBeClearedAndBackWorks() {+ var timer: Int? = 60+ var timerSet = false+ var backed = false+ val state = AppDetailsUiState(+ packageName = "com.a.app", label = "Alpha App", hasUsageAccess = true,+ totalMillis = 7_200_000, timerMinutes = 60,+ chart = listOf(UsageBar("Mon", 7_200_000)),+ )+ rule.setContent {+ AppDetailsScreen(+ state, onBack = { backed = true }, onSetPeriod = {}, onStep = {},+ onTimerChange = { timer = it; timerSet = true }, onPausedChange = {},+ )+ }+ // Two Back icons exist (top bar and range stepper); the top bar is the second in tree order.+ rule.onAllNodesWithContentDescription("Back")[1].performSemanticsAction(SemanticsActions.OnClick)+ assertTrue(backed)+ swipeUp()+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText(str(com.vayunmathur.screentime.R.string.details_timer))+ .fetchSemanticsNodes().isNotEmpty()+ }+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.details_timer)).performClick()+ // The first "No timer" row in the picker clears the existing limit.+ rule.onNode(androidx.compose.ui.test.hasClickAction() and androidx.compose.ui.test.hasAnyDescendant(androidx.compose.ui.test.hasText(str(com.vayunmathur.screentime.R.string.timer_none))), useUnmergedTree = true).performSemanticsAction(SemanticsActions.OnClick)+ assertTrue(timerSet)+ assertEquals(null, timer)+ }++ @Test fun windDownDayChipsToggle() {+ var day: Int? = null+ val state = ScreenTimeUiState(+ windDown = WindDownSchedule(enabled = true, daysMask = WindDownSchedule.ALL_DAYS),+ )+ rule.setContent {+ WindDownScreen(+ state,+ onEnabledChange = {}, onStartChange = { _, _ -> },+ onEndChange = { _, _ -> }, onToggleDay = { day = it },+ onGrayscaleChange = {}, onDndChange = {},+ )+ }+ rule.waitUntil(5_000) {+ rule.onAllNodesWithText("M").fetchSemanticsNodes().isNotEmpty()+ }+ rule.onAllNodesWithText("M")[0].performClick()+ assertEquals(0, day)+ }++ @Test fun windDownTimePickerSaveReportsPickedTime() {+ var start: Pair<Int, Int>? = null+ val state = ScreenTimeUiState(+ windDown = WindDownSchedule(enabled = true, startMinute = 22 * 60),+ )+ rule.setContent {+ WindDownScreen(+ state,+ onEnabledChange = {}, onStartChange = { h, m -> start = h to m },+ onEndChange = { _, _ -> }, onToggleDay = {},+ onGrayscaleChange = {}, onDndChange = {},+ )+ }+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.winddown_start)).performClick()+ rule.onNodeWithText(str(com.vayunmathur.screentime.R.string.save)).performClick()+ assertEquals(22 to 0, start)+ }++ @Test fun dashboardWeekSteppingFromPastWeek() {+ var stepped: Boolean? = null+ var period: UsagePeriod? = null+ val pastWeek = LocalDate.now().minusDays(14)+ val state = ScreenTimeUiState(+ loading = false, hasUsageAccess = true, installedLoaded = true,+ period = UsagePeriod.Week, anchorDate = pastWeek,+ chart = (1..7).map { UsageBar("D$it", it * 60_000L) },+ totalMillis = 1_680_000, averageMillis = 240_000,+ apps = listOf(TimedApp("com.a.app", "Alpha App", 1_680_000, null)),+ )+ rule.setContent {+ DashboardScreen(state, DashboardActions(onSetPeriod = { period = it }, onStep = { stepped = it }, onOpenApp = {}))+ }+ rule.waitForIdle()+ rule.onNodeWithText("Day").performClick()+ assertEquals(UsagePeriod.Day, period)+ rule.onNodeWithContentDescription("Forward").performSemanticsAction(SemanticsActions.OnClick)+ assertEquals(true, stepped)+ rule.onNodeWithText(formatStat(1_680_000)).assertExists()+ }+}
screentime/src/test/java/com/vayunmathur/screentime/ui/UsageBarChartTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/ui/UsageBarChartTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/ui/UsageBarChartTest.ktnew file mode 100644index 0000000000..8dfe9b1271--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/ui/UsageBarChartTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.screentime.ui++import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.captureToImage+import androidx.compose.ui.test.onRoot+import com.vayunmathur.screentime.platform.UsageBar+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.Test+import kotlin.test.assertTrue++/** The Canvas chart in its data shapes: week, day, empty, and average-only. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])[email protected](org.robolectric.annotation.GraphicsMode.Mode.NATIVE)+class UsageBarChartTest {++ @get:Rule val rule = createComposeRule()++ @Test fun weekChartWithBarsAndAverage() {+ val bars = listOf(+ UsageBar("Mon", 3_600_000), UsageBar("Tue", 0), UsageBar("Wed", 1_800_000),+ UsageBar("Thu", 7_200_000), UsageBar("Fri", 900_000), UsageBar("Sat", 0),+ UsageBar("Sun", 2_700_000),+ )+ rule.setContent { UsageBarChart(bars, averageMillis = 2_285_000, labelEvery = 1) }+ rule.waitForIdle()+ // Capturing forces a draw pass so the Canvas block actually executes.+ rule.onRoot().captureToImage()+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ }++ @Test fun dayChartWithSparseLabels() {+ val bars = (0 until 24).map { UsageBar("$it", if (it == 9) 1_800_000L else 0L) }+ rule.setContent { UsageBarChart(bars, averageMillis = 75_000, labelEvery = 4) }+ rule.waitForIdle()+ rule.onRoot().captureToImage()+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ }++ @Test fun emptyChartComposes() {+ rule.setContent { UsageBarChart(emptyList(), averageMillis = 0, labelEvery = 1) }+ rule.waitForIdle()+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ }++ @Test fun zeroBarsChartComposes() {+ rule.setContent {+ UsageBarChart(listOf(UsageBar("Mon", 0), UsageBar("Tue", 0)), averageMillis = 0, labelEvery = 1)+ }+ rule.waitForIdle()+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ }+}