updater: add tests for download, install, worker, service and UI
- Commit
fcab1d79646cbbdd89fd85369c03c64430d75b4a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 06:53 UTC (29 days ago)
- Parents
b3cc053
Coverage (merged, instructions): 14.0% (911/6489) -> 90.5% (6037/6667). 151 unit tests pass (was 6 domain test files). New tests drive the whole pipeline off-device: OtaDownloader over a fake HttpsURLConnection (incremental-first, full fallback, resume via 206/416, range-ignored restart, early EOF, failed-incremental skip, discard), OtaInstaller through crafted OTA zips (signature gate, device/property rejection, care-map staging, engine completion codes, cancellation), SystemBuild/UpdateChecker over hidden SystemProperties, UpdateCheckWorker via TestListenableWorkerBuilder (pending-reboot skip, retry, hold-vs-proceed), UpdateInstallService end-to-end to the pending-reboot marker, UpdaterViewModel state transitions, Compose UpdaterScreen states and toggles, notifications, receivers, navigation and Route serialization. Production changes are test seams only, each defaulting to the real behavior: OtaDownloader/UpdateChecker connection and staged-file overrides, OtaInstaller signature/care-map/payload-engine overrides (the payload engine is now behind a small internal interface so tests can drive the completion callback), and UpdateInstallService asking OtaDownloader for the staged file. A work-testing test dependency is added. Untestable remainder: the real UpdateEngine bind/callback (no update_engine service under Robolectric), RecoverySystem verification success, and the API-36 Live Update notification style (tests run on SDK 34). Verified: :updater:createMergedCoverageReport, :updater:lint and ./check updater all pass. (cherry picked from commit 8184b5524cd73f12d87f3e3f5041c05f8f57b2b9)
Diff
updater/build.gradle.kts
diff --git a/updater/build.gradle.kts b/updater/build.gradle.ktsindex b65bd31953..0298767830 100644--- a/updater/build.gradle.kts+++ b/updater/build.gradle.kts@@ -23,4 +23,6 @@ dependencies { // A/B slot writer. Present at runtime on a MAOS image because this app is privileged; // absent from the public SDK, and must NOT be packaged. See :library:aosp-stubs. compileOnly(project(":library:aosp-stubs"))++ testImplementation(libs.androidx.work.testing) }
updater/src/main/java/com/vayunmathur/updater/platform/OtaDownloader.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/OtaDownloader.kt b/updater/src/main/java/com/vayunmathur/updater/platform/OtaDownloader.ktindex 998666fe86..5203d69a3d 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/OtaDownloader.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/OtaDownloader.kt@@ -51,6 +51,14 @@ object OtaDownloader { /** Where update_engine can reach it. See the class doc. */ val UPDATE_PATH = File("/data/ota_package/update.zip") + /** Test seam: replaces the staged-package file (unwritable off-device). Null means [UPDATE_PATH]. */+ internal var updateFileOverride: File? = null++ /** Test seam: replaces opening the HTTPS connection. Null means the real [URL] connection. */+ internal var connectionOverride: ((url: String, offset: Long) -> HttpsURLConnection)? = null++ internal fun updateFile(): File = updateFileOverride ?: UPDATE_PATH+ sealed interface Result { data class Downloaded(val incremental: Boolean) : Result @@ -84,11 +92,11 @@ object OtaDownloader { val incremental = artifacts.incremental.takeIf { it != null && it != failedIncremental } try {- UPDATE_PATH.parentFile?.mkdirs()+ updateFile().parentFile?.mkdirs() val remembered = store.getStringAwait(UpdaterPreferences.DOWNLOAD_FILE) // Only a partial file whose artifact we can still name is worth resuming. val target = resolveTarget(remembered, incremental, artifacts.full)- if (!target.resumable) UPDATE_PATH.delete()+ if (!target.resumable) updateFile().delete() return@withContext when (val request = requestArtifact(artifacts, target)) { is ArtifactRequest.Complete -> Result.Downloaded(request.wanted == artifacts.incremental)@@ -132,7 +140,7 @@ object OtaDownloader { ): DownloadTarget { val resumable = remembered != null && (remembered == incremental || remembered == full) val wanted = if (resumable) remembered!! else incremental ?: full- val offset = if (resumable) UPDATE_PATH.length() else 0L+ val offset = if (resumable) updateFile().length() else 0L return DownloadTarget(wanted, offset, resumable) } @@ -193,7 +201,7 @@ object OtaDownloader { connection.errorStream?.close() connection.disconnect() Log.status(TAG, "${target.wanted} is not published; falling back to ${artifacts.full}")- UPDATE_PATH.delete()+ updateFile().delete() val retry = open(artifacts.full, 0L) val retryCode = retry.responseCode if (retryCode == HttpURLConnection.HTTP_NOT_FOUND) {@@ -206,12 +214,13 @@ object OtaDownloader { /** Forget the staged package entirely, so the next run starts clean rather than resuming. */ suspend fun discard(context: Context) {- UPDATE_PATH.delete()+ updateFile().delete() DataStoreUtils.getInstance(context).setString(UpdaterPreferences.DOWNLOAD_FILE, "") } private fun open(fileName: String, offset: Long): HttpsURLConnection { val url = "${SystemBuild.otaServer()}/$fileName"+ connectionOverride?.let { return it(url, offset) } // HTTPS only. The signature check is the real boundary, but there is no reason to let a // gigabyte of anything arrive over a connection nobody authenticated. val connection = URL(url).openConnection() as HttpsURLConnection@@ -284,7 +293,7 @@ object OtaDownloader { var lastReport = 0L onProgress(soFar, total) - FileOutputStream(UPDATE_PATH, append).use { output ->+ FileOutputStream(updateFile(), append).use { output -> connection.inputStream.use { input -> val buffer = ByteArray(BUFFER_SIZE) while (true) {@@ -326,7 +335,7 @@ object OtaDownloader { private fun allocate(context: Context, bytes: Long) { runCatching { val storage = context.getSystemService<StorageManager>() ?: return- val uuid = storage.getUuidForPath(UPDATE_PATH)+ val uuid = storage.getUuidForPath(updateFile()) val flag = StorageManager::class.java .getField("FLAG_ALLOCATE_AGGRESSIVE") .getInt(null)
updater/src/main/java/com/vayunmathur/updater/platform/OtaInstaller.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/OtaInstaller.kt b/updater/src/main/java/com/vayunmathur/updater/platform/OtaInstaller.ktindex e85d4dd9df..fa9d60d41b 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/OtaInstaller.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/OtaInstaller.kt@@ -44,6 +44,43 @@ private val CARE_MAP_PATH = File("/data/ota_package/care_map.pb") */ object OtaInstaller { + /** Test seam: replaces `RecoverySystem.verifyPackage`. True means verified. Null means real. */+ internal var signatureCheckOverride: ((File, (Int) -> Unit) -> Boolean)? = null++ /** Test seam: replaces staging the care map at its on-device path. Null means the real path. */+ internal var careMapPathOverride: File? = null++ /** The payload-engine surface [install] needs, so tests can drive the completion callback. */+ internal interface PayloadEngine {+ fun bind(+ onStatusUpdate: (status: Int, percent: Float) -> Unit,+ onPayloadApplicationComplete: (errorCode: Int) -> Unit,+ ): Boolean+ fun applyPayload(url: String, offset: Long, headers: Array<String>)+ fun cancel()+ fun unbind(): Boolean+ }++ /** Test seam: replaces constructing the real `UpdateEngine`. Null means the real engine. */+ internal var payloadEngineOverride: (() -> PayloadEngine)? = null++ private class RealPayloadEngine : PayloadEngine {+ private val engine = UpdateEngine()+ override fun bind(+ onStatusUpdate: (Int, Float) -> Unit,+ onPayloadApplicationComplete: (Int) -> Unit,+ ): Boolean = engine.bind(object : UpdateEngineCallback() {+ override fun onStatusUpdate(status: Int, percent: Float) =+ onStatusUpdate(status, percent)+ override fun onPayloadApplicationComplete(errorCode: Int) =+ onPayloadApplicationComplete(errorCode)+ })+ override fun applyPayload(url: String, offset: Long, headers: Array<String>) =+ engine.applyPayload(url, offset, 0L, headers)+ override fun cancel() = engine.cancel()+ override fun unbind(): Boolean = engine.unbind()+ }+ sealed interface Result { /** Written to the inactive slot. A reboot will boot into it. */ data object Applied : Result@@ -107,6 +144,14 @@ object OtaInstaller { packageFile: File, onProgress: (percent: Int) -> Unit, ): Result.Failed? = withContext(Dispatchers.IO) {+ signatureCheckOverride?.let { check ->+ return@withContext if (check(packageFile, onProgress)) {+ null+ } else {+ packageFile.delete()+ Result.Failed("the update package failed signature verification")+ }+ } try { RecoverySystem.verifyPackage( packageFile,@@ -182,9 +227,9 @@ object OtaInstaller { return } zip.getInputStream(entry).use { input ->- CARE_MAP_PATH.outputStream().use { output -> input.copyTo(output) }+ (careMapPathOverride ?: CARE_MAP_PATH).outputStream().use { output -> input.copyTo(output) } }- CARE_MAP_PATH.setReadable(true, false)+ (careMapPathOverride ?: CARE_MAP_PATH).setReadable(true, false) } }.onFailure { Log.status(TAG, "could not stage the care map; continuing without it", it) } }@@ -212,7 +257,7 @@ object OtaInstaller { onProgress: (percent: Int) -> Unit, ): Result { val engine = try {- UpdateEngine()+ payloadEngineOverride?.invoke() ?: RealPayloadEngine() } catch (e: Exception) { // The constructor binds to the update_engine binder and throws when it is // unavailable - which is what a non-privileged build looks like from here.@@ -233,44 +278,41 @@ object OtaInstaller { } private suspend fun awaitPayload(- engine: UpdateEngine,+ engine: PayloadEngine, packageFile: File, payloadOffset: Long, headers: List<String>, onProgress: (percent: Int) -> Unit, ): Result = suspendCancellableCoroutine { continuation -> - val callback = object : UpdateEngineCallback() {- override fun onStatusUpdate(status: Int, percent: Float) {- // percent is 0..1 here, not 0..100.- onProgress((percent * 100).toInt().coerceIn(0, 100))- }-- override fun onPayloadApplicationComplete(errorCode: Int) {- continuation.finish(- when (val outcome = UpdateEngineOutcome.of(errorCode)) {- UpdateEngineOutcome.Outcome.Applied -> {- // Whatever happened, the 1-2 GB staged package has served its- // purpose and must not be left behind or resumed from.- packageFile.delete()- Result.Applied- }+ // percent is 0..1 here, not 0..100.+ val onStatusUpdate: (Int, Float) -> Unit = { _, percent ->+ onProgress((percent * 100).toInt().coerceIn(0, 100))+ }+ val onComplete: (Int) -> Unit = { errorCode ->+ continuation.finish(+ when (val outcome = UpdateEngineOutcome.of(errorCode)) {+ UpdateEngineOutcome.Outcome.Applied -> {+ // Whatever happened, the 1-2 GB staged package has served its+ // purpose and must not be left behind or resumed from.+ packageFile.delete()+ Result.Applied+ } - is UpdateEngineOutcome.Outcome.Failed -> {- Log.error(TAG, "apply failed: ${outcome.reason} (${outcome.code})")- packageFile.delete()- Result.Failed(- outcome.reason,- outcome.retryable,- outcome.initializationFailure,- )- }- },- )- }+ is UpdateEngineOutcome.Outcome.Failed -> {+ Log.error(TAG, "apply failed: ${outcome.reason} (${outcome.code})")+ packageFile.delete()+ Result.Failed(+ outcome.reason,+ outcome.retryable,+ outcome.initializationFailure,+ )+ }+ },+ ) } - if (!engine.bind(callback)) {+ if (!engine.bind(onStatusUpdate, onComplete)) { continuation.resume(Result.Failed("could not attach to the system update service")) return@suspendCancellableCoroutine }@@ -286,9 +328,6 @@ object OtaInstaller { engine.applyPayload( "file://${packageFile.absolutePath}", payloadOffset,- // 0 means "to the end of the file". The payload runs to the end of the zip- // entry and update_engine reads its real length out of the metadata headers.- 0L, headers.toTypedArray(), ) } catch (e: Exception) {
updater/src/main/java/com/vayunmathur/updater/platform/UpdateChecker.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/platform/UpdateChecker.kt b/updater/src/main/java/com/vayunmathur/updater/platform/UpdateChecker.ktindex aa271b43a5..bc8b123d93 100644--- a/updater/src/main/java/com/vayunmathur/updater/platform/UpdateChecker.kt+++ b/updater/src/main/java/com/vayunmathur/updater/platform/UpdateChecker.kt@@ -23,6 +23,9 @@ object UpdateChecker { private const val CHANNEL = "stable" + /** Test seam: replaces opening the HTTPS connection. Null means the real [URL] connection. */+ internal var connectionOverride: ((url: String) -> HttpsURLConnection)? = null+ /** The result of one check. Every failure is a value, not an exception. */ sealed interface Result { /** A build newer than the running one is available. */@@ -63,7 +66,8 @@ object UpdateChecker { * this device yet. */ private fun fetch(url: String): String? = runCatching {- val connection = URL(url).openConnection() as? HttpsURLConnection+ val connection = connectionOverride?.invoke(url)+ ?: URL(url).openConnection() as? HttpsURLConnection ?: run { Log.status(TAG, "refusing a non-HTTPS OTA URL") return null
updater/src/main/java/com/vayunmathur/updater/service/UpdateInstallService.kt
diff --git a/updater/src/main/java/com/vayunmathur/updater/service/UpdateInstallService.kt b/updater/src/main/java/com/vayunmathur/updater/service/UpdateInstallService.ktindex 3f10dbff23..e9fae74eb8 100644--- a/updater/src/main/java/com/vayunmathur/updater/service/UpdateInstallService.kt+++ b/updater/src/main/java/com/vayunmathur/updater/service/UpdateInstallService.kt@@ -166,7 +166,7 @@ class UpdateInstallService : Service() { ) { UpdateNotifications.updateProgress(this, getString(R.string.notify_verifying), 0) val result = OtaInstaller.install(- packageFile = OtaDownloader.UPDATE_PATH,+ packageFile = OtaDownloader.updateFile(), expected = OtaPackageValidation.Expected( buildDateUtcSeconds = buildDate, targetBuild = build,
updater/src/test/java/com/vayunmathur/updater/MainActivityNavigationTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/MainActivityNavigationTest.kt b/updater/src/test/java/com/vayunmathur/updater/MainActivityNavigationTest.ktnew file mode 100644index 0000000000..5a62e5a165--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/MainActivityNavigationTest.kt@@ -0,0 +1,56 @@+package com.vayunmathur.updater++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createAndroidComposeRule+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.updater.platform.TestSysProps+import com.vayunmathur.updater.platform.UpdaterViewModel+import kotlin.test.Test+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import androidx.test.core.app.ApplicationProvider+import android.app.Application++@RunWith(RobolectricTestRunner::class)+class MainActivityNavigationTest {++ @get:Rule+ val composeRule = createComposeRule()++ @Test+ fun `navigation hosts the updater screen for the home route`() {+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ val app = ApplicationProvider.getApplicationContext<Application>()+ val viewModel = UpdaterViewModel(app)+ composeRule.setContent {+ DynamicTheme { Navigation(viewModel) }+ }+ composeRule.onNodeWithText("Check now").assertIsDisplayed()+ composeRule.onNodeWithText("Install updates automatically").assertIsDisplayed()+ }+}++@RunWith(RobolectricTestRunner::class)+class MainActivityTest {++ @Test+ fun `the activity launches, schedules checks and renders the home route`() {+ runCatching {+ androidx.work.testing.WorkManagerTestInitHelper.initializeTestWorkManager(+ ApplicationProvider.getApplicationContext(),+ )+ }+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ val controller = org.robolectric.Robolectric.buildActivity(MainActivity::class.java)+ val activity = controller.create().start().resume().visible().get()+ org.robolectric.shadows.ShadowLooper.idleMainLooper()+ kotlin.test.assertNotNull(activity)+ kotlin.test.assertFalse(activity.isFinishing)+ controller.pause().stop().destroy()+ }+}
updater/src/test/java/com/vayunmathur/updater/RouteSerializationTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/RouteSerializationTest.kt b/updater/src/test/java/com/vayunmathur/updater/RouteSerializationTest.ktnew file mode 100644index 0000000000..2d6511f85e--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/RouteSerializationTest.kt@@ -0,0 +1,16 @@+package com.vayunmathur.updater++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.serialization.json.Json++class RouteSerializationTest {++ @Test+ fun `the home route round-trips through its nav-key serializer`() {+ val encoded = Json.encodeToString(Route.serializer(), Route.Home)+ val decoded = Json.decodeFromString(Route.serializer(), encoded)+ assertEquals(Route.Home, decoded)+ assertEquals(Route.Home, Json.decodeFromString(Route.Home.serializer(), Json.encodeToString(Route.Home.serializer(), Route.Home)))+ }+}
updater/src/test/java/com/vayunmathur/updater/domain/OtaArtifactsComparisonTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/domain/OtaArtifactsComparisonTest.kt b/updater/src/test/java/com/vayunmathur/updater/domain/OtaArtifactsComparisonTest.ktnew file mode 100644index 0000000000..f8833ceecd--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/domain/OtaArtifactsComparisonTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.updater.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++class OtaArtifactsComparisonTest {++ @Test+ fun `streaming and plain artifact names differ only by the suffix`() {+ assertEquals(+ "shiba-incremental-2026090500-2026090700.zip",+ OtaArtifacts.incremental("shiba", "2026090500", "2026090700", streaming = false),+ )+ assertEquals(+ "shiba-streaming-incremental-2026090500-2026090700.zip",+ OtaArtifacts.incremental("shiba", "2026090500", "2026090700", streaming = true),+ )+ assertEquals(+ "shiba-ota_update-2026090700.zip",+ OtaArtifacts.full("shiba", "2026090700", streaming = false),+ )+ assertEquals(+ "shiba-streaming-ota_update-2026090700.zip",+ OtaArtifacts.full("shiba", "2026090700", streaming = true),+ )+ }++ @Test+ fun `only a strictly newer build date is an update`() {+ val current = UpdateComparison.CurrentBuild("2026090500", 1000L)+ assertTrue(UpdateComparison.isNewer(current, UpdateMetadata("2026090700", 1001L)))+ assertFalse(UpdateComparison.isNewer(current, UpdateMetadata("2026090700", 1000L)))+ assertFalse(UpdateComparison.isNewer(current, UpdateMetadata("2026090700", 999L)))+ }++ @Test+ fun `payload offset skips malformed and unrelated entries`() {+ val metadata = OtaPackageMetadata(+ postTimestamp = null, postBuildIncremental = null, preDevice = null, serialNo = null,+ otaType = null, preBuildIncremental = null, preBuildFingerprint = null,+ streamingPropertyFiles = listOf("payload_properties.txt:5:60", "payload.bin:notanumber:20", "payload.bin"),+ )+ assertNull(metadata.payloadOffset())+ }++ @Test+ fun `payload offset uses the first payload_bin entry that parses`() {+ val metadata = OtaPackageMetadata(+ postTimestamp = null, postBuildIncremental = null, preDevice = null, serialNo = null,+ otaType = null, preBuildIncremental = null, preBuildFingerprint = null,+ streamingPropertyFiles = listOf("payload.bin:oops:20", "payload.bin:4096:99"),+ )+ assertEquals(4096L, metadata.payloadOffset())+ }++ @Test+ fun `metadata parse tolerates a non numeric timestamp and trims streaming entries`() {+ val parsed = OtaPackageMetadata.parse(+ sequenceOf(+ "post-timestamp=not-a-number",+ "ota-streaming-property-files= payload.bin:7:8 , payload_properties.txt:1:2 ",+ "serialno=",+ ),+ )+ assertNull(parsed.postTimestamp)+ assertEquals("", parsed.serialNo)+ assertEquals(listOf("payload.bin:7:8", "payload_properties.txt:1:2"), parsed.streamingPropertyFiles)+ assertEquals(7L, parsed.payloadOffset())+ }+}
updater/src/test/java/com/vayunmathur/updater/notifications/UpdateNotificationsTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/notifications/UpdateNotificationsTest.kt b/updater/src/test/java/com/vayunmathur/updater/notifications/UpdateNotificationsTest.ktnew file mode 100644index 0000000000..20f61a59b8--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/notifications/UpdateNotificationsTest.kt@@ -0,0 +1,105 @@+package com.vayunmathur.updater.notifications++import android.app.Notification+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+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.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class UpdateNotificationsTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val manager get() = ctx.getSystemService(NotificationManager::class.java)++ private fun posted() = manager.activeNotifications.toList()++ @Test+ fun `ensure channels creates the progress and result channels`() {+ UpdateNotifications.ensureChannels(ctx)+ assertNotNull(manager.getNotificationChannel(UpdateNotifications.CHANNEL_PROGRESS))+ assertEquals(+ NotificationManager.IMPORTANCE_LOW,+ manager.getNotificationChannel(UpdateNotifications.CHANNEL_PROGRESS).importance,+ )+ assertNotNull(manager.getNotificationChannel("updater_result"))+ }++ @Test+ fun `progress below zero is indeterminate and at zero or above is determinate`() {+ val indeterminate = UpdateNotifications.progress(ctx, "Preparing", -1)+ assertTrue(indeterminate.extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE))+ assertTrue(indeterminate.flags and Notification.FLAG_ONGOING_EVENT != 0)++ val half = UpdateNotifications.progress(ctx, "Downloading", 50)+ // The compat style (legacy branch below API 36) reports progress through the extras.+ val progress = half.extras.getInt(Notification.EXTRA_PROGRESS)+ val max = half.extras.getInt(Notification.EXTRA_PROGRESS_MAX)+ if (max > 0) assertEquals(50, progress)+ assertFalse(half.extras.getBoolean(Notification.EXTRA_PROGRESS_INDETERMINATE))+ assertEquals("Downloading", half.extras.getCharSequence(Notification.EXTRA_TITLE)?.toString())+ }++ @Test+ fun `progress is clamped to the notification scale`() {+ val over = UpdateNotifications.progress(ctx, "Installing", 250)+ val max = over.extras.getInt(Notification.EXTRA_PROGRESS_MAX)+ if (max > 0) assertEquals(max, over.extras.getInt(Notification.EXTRA_PROGRESS))+ }++ @Test+ fun `update progress posts under the shared progress id`() {+ UpdateNotifications.ensureChannels(ctx)+ UpdateNotifications.updateProgress(ctx, "Downloading", 10)+ UpdateNotifications.updateProgress(ctx, "Verifying", 90)+ val posted = posted().filter { it.id == UpdateNotifications.ID_PROGRESS }+ assertEquals(1, posted.size, "progress updates replace, not stack")+ }++ @Test+ fun `reboot pending posts a result with a restart action`() {+ UpdateNotifications.ensureChannels(ctx)+ val restart = PendingIntent.getBroadcast(+ ctx, 0, Intent("test.restart"), PendingIntent.FLAG_IMMUTABLE,+ )+ UpdateNotifications.rebootPending(ctx, "2026090700", restart)+ val posted = posted().single { it.id == 2 }+ val notification = posted.notification+ assertTrue(+ notification.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()?.contains("2026090700") == true,+ notification.extras.toString(),+ )+ assertNotNull(notification.actions?.singleOrNull())+ assertFalse(notification.flags and Notification.FLAG_AUTO_CANCEL != 0)+ }++ @Test+ fun `update available and failed post results, and clear removes them`() {+ UpdateNotifications.ensureChannels(ctx)+ UpdateNotifications.updateAvailable(ctx, "2026090700")+ var notification = posted().single { it.id == 2 }.notification+ assertTrue(+ notification.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString()?.contains("2026090700") == true,+ )+ assertTrue(notification.flags and Notification.FLAG_AUTO_CANCEL != 0)++ UpdateNotifications.failed(ctx, "the payload transfer failed")+ notification = posted().single { it.id == 2 }.notification+ assertEquals(+ "the payload transfer failed",+ notification.extras.getCharSequence(Notification.EXTRA_TEXT)?.toString(),+ )++ UpdateNotifications.clearResult(ctx)+ assertTrue(posted().none { it.id == 2 })+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/FakeHttpsConnection.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/FakeHttpsConnection.kt b/updater/src/test/java/com/vayunmathur/updater/platform/FakeHttpsConnection.ktnew file mode 100644index 0000000000..08119cdcd4--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/FakeHttpsConnection.kt@@ -0,0 +1,64 @@+package com.vayunmathur.updater.platform++import java.io.ByteArrayInputStream+import java.io.IOException+import java.io.InputStream+import java.net.URL+import java.security.Principal+import java.security.cert.Certificate+import javax.net.ssl.HttpsURLConnection++/** An in-memory [HttpsURLConnection] so download/check tests never touch the network. */+class FakeHttpsConnection(+ url: URL,+ private val code: Int,+ private val body: ByteArray = ByteArray(0),+ private val declaredLength: Long = body.size.toLong(),+ private val failOnInput: Boolean = false,+) : HttpsURLConnection(url) {++ var disconnected: Boolean = false+ private set++ override fun getResponseCode(): Int = code++ override fun getInputStream(): InputStream {+ if (failOnInput) throw IOException("fake input failure")+ return ByteArrayInputStream(body)+ }++ override fun getErrorStream(): InputStream = ByteArrayInputStream(ByteArray(0))++ override fun getContentLengthLong(): Long = declaredLength++ override fun connect() = Unit++ override fun disconnect() {+ disconnected = true+ }++ override fun usingProxy(): Boolean = false++ override fun getCipherSuite(): String = "TLS_FAKE_SUITE"++ override fun getLocalCertificates(): Array<Certificate> = emptyArray()++ override fun getServerCertificates(): Array<Certificate> = emptyArray()++ override fun getPeerPrincipal(): Principal = Principal { "fake-peer" }+}++/** Sets a hidden `android.os.SystemProperties` value the way a real build would report it. */+object TestSysProps {+ fun set(key: String, value: String) {+ val cls = Class.forName("android.os.SystemProperties")+ cls.getMethod("set", String::class.java, String::class.java).invoke(null, key, value)+ }++ fun setRunningBuild(build: String = "2026090500", dateUtcSeconds: Long = 1000L, device: String = "shiba") {+ set("ro.build.version.incremental", build)+ set("ro.build.date.utc", dateUtcSeconds.toString())+ set("ro.product.device", device)+ set("ro.build.fingerprint", "Modern/$device/$device:16/$build/user/release-keys")+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/OtaDownloaderTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/OtaDownloaderTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/OtaDownloaderTest.ktnew file mode 100644index 0000000000..49d799cc4e--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/OtaDownloaderTest.kt@@ -0,0 +1,193 @@+package com.vayunmathur.updater.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.net.URL+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class OtaDownloaderTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val store get() = DataStoreUtils.getInstance(ctx)++ private lateinit var file: File+ private val requested = mutableListOf<String>()+ private val responses = ArrayDeque<(String) -> FakeHttpsConnection>()++ @BeforeTest+ fun setUp() = runBlocking {+ file = File(ctx.cacheDir, "update-${System.nanoTime()}.zip")+ OtaDownloader.updateFileOverride = file+ OtaDownloader.connectionOverride = { url, _ ->+ val name = url.substringAfterLast('/')+ requested += name+ responses.removeFirst()(name)+ }+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "")+ store.setString(UpdaterPreferences.FAILED_INCREMENTAL, "")+ Unit+ }++ @AfterTest+ fun tearDown() {+ OtaDownloader.updateFileOverride = null+ OtaDownloader.connectionOverride = null+ file.delete()+ }++ private fun respond(code: Int, body: String = "", declaredLength: Long = body.toByteArray().size.toLong()) {+ responses.add { FakeHttpsConnection(URL("https://ota.example/$it"), code, body.toByteArray(), declaredLength) }+ }++ private fun download(current: String = "2026090500", target: String = "2026090700", progress: MutableList<Pair<Long, Long>>? = null) =+ runBlocking {+ OtaDownloader.download(ctx, "shiba", current, target) { bytes, total -> progress?.add(bytes to total) }+ }++ @Test+ fun `downloads the incremental first and records what the file is`() {+ respond(200, "incremental-bytes")+ val progress = mutableListOf<Pair<Long, Long>>()+ val result = download(progress = progress)+ assertEquals(OtaDownloader.Result.Downloaded(incremental = true), result)+ assertEquals("incremental-bytes", file.readText())+ assertEquals(listOf("shiba-incremental-2026090500-2026090700.zip"), requested)+ assertEquals(17L to 17L, progress.last())+ runBlocking {+ assertEquals(+ "shiba-incremental-2026090500-2026090700.zip",+ store.getStringAwait(UpdaterPreferences.DOWNLOAD_FILE),+ )+ }+ }++ @Test+ fun `falls back to the full package when no incremental is published`() {+ respond(404)+ respond(200, "full-bytes")+ val result = download()+ assertEquals(OtaDownloader.Result.Downloaded(incremental = false), result)+ assertEquals("full-bytes", file.readText())+ assertEquals(+ listOf("shiba-incremental-2026090500-2026090700.zip", "shiba-ota_update-2026090700.zip"),+ requested,+ )+ }++ @Test+ fun `reports not found when neither artifact is published`() {+ respond(404)+ respond(404)+ assertEquals(OtaDownloader.Result.NotFound, download())+ // And when the current build is unknown there is only the full package to miss.+ requested.clear()+ respond(404)+ assertEquals(OtaDownloader.Result.NotFound, download(current = ""))+ assertEquals(listOf("shiba-ota_update-2026090700.zip"), requested)+ }++ @Test+ fun `skips an incremental update_engine already refused`() = runBlocking {+ store.setString(+ UpdaterPreferences.FAILED_INCREMENTAL,+ "shiba-incremental-2026090500-2026090700.zip",+ )+ respond(200, "full-bytes")+ assertEquals(OtaDownloader.Result.Downloaded(incremental = false), download())+ assertEquals(listOf("shiba-ota_update-2026090700.zip"), requested)+ }++ @Test+ fun `a resumed download the server calls complete is not streamed again`() = runBlocking {+ file.writeText("already-here")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "shiba-ota_update-2026090700.zip")+ respond(416)+ val result = download()+ assertEquals(OtaDownloader.Result.Downloaded(incremental = false), result)+ assertEquals("already-here", file.readText())+ }++ @Test+ fun `resumes a partial full package with a ranged partial response`() = runBlocking {+ file.writeText("alp")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "shiba-ota_update-2026090700.zip")+ respond(206, "ha", declaredLength = 2L)+ val progress = mutableListOf<Pair<Long, Long>>()+ val result = download(progress = progress)+ assertEquals(OtaDownloader.Result.Downloaded(incremental = false), result)+ assertEquals("alpha", file.readText())+ assertEquals(5L to 5L, progress.last())+ }++ @Test+ fun `restarts from scratch when the server ignores the range`() = runBlocking {+ file.writeText("stale-partial")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "shiba-ota_update-2026090700.zip")+ respond(200, "fresh-full-body")+ assertEquals(OtaDownloader.Result.Downloaded(incremental = false), download())+ assertEquals("fresh-full-body", file.readText())+ }++ @Test+ fun `a partial file from a different artifact is discarded, not resumed`() = runBlocking {+ file.writeText("other-artifact-bytes")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "shiba-incremental-2026010100-2026090700.zip")+ respond(200, "inc")+ assertEquals(OtaDownloader.Result.Downloaded(incremental = true), download())+ assertEquals("inc", file.readText())+ }++ @Test+ fun `an unexpected HTTP status fails with the status in the reason`() {+ respond(500, "boom")+ val result = download()+ val failed = assertIs<OtaDownloader.Result.Failed>(result)+ assertTrue(failed.reason.contains("500"), failed.reason)+ }++ @Test+ fun `a body that ends before its declared length fails`() {+ respond(200, "short", declaredLength = 100L)+ val result = download()+ val failed = assertIs<OtaDownloader.Result.Failed>(result)+ assertTrue(failed.reason.contains("ended early"), failed.reason)+ }++ @Test+ fun `a body with no declared length downloads to its end`() {+ respond(200, "unbounded", declaredLength = -1L)+ assertEquals(OtaDownloader.Result.Downloaded(incremental = true), download())+ assertEquals("unbounded", file.readText())+ }++ @Test+ fun `a connection failure is a failed result, not a throw`() {+ responses.add {+ FakeHttpsConnection(URL("https://ota.example/$it"), 200, failOnInput = true)+ }+ val result = download()+ val failed = assertIs<OtaDownloader.Result.Failed>(result)+ assertTrue(failed.reason.contains("could not be downloaded"), failed.reason)+ }++ @Test+ fun `discard deletes the staged file and forgets its name`() = runBlocking {+ file.writeText("staged")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "shiba-ota_update-2026090700.zip")+ OtaDownloader.discard(ctx)+ assertFalse(file.exists())+ assertEquals("", store.getStringAwait(UpdaterPreferences.DOWNLOAD_FILE))+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/OtaInstallerTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/OtaInstallerTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/OtaInstallerTest.ktnew file mode 100644index 0000000000..e75d03ec7d--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/OtaInstallerTest.kt@@ -0,0 +1,321 @@+package com.vayunmathur.updater.platform++import com.vayunmathur.updater.domain.OtaPackageValidation+import java.io.File+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertIs+import kotlin.test.assertTrue+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import androidx.test.core.app.ApplicationProvider+import android.content.Context++@RunWith(RobolectricTestRunner::class)+class OtaInstallerTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ private val expected = OtaPackageValidation.Expected(+ buildDateUtcSeconds = 100L,+ targetBuild = "2026090700",+ device = "shiba",+ currentBuild = "2026090500",+ currentFingerprint = "Modern/shiba/shiba:16/2026090500/user/release-keys",+ )++ private class FakeEngine(+ var bindResult: Boolean = true,+ var completionCode: Int = 0,+ var applyThrows: Boolean = false,+ var unbindResult: Boolean = true,+ var neverCompletes: Boolean = false,+ ) : OtaInstaller.PayloadEngine {+ var onComplete: ((Int) -> Unit)? = null+ var onStatus: ((Int, Float) -> Unit)? = null+ var appliedUrl: String? = null+ var appliedOffset: Long = -1L+ var appliedHeaders: List<String> = emptyList()+ var cancelled: Boolean = false+ var unbound: Boolean = false++ override fun bind(+ onStatusUpdate: (Int, Float) -> Unit,+ onPayloadApplicationComplete: (Int) -> Unit,+ ): Boolean {+ onStatus = onStatusUpdate+ onComplete = onPayloadApplicationComplete+ return bindResult+ }++ override fun applyPayload(url: String, offset: Long, headers: Array<String>) {+ if (applyThrows) throw IllegalStateException("engine refused")+ appliedUrl = url+ appliedOffset = offset+ appliedHeaders = headers.toList()+ if (neverCompletes) return+ onStatus?.invoke(3, 0.5f)+ onComplete?.invoke(completionCode)+ }++ override fun cancel() {+ cancelled = true+ }++ override fun unbind(): Boolean {+ unbound = true+ return unbindResult+ }+ }++ private lateinit var careMap: File++ @BeforeTest+ fun setUp() {+ careMap = File(ctx.cacheDir, "care_map-${System.nanoTime()}.pb")+ OtaInstaller.careMapPathOverride = careMap+ OtaInstaller.signatureCheckOverride = { _, onProgress -> onProgress(42); true }+ }++ @AfterTest+ fun tearDown() {+ OtaInstaller.signatureCheckOverride = null+ OtaInstaller.payloadEngineOverride = null+ OtaInstaller.careMapPathOverride = null+ careMap.delete()+ }++ private fun zipFile(+ metadata: String = """+ post-timestamp=100+ post-build-incremental=2026090700+ pre-device=shiba+ ota-type=AB+ ota-streaming-property-files=payload.bin:1234:5678+ """.trimIndent(),+ properties: String? = "FILE_HASH=a\nFILE_SIZE=1\nMETADATA_HASH=b\nMETADATA_SIZE=2\n",+ includeMetadata: Boolean = true,+ includeProperties: Boolean = true,+ includeCareMap: Boolean = true,+ ): File {+ val file = File.createTempFile("ota", ".zip", ctx.cacheDir)+ ZipOutputStream(file.outputStream()).use { zip ->+ if (includeMetadata) {+ zip.putNextEntry(ZipEntry("META-INF/com/android/metadata"))+ zip.write(metadata.toByteArray()); zip.closeEntry()+ }+ if (includeProperties && properties != null) {+ zip.putNextEntry(ZipEntry("payload_properties.txt"))+ zip.write(properties.toByteArray()); zip.closeEntry()+ }+ if (includeCareMap) {+ zip.putNextEntry(ZipEntry("care_map.pb"))+ zip.write(byteArrayOf(9, 8, 7)); zip.closeEntry()+ }+ zip.putNextEntry(ZipEntry("payload.bin"))+ zip.write(ByteArray(32)); zip.closeEntry()+ }+ return file+ }++ private fun install(file: File, verify: MutableList<Int>? = null, apply: MutableList<Int>? = null) = runBlocking {+ OtaInstaller.install(file, expected, { verify?.add(it) }, { apply?.add(it) })+ }++ @Test+ fun `a verified valid package is applied and the staged file is removed`() {+ val engine = FakeEngine(completionCode = 0)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile()+ val verifyProgress = mutableListOf<Int>()+ val applyProgress = mutableListOf<Int>()+ val result = install(file, verifyProgress, applyProgress)+ assertEquals(OtaInstaller.Result.Applied, result)+ assertEquals(listOf(42), verifyProgress)+ assertEquals(listOf(50), applyProgress)+ assertFalse(file.exists(), "applied package must be deleted")+ assertTrue(engine.appliedUrl!!.endsWith(file.name), engine.appliedUrl)+ assertEquals(1234L, engine.appliedOffset)+ assertEquals(listOf("FILE_HASH=a", "FILE_SIZE=1", "METADATA_HASH=b", "METADATA_SIZE=2"), engine.appliedHeaders)+ assertTrue(engine.unbound)+ assertEquals(listOf<Byte>(9, 8, 7), careMap.readBytes().toList())+ }++ @Test+ fun `a failed signature check deletes the package and applies nothing`() {+ OtaInstaller.signatureCheckOverride = { _, _ -> false }+ var engineUsed = false+ OtaInstaller.payloadEngineOverride = { engineUsed = true; FakeEngine() }+ val file = zipFile()+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("signature verification"), failed.reason)+ assertFalse(file.exists())+ assertFalse(engineUsed)+ }++ @Test+ fun `the real signature check rejects an unsigned package under Robolectric`() {+ OtaInstaller.signatureCheckOverride = null+ val file = zipFile()+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("signature verification"), failed.reason)+ assertFalse(file.exists())+ }++ @Test+ fun `a package for another device is rejected after verification`() {+ OtaInstaller.payloadEngineOverride = { FakeEngine() }+ val file = zipFile(+ metadata = """+ post-timestamp=100+ post-build-incremental=2026090700+ pre-device=husky+ ota-type=AB+ ota-streaming-property-files=payload.bin:1234:5678+ """.trimIndent(),+ )+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("husky"), failed.reason)+ assertFalse(file.exists())+ }++ @Test+ fun `a package missing its payload properties is rejected`() {+ OtaInstaller.payloadEngineOverride = { FakeEngine() }+ val file = zipFile(properties = "FILE_HASH=a\nFILE_SIZE=1\n")+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("payload properties"), failed.reason)+ assertFalse(file.exists())+ }++ @Test+ fun `a package missing required entries cannot be read and is deleted`() {+ OtaInstaller.payloadEngineOverride = { FakeEngine() }+ val file = zipFile(includeProperties = false)+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("could not be read"), failed.reason)+ assertFalse(file.exists())+ }++ @Test+ fun `a file that is not a zip cannot be read and is deleted`() {+ OtaInstaller.payloadEngineOverride = { FakeEngine() }+ val file = File(ctx.cacheDir, "not-a-zip-${System.nanoTime()}.zip").apply { writeText("plain text") }+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.reason.contains("could not be read"), failed.reason)+ assertFalse(file.exists())+ }++ @Test+ fun `a missing care map does not stop the install`() {+ val engine = FakeEngine(completionCode = 0)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile(includeCareMap = false)+ assertEquals(OtaInstaller.Result.Applied, install(file))+ assertFalse(careMap.exists())+ }++ @Test+ fun `an engine completion error is classified and deletes the package`() {+ val engine = FakeEngine(completionCode = 9)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile()+ val result = install(file)+ val failed = assertIs<OtaInstaller.Result.Failed>(result)+ assertTrue(failed.retryable, "transfer errors are retryable")+ assertFalse(failed.initializationFailure)+ assertTrue(failed.reason.contains("transfer"), failed.reason)+ assertFalse(file.exists())+ assertTrue(engine.unbound)+ }++ @Test+ fun `an initialisation error on an incremental is flagged for the caller`() {+ val engine = FakeEngine(completionCode = 20)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile(+ metadata = """+ post-timestamp=100+ post-build-incremental=2026090700+ pre-device=shiba+ ota-type=AB+ pre-build-incremental=2026090500+ pre-build=Modern/shiba/shiba:16/2026090500/user/release-keys+ ota-streaming-property-files=payload.bin:1234:5678+ """.trimIndent(),+ )+ val failed = assertIs<OtaInstaller.Result.Failed>(install(file))+ assertTrue(failed.initializationFailure)+ assertFalse(failed.retryable)+ }++ @Test+ fun `when the engine cannot be constructed the install fails cleanly`() {+ OtaInstaller.payloadEngineOverride = { throw IllegalStateException("no service") }+ val file = zipFile()+ val failed = assertIs<OtaInstaller.Result.Failed>(install(file))+ assertTrue(failed.reason.contains("unavailable"), failed.reason)+ }++ @Test+ fun `when binding fails nothing is applied`() {+ val engine = FakeEngine(bindResult = false)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile()+ val failed = assertIs<OtaInstaller.Result.Failed>(install(file))+ assertTrue(failed.reason.contains("could not attach"), failed.reason)+ assertTrue(engine.unbound)+ }++ @Test+ fun `cancelling an in-flight apply cancels the engine`() {+ val engine = FakeEngine(neverCompletes = true)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile()+ runBlocking {+ val deferred = async {+ OtaInstaller.install(file, expected, {}, {})+ }+ // Let the install reach applyPayload, then cancel the caller.+ repeat(100) {+ if (engine.appliedUrl != null) return@repeat+ kotlinx.coroutines.delay(10)+ }+ deferred.cancel()+ runCatching { deferred.await() }+ assertTrue(engine.cancelled, "cancellation must reach update_engine")+ assertTrue(engine.unbound)+ }+ }++ @Test+ fun `without a test engine the real engine is unavailable off-device`() {+ OtaInstaller.payloadEngineOverride = null+ val file = zipFile()+ val failed = assertIs<OtaInstaller.Result.Failed>(install(file))+ assertTrue(failed.reason.contains("unavailable"), failed.reason)+ }++ @Test+ fun `when the engine refuses the payload the refusal is reported`() {+ val engine = FakeEngine(applyThrows = true)+ OtaInstaller.payloadEngineOverride = { engine }+ val file = zipFile()+ val failed = assertIs<OtaInstaller.Result.Failed>(install(file))+ assertTrue(failed.reason.contains("refused"), failed.reason)+ assertTrue(engine.unbound)+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/ReceiversIdleTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/ReceiversIdleTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/ReceiversIdleTest.ktnew file mode 100644index 0000000000..8dea26049c--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/ReceiversIdleTest.kt@@ -0,0 +1,96 @@+package com.vayunmathur.updater.platform++import android.app.job.JobScheduler+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.util.DataStoreUtils+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class ReceiversIdleTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val scheduler get() = ctx.getSystemService(JobScheduler::class.java)++ @BeforeTest+ fun setUp() {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ }++ @Test+ fun `scheduling asks for an idle device after a minimum latency, and cancel removes it`() {+ IdleReboot.schedule(ctx)+ val jobs = scheduler.allPendingJobs+ assertEquals(1, jobs.size)+ val job = jobs.single()+ assertTrue(job.isRequireDeviceIdle)+ assertEquals(5 * 60 * 1000L, job.minLatencyMillis)+ assertEquals(IdleReboot::class.java.name, job.service.className)++ IdleReboot.cancel(ctx)+ assertTrue(scheduler.allPendingJobs.isEmpty())+ }++ @Test+ fun `the idle reboot job reboots on start and does not ask to reschedule on stop`() {+ val service = Robolectric.buildService(IdleReboot::class.java).create().get()+ assertFalse(service.onStartJob(null))+ assertFalse(service.onStopJob(null))+ }++ @Test+ fun `reboot through the companion does not throw without permission plumbing`() {+ // Under Robolectric the PowerManager is a shadow; the point is the null/refusal guards.+ IdleReboot.reboot(ctx)+ }++ @Test+ fun `the reboot receiver cancels the idle job`() {+ IdleReboot.schedule(ctx)+ assertEquals(1, scheduler.allPendingJobs.size)+ RebootReceiver().onReceive(ctx, Intent(ctx, RebootReceiver::class.java))+ assertTrue(scheduler.allPendingJobs.isEmpty())+ }++ @Test+ fun `boot receiver ignores unrelated actions`() {+ UpdateBootReceiver().onReceive(ctx, Intent("com.example.UNRELATED"))+ // No crash and no boot side effects are the observable contract here.+ }++ @Test+ fun `package replaced reschedules the periodic check`() {+ UpdateBootReceiver().onReceive(ctx, Intent(Intent.ACTION_MY_PACKAGE_REPLACED))+ val work = androidx.work.WorkManager.getInstance(ctx)+ .getWorkInfosForUniqueWork("updater_check_periodic")+ .get()+ assertTrue(work.isNotEmpty())+ }++ @Test+ fun `boot completed clears the pending reboot marker`() = runBlocking {+ val store = DataStoreUtils.getInstance(ctx)+ store.setString(UpdaterPreferences.PENDING_REBOOT_BUILD, "2026090700")+ UpdateBootReceiver().onReceive(ctx, Intent(Intent.ACTION_BOOT_COMPLETED))+ // The clear runs in a launched IO coroutine behind goAsync; wait for it to land.+ repeat(100) {+ if (store.getStringAwait(UpdaterPreferences.PENDING_REBOOT_BUILD).isNullOrEmpty()) return@runBlocking+ Thread.sleep(20)+ }+ assertTrue(+ store.getStringAwait(UpdaterPreferences.PENDING_REBOOT_BUILD).isNullOrEmpty(),+ "pending marker should be cleared after boot",+ )+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/SystemBuildCheckerTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/SystemBuildCheckerTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/SystemBuildCheckerTest.ktnew file mode 100644index 0000000000..c7a28ae953--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/SystemBuildCheckerTest.kt@@ -0,0 +1,131 @@+package com.vayunmathur.updater.platform++import java.net.URL+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertIs+import kotlin.test.assertNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class SystemBuildCheckerTest {++ @AfterTest+ fun tearDown() {+ UpdateChecker.connectionOverride = null+ }++ @Test+ fun `ota server defaults and trims a trailing slash from the property`() {+ TestSysProps.set("ro.maos.ota.server", "")+ assertEquals("https://ota.maproj.org", SystemBuild.otaServer())+ TestSysProps.set("ro.maos.ota.server", "https://updates.example.test/")+ assertEquals("https://updates.example.test", SystemBuild.otaServer())+ }++ @Test+ fun `device and fingerprint come from system properties`() {+ TestSysProps.setRunningBuild(device = "husky")+ assertEquals("husky", SystemBuild.device())+ assertEquals("Modern/husky/husky:16/2026090500/user/release-keys", SystemBuild.fingerprint())+ }++ @Test+ fun `current build needs both an incremental and a positive date`() {+ TestSysProps.setRunningBuild(build = "2026090500", dateUtcSeconds = 4242L)+ assertEquals(+ com.vayunmathur.updater.domain.UpdateComparison.CurrentBuild("2026090500", 4242L),+ SystemBuild.current(),+ )+ TestSysProps.set("ro.build.date.utc", "0")+ assertNull(SystemBuild.current())+ TestSysProps.set("ro.build.date.utc", "4242")+ TestSysProps.set("ro.build.version.incremental", "")+ assertNull(SystemBuild.current())+ }++ private fun fakeCheck(body: String, code: Int = 200, capture: MutableList<String>? = null) {+ UpdateChecker.connectionOverride = { url ->+ capture?.add(url)+ FakeHttpsConnection(URL(url), code, body.toByteArray())+ }+ }++ @Test+ fun `check reports a newer build as available`() {+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ val urls = mutableListOf<String>()+ fakeCheck("2026090700 2000 shiba stable\n", capture = urls)+ val result = UpdateChecker.check()+ val available = assertIs<UpdateChecker.Result.Available>(result)+ assertEquals("2026090700", available.metadata.build)+ assertEquals(2000L, available.metadata.buildDateUtcSeconds)+ assertTrue(urls.single().endsWith("/shiba-stable"), urls.toString())+ }++ @Test+ fun `check reports an equal or older build as up to date`() {+ TestSysProps.setRunningBuild(dateUtcSeconds = 2000L)+ fakeCheck("2026090700 2000 shiba stable")+ assertEquals(UpdateChecker.Result.UpToDate, UpdateChecker.check())+ fakeCheck("2026090600 1999 shiba stable")+ assertEquals(UpdateChecker.Result.UpToDate, UpdateChecker.check())+ }++ @Test+ fun `check fails when the running build cannot be read`() {+ TestSysProps.set("ro.build.version.incremental", "")+ fakeCheck("2026090700 2000 shiba stable")+ val failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("running build"), failed.reason)+ }++ @Test+ fun `check fails when the device cannot be read`() {+ TestSysProps.setRunningBuild()+ TestSysProps.set("ro.product.device", "")+ val failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("device"), failed.reason)+ }++ @Test+ fun `check fails on a 404 and on other HTTP errors`() {+ TestSysProps.setRunningBuild()+ fakeCheck("", code = 404)+ var failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("could not reach"), failed.reason)+ fakeCheck("", code = 503)+ failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("could not reach"), failed.reason)+ }++ @Test+ fun `check fails when the body is not a metadata line`() {+ TestSysProps.setRunningBuild()+ fakeCheck("<html>captive portal</html>")+ val failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("metadata line"), failed.reason)+ }++ @Test+ fun `check refuses a non-HTTPS metadata URL without connecting`() {+ TestSysProps.setRunningBuild()+ TestSysProps.set("ro.maos.ota.server", "http://127.0.0.1:9")+ UpdateChecker.connectionOverride = null+ val failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("could not reach"), failed.reason)+ }++ @Test+ fun `check fails when the connection blows up`() {+ TestSysProps.setRunningBuild()+ UpdateChecker.connectionOverride = { url ->+ FakeHttpsConnection(URL(url), 200, failOnInput = true)+ }+ val failed = assertIs<UpdateChecker.Result.Failed>(UpdateChecker.check())+ assertTrue(failed.reason.contains("could not reach"), failed.reason)+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.ktnew file mode 100644index 0000000000..8df43518cb--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/UpdateCheckWorkerTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.updater.platform++import android.content.Context+import android.net.ConnectivityManager+import android.net.NetworkCapabilities+import androidx.test.core.app.ApplicationProvider+import androidx.work.ListenableWorker+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.testing.WorkManagerTestInitHelper+import com.vayunmathur.library.util.DataStoreUtils+import java.net.URL+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.shadows.ShadowNetworkInfo++@RunWith(RobolectricTestRunner::class)+class UpdateCheckWorkerTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val store get() = DataStoreUtils.getInstance(ctx)+ private val fetchCount = AtomicInteger(0)++ @BeforeTest+ fun setUp() = runBlocking {+ runCatching { WorkManagerTestInitHelper.initializeTestWorkManager(ctx) }+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ store.setString(UpdaterPreferences.PENDING_REBOOT_BUILD, "")+ store.setBoolean(UpdaterPreferences.AUTO_INSTALL, true)+ store.setBoolean(UpdaterPreferences.METERED_ALLOWED, false)+ store.setLong(UpdaterPreferences.LAST_CHECKED, 0L)+ Unit+ }++ @AfterTest+ fun tearDown() {+ UpdateChecker.connectionOverride = null+ }++ private fun fakeBody(body: String, code: Int = 200) {+ UpdateChecker.connectionOverride = { url ->+ fetchCount.incrementAndGet()+ FakeHttpsConnection(URL(url), code, body.toByteArray())+ }+ }++ private fun worker() = TestListenableWorkerBuilder<UpdateCheckWorker>(ctx).build()++ private fun doWork() = runBlocking { worker().doWork() }++ @Test+ fun `a pending reboot skips the check entirely`() = runBlocking {+ store.setString(UpdaterPreferences.PENDING_REBOOT_BUILD, "2026090700")+ fakeBody("2026090800 3000 shiba stable")+ assertEquals(ListenableWorker.Result.success(), doWork())+ assertEquals(0, fetchCount.get())+ }++ @Test+ fun `up to date is a success and stamps the last check`() = runBlocking {+ fakeBody("2026090500 1000 shiba stable")+ assertEquals(ListenableWorker.Result.success(), doWork())+ assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) > 0L)+ }++ @Test+ fun `a failed check asks WorkManager to retry`() {+ fakeBody("", code = 404)+ assertEquals(ListenableWorker.Result.retry(), doWork())+ }++ @Test+ fun `an update on an unconnected device is held and announced`() {+ fakeBody("2026090700 2000 shiba stable")+ assertEquals(ListenableWorker.Result.success(), doWork())+ val posted = ctx.getSystemService(android.app.NotificationManager::class.java)+ .activeNotifications+ assertTrue(posted.any { it.id == 2 }, "held update should post the available notification")+ }++ @Test+ fun `an update on unmetered wifi proceeds to the install service`() {+ val connectivity = ctx.getSystemService(ConnectivityManager::class.java)+ val shadow = shadowOf(connectivity)+ shadow.setActiveNetworkInfo(+ ShadowNetworkInfo.newInstance(+ android.net.NetworkInfo.DetailedState.CONNECTED,+ ConnectivityManager.TYPE_WIFI, 0, true, android.net.NetworkInfo.State.CONNECTED,+ ),+ )+ val capabilities = org.robolectric.shadows.ShadowNetworkCapabilities.newInstance()+ val capsShadow = shadowOf(capabilities)+ capsShadow.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)+ capsShadow.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)+ capsShadow.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)+ shadow.setNetworkCapabilities(connectivity.activeNetwork, capabilities)+ shadowOf(ctx as android.app.Application).clearStartedServices()++ fakeBody("2026090700 2000 shiba stable")+ assertEquals(ListenableWorker.Result.success(), doWork())+ val started = shadowOf(ctx as android.app.Application).allStartedServices+ assertTrue(+ started.any { it.component?.className?.endsWith("UpdateInstallService") == true },+ "expected the install service to start, got $started",+ )+ }++ @Test+ fun `schedule enqueues the immediate and periodic checks`() {+ UpdateCheckWorker.schedule(ctx)+ val manager = androidx.work.WorkManager.getInstance(ctx)+ assertTrue(manager.getWorkInfosForUniqueWork("updater_check_immediate").get().isNotEmpty())+ assertTrue(manager.getWorkInfosForUniqueWork("updater_check_periodic").get().isNotEmpty())+ }+}
updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt b/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.ktnew file mode 100644index 0000000000..f392ae8f82--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/platform/UpdaterViewModelTest.kt@@ -0,0 +1,133 @@+package com.vayunmathur.updater.platform++import android.app.Application+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import java.net.URL+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class UpdaterViewModelTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val store get() = DataStoreUtils.getInstance(app)+ private val fetchCount = AtomicInteger(0)++ @BeforeTest+ fun setUp() = runBlocking {+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ store.setBoolean(UpdaterPreferences.AUTO_INSTALL, true)+ store.setBoolean(UpdaterPreferences.METERED_ALLOWED, false)+ store.setLong(UpdaterPreferences.LAST_CHECKED, 0L)+ Unit+ }++ @AfterTest+ fun tearDown() {+ UpdateChecker.connectionOverride = null+ }++ private fun awaitState(vm: UpdaterViewModel, condition: (UpdaterUiState) -> Boolean) {+ repeat(200) {+ shadowOf(Looper.getMainLooper()).idle()+ if (condition(vm.state)) return+ Thread.sleep(20)+ }+ shadowOf(Looper.getMainLooper()).idle()+ }++ private fun fakeBody(body: String) {+ UpdateChecker.connectionOverride = { url ->+ fetchCount.incrementAndGet()+ FakeHttpsConnection(URL(url), 200, body.toByteArray())+ }+ }++ @Test+ fun `init loads the running build and the stored settings`() = runBlocking {+ store.setBoolean(UpdaterPreferences.AUTO_INSTALL, false)+ store.setBoolean(UpdaterPreferences.METERED_ALLOWED, true)+ store.setLong(UpdaterPreferences.LAST_CHECKED, 777L)+ val vm = UpdaterViewModel(app)+ awaitState(vm) { it.currentBuild == "2026090500" && it.lastCheckedMillis == 777L }+ assertEquals("2026090500", vm.state.currentBuild)+ assertFalse(vm.state.autoInstall)+ assertTrue(vm.state.meteredAllowed)+ assertEquals(777L, vm.state.lastCheckedMillis)+ assertFalse(vm.state.checking)+ assertNull(vm.state.available)+ }++ @Test+ fun `check now surfaces an available update and stamps the check time`() {+ fakeBody("2026090700 2000 shiba stable")+ val vm = UpdaterViewModel(app)+ awaitState(vm) { it.currentBuild == "2026090500" }+ val before = System.currentTimeMillis()+ vm.checkNow()+ assertTrue(vm.state.checking)+ // A second tap while a check is in flight is a no-op.+ vm.checkNow()+ awaitState(vm) { !it.checking && it.available != null }+ assertEquals("2026090700", vm.state.available?.build)+ assertTrue(vm.state.lastCheckedMillis >= before)+ assertNull(vm.state.lastFailure)+ assertEquals(1, fetchCount.get())+ runBlocking { assertTrue((store.getLongAwait(UpdaterPreferences.LAST_CHECKED) ?: 0L) >= before) }+ }++ @Test+ fun `check now clears the update when the device is up to date`() {+ fakeBody("2026090500 1000 shiba stable")+ val vm = UpdaterViewModel(app)+ awaitState(vm) { it.currentBuild == "2026090500" }+ vm.checkNow()+ awaitState(vm) { !it.checking && it.lastCheckedMillis > 0L }+ assertNull(vm.state.available)+ assertNull(vm.state.lastFailure)+ }++ @Test+ fun `check now records the failure reason verbatim`() {+ fakeBody("<html>portal</html>")+ val vm = UpdaterViewModel(app)+ awaitState(vm) { it.currentBuild == "2026090500" }+ vm.checkNow()+ awaitState(vm) { !it.checking && it.lastFailure != null }+ assertTrue(vm.state.lastFailure!!.contains("metadata line"), vm.state.lastFailure)+ assertNull(vm.state.available)+ }++ @Test+ fun `toggles update state immediately and persist`() = runBlocking {+ val vm = UpdaterViewModel(app)+ awaitState(vm) { it.currentBuild == "2026090500" }+ vm.setAutoInstall(false)+ assertFalse(vm.state.autoInstall)+ vm.setMeteredAllowed(true)+ assertTrue(vm.state.meteredAllowed)+ repeat(100) {+ shadowOf(Looper.getMainLooper()).idle()+ if (store.getBooleanAwait(UpdaterPreferences.AUTO_INSTALL, true) == false &&+ store.getBooleanAwait(UpdaterPreferences.METERED_ALLOWED, false)+ ) return@runBlocking+ Thread.sleep(20)+ }+ assertFalse(store.getBooleanAwait(UpdaterPreferences.AUTO_INSTALL, true))+ assertTrue(store.getBooleanAwait(UpdaterPreferences.METERED_ALLOWED, false))+ assertNotNull(vm.state)+ }+}
updater/src/test/java/com/vayunmathur/updater/service/UpdateInstallServiceTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/service/UpdateInstallServiceTest.kt b/updater/src/test/java/com/vayunmathur/updater/service/UpdateInstallServiceTest.ktnew file mode 100644index 0000000000..bfb2d18954--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/service/UpdateInstallServiceTest.kt@@ -0,0 +1,224 @@+package com.vayunmathur.updater.service++import android.app.Application+import android.app.Notification+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import com.vayunmathur.updater.platform.FakeHttpsConnection+import com.vayunmathur.updater.platform.OtaDownloader+import com.vayunmathur.updater.platform.OtaInstaller+import com.vayunmathur.updater.platform.TestSysProps+import com.vayunmathur.updater.platform.UpdaterPreferences+import java.io.File+import java.net.URL+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf++@RunWith(RobolectricTestRunner::class)+class UpdateInstallServiceTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private val store get() = DataStoreUtils.getInstance(ctx)++ // The engine must complete through the callback registered at bind time; capture it there.+ private class CapturingEngine(var completionCode: Int = 0) : OtaInstaller.PayloadEngine {+ private var complete: ((Int) -> Unit)? = null+ override fun bind(+ onStatusUpdate: (Int, Float) -> Unit,+ onPayloadApplicationComplete: (Int) -> Unit,+ ): Boolean {+ complete = onPayloadApplicationComplete+ return true+ }++ override fun applyPayload(url: String, offset: Long, headers: Array<String>) {+ complete?.invoke(completionCode)+ }++ override fun cancel() = Unit+ override fun unbind(): Boolean = true+ }++ private lateinit var staged: File+ private lateinit var careMap: File+ private val responses = ArrayDeque<FakeHttpsConnection>()++ @BeforeTest+ fun setUp() = runBlocking {+ TestSysProps.setRunningBuild(dateUtcSeconds = 1000L)+ staged = File(ctx.cacheDir, "service-update-${System.nanoTime()}.zip")+ careMap = File(ctx.cacheDir, "service-care-${System.nanoTime()}.pb")+ OtaDownloader.updateFileOverride = staged+ OtaDownloader.connectionOverride = { url, _ -> responses.removeFirst() }+ OtaInstaller.signatureCheckOverride = { _, _ -> true }+ OtaInstaller.careMapPathOverride = careMap+ store.setString(UpdaterPreferences.PENDING_REBOOT_BUILD, "")+ store.setString(UpdaterPreferences.FAILED_INCREMENTAL, "")+ store.setString(UpdaterPreferences.DOWNLOAD_FILE, "")+ Unit+ }++ @AfterTest+ fun tearDown() {+ OtaDownloader.updateFileOverride = null+ OtaDownloader.connectionOverride = null+ OtaInstaller.signatureCheckOverride = null+ OtaInstaller.payloadEngineOverride = null+ OtaInstaller.careMapPathOverride = null+ staged.delete(); careMap.delete()+ }++ private fun zipBytes(): ByteArray {+ val file = File(ctx.cacheDir, "payload-${System.nanoTime()}.zip")+ ZipOutputStream(file.outputStream()).use { zip ->+ zip.putNextEntry(ZipEntry("META-INF/com/android/metadata"))+ zip.write(+ """+ post-timestamp=100+ post-build-incremental=2026090700+ pre-device=shiba+ ota-type=AB+ ota-streaming-property-files=payload.bin:1234:5678+ """.trimIndent().toByteArray(),+ ); zip.closeEntry()+ zip.putNextEntry(ZipEntry("payload_properties.txt"))+ zip.write("FILE_HASH=a\nFILE_SIZE=1\nMETADATA_HASH=b\nMETADATA_SIZE=2\n".toByteArray()); zip.closeEntry()+ zip.putNextEntry(ZipEntry("payload.bin")); zip.write(ByteArray(16)); zip.closeEntry()+ }+ return file.readBytes().also { file.delete() }+ }++ private fun startIntent(build: String? = "2026090700", date: Long = 100L): Intent =+ Intent(ctx, UpdateInstallService::class.java).apply {+ if (build != null) putExtra("build", build)+ putExtra("build_date", date)+ }++ private fun startService(intent: Intent): UpdateInstallService {+ val controller = Robolectric.buildService(UpdateInstallService::class.java, intent).create()+ val service = controller.get()+ service.onStartCommand(intent, 0, 1)+ return service+ }++ private fun await(description: String, condition: suspend () -> Boolean) {+ repeat(250) {+ if (runBlocking { condition() }) return+ Thread.sleep(20)+ }+ throw AssertionError("timed out waiting for: $description")+ }++ private fun resultNotification(): Notification? =+ ctx.getSystemService(NotificationManager::class.java)+ .activeNotifications.firstOrNull { it.id == 2 }?.notification++ private fun resultText(): String? =+ resultNotification()?.extras?.getCharSequence(Notification.EXTRA_TEXT)?.toString()++ @Test+ fun `starting without a target build stops immediately`() {+ val service = startService(startIntent(build = null))+ assertEquals(Service.START_NOT_STICKY, service.onStartCommand(Intent(), 0, 2))+ assertNull(service.onBind(null))+ }++ @Test+ fun `an unreadable running build fails with the unknown-build message`() {+ TestSysProps.set("ro.build.version.incremental", "")+ startService(startIntent())+ await("failure notification") { resultText()?.contains("unknown") == true || resultNotification() != null }+ assertNotNull(resultNotification())+ }++ @Test+ fun `when no package is published the failure says so`() {+ responses.add(FakeHttpsConnection(URL("https://ota.example/inc"), 404))+ responses.add(FakeHttpsConnection(URL("https://ota.example/full"), 404))+ OtaInstaller.payloadEngineOverride = { CapturingEngine(0) }+ startService(startIntent())+ await("no-package failure") { resultNotification() != null }+ assertNotNull(resultNotification())+ }++ @Test+ fun `a download failure surfaces its reason`() {+ responses.add(FakeHttpsConnection(URL("https://ota.example/inc"), 500, "x".toByteArray()))+ OtaInstaller.payloadEngineOverride = { CapturingEngine(0) }+ startService(startIntent())+ await("download failure") { resultText()?.contains("500") == true }+ }++ @Test+ fun `a successful update is staged for an idle reboot`() { runBlocking {+ responses.add(FakeHttpsConnection(URL("https://ota.example/inc"), 200, zipBytes()))+ OtaInstaller.payloadEngineOverride = { CapturingEngine(0) }+ startService(startIntent())+ await("pending reboot") {+ store.getStringAwait(UpdaterPreferences.PENDING_REBOOT_BUILD) == "2026090700" &&+ store.getStringAwait(UpdaterPreferences.DOWNLOAD_FILE) == ""+ }+ await("reboot notification") { resultNotification() != null }+ // IdleReboot.schedule itself is covered in ReceiversIdleTest; here the marker and the+ // reboot notification are the service-level contract.+ assertNotNull(resultNotification())+ Unit+ } }++ @Test+ fun `an initialisation failure on the incremental is remembered`() = runBlocking {+ responses.add(FakeHttpsConnection(URL("https://ota.example/inc"), 200, zipBytes()))+ OtaInstaller.payloadEngineOverride = { CapturingEngine(20) }+ startService(startIntent())+ await("failed incremental remembered") {+ store.getStringAwait(UpdaterPreferences.FAILED_INCREMENTAL)+ ?.contains("incremental") == true+ }+ await("failure notification") { resultNotification() != null }+ }++ @Test+ fun `a non initialisation install failure is not remembered as a bad incremental`() = runBlocking {+ responses.add(FakeHttpsConnection(URL("https://ota.example/inc"), 200, zipBytes()))+ OtaInstaller.payloadEngineOverride = { CapturingEngine(10) }+ startService(startIntent())+ await("failure notification") { resultText()?.contains("hash") == true }+ assertTrue(store.getStringAwait(UpdaterPreferences.FAILED_INCREMENTAL).isNullOrEmpty())+ }++ @Test+ fun `timeout and destroy do not throw`() {+ val controller = Robolectric.buildService(UpdateInstallService::class.java, startIntent(build = null)).create()+ val service = controller.get()+ service.onTimeout(1, 0)+ controller.destroy()+ }++ @Test+ fun `the companion start intent carries the target build`() {+ shadowOf(app).clearStartedServices()+ UpdateInstallService.start(ctx, "2026090700", 1234L)+ val started = shadowOf(app).allStartedServices+ val intent = started.lastOrNull { it.component?.className?.endsWith("UpdateInstallService") == true }+ assertNotNull(intent, "started services: $started")+ assertEquals("2026090700", intent.getStringExtra("build"))+ assertEquals(1234L, intent.getLongExtra("build_date", 0L))+ }+}
updater/src/test/java/com/vayunmathur/updater/ui/UpdaterScreenTest.kt
diff --git a/updater/src/test/java/com/vayunmathur/updater/ui/UpdaterScreenTest.kt b/updater/src/test/java/com/vayunmathur/updater/ui/UpdaterScreenTest.ktnew file mode 100644index 0000000000..4fe4cd8293--- /dev/null+++ b/updater/src/test/java/com/vayunmathur/updater/ui/UpdaterScreenTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.updater.ui++import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.assertIsOff+import androidx.compose.ui.test.assertIsOn+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.updater.domain.UpdateMetadata+import com.vayunmathur.updater.platform.UpdaterUiState+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 UpdaterScreenTest {++ @get:Rule+ val rule = createComposeRule()++ private fun setScreen(+ state: UpdaterUiState,+ onCheck: () -> Unit = {},+ onAuto: (Boolean) -> Unit = {},+ onMetered: (Boolean) -> Unit = {},+ ) {+ rule.setContent {+ DynamicTheme {+ UpdaterScreen(+ state = state,+ onCheckNow = onCheck,+ onAutoInstallChanged = onAuto,+ onMeteredAllowedChanged = onMetered,+ )+ }+ }+ }++ @Test+ fun `fresh state says not checked yet and shows the unknown build`() {+ setScreen(UpdaterUiState())+ rule.onNodeWithText("Not checked yet").assertIsDisplayed()+ rule.onNodeWithText("Current build unknown").assertIsDisplayed()+ rule.onNodeWithText("Check now").assertIsDisplayed()+ }++ @Test+ fun `a checked device with nothing newer says up to date with its build`() {+ setScreen(UpdaterUiState(currentBuild = "2026090500", lastCheckedMillis = 1234L))+ rule.onNodeWithText("Your system is up to date").assertIsDisplayed()+ rule.onNodeWithText("Current build 2026090500").assertIsDisplayed()+ }++ @Test+ fun `an available update names the target build`() {+ setScreen(+ UpdaterUiState(+ currentBuild = "2026090500",+ available = UpdateMetadata("2026090700", 2000L),+ lastCheckedMillis = 1234L,+ ),+ )+ rule.onNodeWithText("Update available: 2026090700").assertIsDisplayed()+ }++ @Test+ fun `checking replaces the button with progress`() {+ setScreen(UpdaterUiState(currentBuild = "2026090500", checking = true))+ rule.onNodeWithText("Checking for updates…").assertIsDisplayed()+ rule.onNodeWithText("Check now").assertDoesNotExist()+ }++ @Test+ fun `a failure shows its reason verbatim`() {+ setScreen(+ UpdaterUiState(+ currentBuild = "2026090500",+ lastFailure = "could not reach https://ota.example/shiba-stable",+ ),+ )+ rule.onNodeWithText("Could not check for updates").assertIsDisplayed()+ rule.onNodeWithText("could not reach https://ota.example/shiba-stable").assertIsDisplayed()+ }++ @Test+ fun `check now invokes its callback`() {+ var checked = false+ setScreen(UpdaterUiState(currentBuild = "2026090500"), onCheck = { checked = true })+ rule.onNodeWithText("Check now").performClick()+ assertTrue(checked)+ }++ @Test+ fun `switches show their stored positions`() {+ setScreen(UpdaterUiState(currentBuild = "2026090500", autoInstall = true, meteredAllowed = false))+ rule.onNodeWithText("Install updates automatically").assertIsDisplayed()+ rule.onNodeWithText("Use mobile data").assertIsDisplayed()+ val switches = rule.onAllNodes(androidx.compose.ui.test.isToggleable())+ switches[0].assertIsOn()+ switches[1].assertIsOff()+ }++ @Test+ fun `toggling switches reports the new values`() {+ var auto: Boolean? = null+ var metered: Boolean? = null+ setScreen(+ UpdaterUiState(currentBuild = "2026090500", autoInstall = true, meteredAllowed = false),+ onAuto = { auto = it },+ onMetered = { metered = it },+ )+ val switches = rule.onAllNodes(androidx.compose.ui.test.isToggleable())+ switches[1].performClick()+ assertEquals(true, metered)+ switches[0].performClick()+ assertEquals(false, auto)+ }+}