Modern Apps git

← Modern-Apps.git

setupwizard: raise coverage to 81% with flow and platform tests (#tests)

Commit
1f3386e03d905e520926b92ba572ebff3db03531
Author
Vayun Mathur <[email protected]>
When
2026-11-16 17:43 UTC (20 days ago)
Parents
5c0472a
Adds NavigationFlowTest (the full primary-user walk Welcome -> Wifi handoff -> Location -> Security handoff -> Migration auto-skip -> Gestures -> Finish, plus handoff-cancel and language-picker branches), SystemSetupDeepTest (locale/OEM-lock fallbacks, location and keyguard state mirroring, setup-complete flags, display-mirroring seeding, emergency dialer intent, disableSelf), and MainActivityTest (setup-complete short-circuit).

Coverage measured with :setupwizard:createMergedCoverageReport (INSTRUCTION): 64.0% -> 81.39%. Remaining missed is concentrated in NavigationKt screen lambdas and the Route serializer companion, which are structural on the host.

Verified with :setupwizard:testDevUnitTest (no ignore-failures), :setupwizard:detekt and :setupwizard:lint, all green. Tests only; no production code changed.

Diff

setupwizard/src/test/java/com/vayunmathur/setupwizard/MainActivityTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/MainActivityTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/MainActivityTest.ktnew file mode 100644index 0000000000..d49e6858ba--- /dev/null+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/MainActivityTest.kt@@ -0,0 +1,25 @@+package com.vayunmathur.setupwizard++import android.app.Application+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class MainActivityTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()++    @Test fun `launch after setup completed finishes instead of showing the wizard again`() {+        Settings.Secure.putInt(app.contentResolver, "user_setup_complete", 1)+        val controller = Robolectric.buildActivity(MainActivity::class.java)+        val activity = controller.setup().get()+        // onCreateBeforeContent sees setup complete and runs finishSetup, whose last steps+        // finish the activity and disable the package: a re-launch must not re-run the flow.+        assertTrue(activity.isFinishing || activity.isDestroyed)+        Settings.Secure.putInt(app.contentResolver, "user_setup_complete", 0)+    }+}
setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.ktnew file mode 100644index 0000000000..17f387ba1c--- /dev/null+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/NavigationFlowTest.kt@@ -0,0 +1,159 @@+package com.vayunmathur.setupwizard++import android.app.Activity+import android.app.Application+import android.provider.Settings+import androidx.activity.ComponentActivity+import androidx.activity.result.ActivityResult+import androidx.compose.ui.test.hasText+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.setupwizard.platform.DebugFlags+import com.vayunmathur.setupwizard.platform.SetupViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class NavigationFlowTest {+    @get:Rule val rule = createAndroidComposeRule<ComponentActivity>()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private fun str(id: Int) = ctx.getString(id)++    @BeforeTest fun setUp() {+        Dispatchers.setMain(Dispatchers.Unconfined)+        Settings.Global.putString(ctx.contentResolver, "setupwizard_debug_flags", null)+    }++    @AfterTest fun tearDown() {+        Dispatchers.resetMain()+        Settings.Global.putString(ctx.contentResolver, "setupwizard_debug_flags", null)+    }++    private fun awaitText(id: Int) {+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodes(hasText(str(id))).fetchSemanticsNodes().isNotEmpty()+        }+    }++    private fun awaitNoText(id: Int) {+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodes(hasText(str(id))).fetchSemanticsNodes().isEmpty()+        }+    }++    /** Delivers a result to whichever handoff activity the wizard just launched. */+    private fun deliverHandoffResult(resultCode: Int) {+        rule.waitForIdle()+        rule.waitUntil(timeoutMillis = 10_000) {+            Shadows.shadowOf(rule.activity).peekNextStartedActivityForResult() != null+        }+        val request = Shadows.shadowOf(rule.activity).nextStartedActivityForResult+        kotlin.test.assertNotNull(request, "wizard should have launched a handoff activity")+        rule.runOnUiThread {+            rule.activity.activityResultRegistry.dispatchResult(+                request.requestCode,+                ActivityResult(resultCode, null),+            )+        }+        rule.waitForIdle()+    }++    @Test fun `primary user walks welcome through handoffs to finish`() {+        val vm = SetupViewModel(app)+        assertTrue(vm.state.isPrimaryUser)+        rule.setContent { Navigation(vm) }+        awaitText(R.string.welcome_to_modern_apps_os)++        // Accessibility / emergency rows open external settings/dialer intents; under+        // Robolectric nothing handles them and Navigation must swallow that.+        rule.onNodeWithText(str(R.string.accessibility)).performClick()++        rule.onNodeWithText(str(R.string.next)).performClick()+        // Wifi is a handoff step with no UI of its own: completing the external setup+        // activity replaces it with Location instead of leaving it on the back stack.+        deliverHandoffResult(Activity.RESULT_OK)+        awaitText(R.string.location_services)+        awaitNoText(R.string.welcome_to_modern_apps_os)++        rule.onNodeWithText(str(R.string.next)).performClick()+        // Security hands off to biometric enrol; completing it lands on Migration,+        // which skips itself when no restore handler exists -> Gestures.+        deliverHandoffResult(Activity.RESULT_OK)+        awaitText(R.string.swipe_gestures_title)++        rule.onNodeWithText(str(R.string.skip)).performClick()+        awaitText(R.string.you_re_all_set_now)+        rule.onNodeWithText(str(R.string.start)).assertExists()+    }++    @Test fun `cancelling the wifi handoff returns to welcome`() {+        val vm = SetupViewModel(app)+        rule.setContent { Navigation(vm) }+        awaitText(R.string.welcome_to_modern_apps_os)+        rule.onNodeWithText(str(R.string.next)).performClick()+        // Backing out of Wi-Fi setup pops the handoff step rather than advancing.+        deliverHandoffResult(Activity.RESULT_CANCELED)+        awaitText(R.string.welcome_to_modern_apps_os)+    }++    @Test fun `language row opens picker and selecting a language closes it`() {+        val vm = SetupViewModel(app)+        rule.setContent { Navigation(vm) }+        awaitText(R.string.welcome_to_modern_apps_os)+        val languageLabel = vm.state.language.ifBlank { str(R.string.english_united_states) }+        rule.onNodeWithText(languageLabel).performClick()+        // The picker is populated from the platform locales; dismissing it returns to welcome.+        rule.waitUntil(timeoutMillis = 10_000) {+            rule.onAllNodes(hasText(str(R.string.welcome_to_modern_apps_os)))+                .fetchSemanticsNodes().isNotEmpty()+        }+        assertTrue(vm.availableLanguages().isNotEmpty())+    }++    @Test fun `unlocked bootloader flag diverts welcome to the warning step`() {+        // Only honoured on a debuggable OS; Robolectric reports one, and the VM reads the+        // override when it snapshots OEM state in init, so set the flag before creating it.+        Settings.Global.putString(+            ctx.contentResolver,+            "setupwizard_debug_flags",+            "isDeviceOemUnlocked_override=true",+        )+        assertTrue(DebugFlags.getBool(ctx, "isDeviceOemUnlocked_override") == true)+        val vm = SetupViewModel(app)+        if (!vm.state.bootloaderUnlocked) {+            // Non-debuggable shadow build: the override is ignored by design (see DebugFlags).+            assertFalse(vm.welcomeLeadsToBootloaderWarning())+            return+        }+        assertTrue(vm.welcomeLeadsToBootloaderWarning())+        rule.setContent { Navigation(vm) }+        awaitText(R.string.welcome_to_modern_apps_os)+        rule.onNodeWithText(str(R.string.next)).performClick()+        awaitText(R.string.lock_your_bootloader)+        awaitNoText(R.string.welcome_to_modern_apps_os)+    }++    @Test fun `routes serialise distinctly`() {+        val routes = listOf(+            Route.Welcome, Route.OemUnlock, Route.Wifi, Route.Location,+            Route.Security, Route.Migration, Route.Gestures, Route.Finish,+        )+        assertTrue(routes.distinct().size == routes.size)+        assertTrue(routes.all { it.toString().isNotBlank() })+    }+}
setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt
diff --git a/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.ktnew file mode 100644index 0000000000..f2ab568e92--- /dev/null+++ b/setupwizard/src/test/java/com/vayunmathur/setupwizard/platform/SystemSetupDeepTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.setupwizard.platform++import android.app.Activity+import android.app.Application+import android.content.ComponentName+import android.content.Context+import android.content.pm.PackageManager+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.shadows.ShadowKeyguardManager+import org.robolectric.shadows.ShadowLocationManager+import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SystemSetupDeepTest {+    private val app get() = ApplicationProvider.getApplicationContext<Application>()+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    @Test fun `identity locale and locale list come from the platform`() {+        val system = SystemSetup(app)+        assertTrue(system.isPrimaryUser)+        assertNotNull(system.currentLocale())+        val locales = system.availableLocales()+        assertTrue(locales.isNotEmpty(), "system asset locales should be listed")+        assertTrue(locales.all { it.language.isNotEmpty() })+        assertEquals(locales.distinctBy { it.toLanguageTag() }.size, locales.size)+        // Hidden framework writes are unavailable under Robolectric and must degrade, not throw.+        system.setSystemLocale(Locale.GERMAN)+        assertNotNull(system.currentLocale())+    }++    @Test fun `sim and oem lock readings degrade to null and false without the services`() {+        val system = SystemSetup(app)+        // No OemLockManager service is registered in Robolectric, so every OEM read is the+        // documented fallback rather than an exception.+        assertFalse(system.isDeviceOemUnlocked())+        assertFalse(system.isOemUnlockAllowedByUser())+        system.setOemUnlockAllowedByUser(false)+        system.setOemUnlockAllowedByUser(true)+        // Telephony is present but the hidden SIM-locale method is not: null, not a crash.+        system.simLocale()+    }++    @Test fun `status bar and bootloader reboot calls never throw`() {+        val system = SystemSetup(app)+        system.setStatusBarHiddenForSetup(true)+        system.setStatusBarHiddenForSetup(false)+        // ShadowPowerManager records reboot instead of rebooting the test process.+        system.rebootToBootloader()+    }++    @Test fun `location wifi and lock readings mirror shadow state`() {+        val system = SystemSetup(app)+        val locationManager = ctx.getSystemService(android.location.LocationManager::class.java)+        val shadowLocation = Shadows.shadowOf(locationManager) as ShadowLocationManager+        shadowLocation.setLocationEnabled(true)+        assertTrue(system.isLocationEnabled())+        shadowLocation.setLocationEnabled(false)+        assertFalse(system.isLocationEnabled())+        // Hidden setters degrade without throwing either way.+        system.setLocationEnabled(true)+        system.setWifiScanningAlwaysAvailable(true)+        system.isWifiScanningAlwaysAvailable()++        val keyguard = ctx.getSystemService(android.app.KeyguardManager::class.java)+        val shadowKeyguard = Shadows.shadowOf(keyguard) as ShadowKeyguardManager+        shadowKeyguard.setIsDeviceSecure(true)+        assertTrue(system.isDeviceSecure())+        shadowKeyguard.setIsDeviceSecure(false)+        assertFalse(system.isDeviceSecure())+    }++    @Test fun `automatic time seeds and display mirroring seed only once`() {+        val system = SystemSetup(app)+        system.enableAutomaticTime()+        assertEquals(1, Settings.Global.getInt(ctx.contentResolver, Settings.Global.AUTO_TIME, 0))+        assertEquals(1, Settings.Global.getInt(ctx.contentResolver, Settings.Global.AUTO_TIME_ZONE, 0))++        Settings.Secure.putString(ctx.contentResolver, "mirror_built_in_display", null)+        system.seedDisplayMirroring()+        assertEquals(1, Settings.Secure.getInt(ctx.contentResolver, "mirror_built_in_display", 0))+        // A deliberate user choice (0) must never be overwritten by a later setup launch.+        Settings.Secure.putInt(ctx.contentResolver, "mirror_built_in_display", 0)+        system.seedDisplayMirroring()+        assertEquals(0, Settings.Secure.getInt(ctx.contentResolver, "mirror_built_in_display", 1))+    }++    @Test fun `emergency dialer intent and setup-complete lifecycle`() {+        val system = SystemSetup(app)+        val intent = system.emergencyDialerIntent()+        assertNotNull(intent.action)++        Settings.Secure.putInt(ctx.contentResolver, "user_setup_complete", 0)+        assertFalse(system.isUserSetupComplete())+        val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+        system.markSetupComplete(activity)+        assertTrue(system.isUserSetupComplete())+        system.finishAllTasks(activity)++        system.disableSelf()+        val state = ctx.packageManager.getApplicationEnabledSetting(ctx.packageName)+        assertEquals(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, state)+        // Restore for other tests sharing this Robolectric sandbox.+        ctx.packageManager.setApplicationEnabledSetting(+            ctx.packageName,+            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,+            PackageManager.DONT_KILL_APP,+        )+        assertNotNull(ComponentName(ctx, MainActivityShim::class.java))+    }+}++/** Local reference so the lifecycle test anchors on a real component name. */+private class MainActivityShim