Modern Apps git

← Modern-Apps.git

library/downloadservice: add tests for download core, worker and UI

Commit
589263cd75cf57582a2f13bd96e979df6cd58f0d
Author
Vayun Mathur <[email protected]>
When
2026-11-07 06:11 UTC (29 days ago)
Parents
cba8b89
Merged INSTRUCTION coverage 8.0% -> 90.9% (321/4030 -> 3665/4030).

Added DownloadCoreTest (loopback-HTTP downloads: verify/finalize, nested
dirs, skip/hash/mark already-present files, stale redownload, Range resume
and 200-restart, checksum-mismatch exhaustion, mixed success/failure),
DownloadEdgeTest (retry-then-success, chunked unknown length, slow-drip
progress/speed publishing, legacy DownloadManager claim severing and
.migrating crash restore), DownloadWorkerAndUiTest (unique-work
enqueue/KEEP/REPLACE, doWork success/failure/retry-cap/legacy-no-sizes via
TestListenableWorkerBuilder, GemmaMaml disk helpers, FileProgressItem and
InitialDownloadChecker/InitialModelDownloadChecker Compose states).
Test-only work-testing + mockito deps added.

Verified: :library:downloadservice:testDebugUnitTest (58 tests, 0
failures), createMergedCoverageReport and lint pass.

(cherry picked from commit 36ea0352307415e038e4917cf51076790a8ef945)

Diff

library/downloadservice/build.gradle.kts
diff --git a/library/downloadservice/build.gradle.kts b/library/downloadservice/build.gradle.ktsindex 5a5101c892..f44702136e 100644--- a/library/downloadservice/build.gradle.kts+++ b/library/downloadservice/build.gradle.kts@@ -8,4 +8,6 @@ dependencies {     // (the :library:work helpers schedule that module's own reminders, nothing     // reusable here), so no library-to-library edge is needed (#884).     implementation(libs.androidx.work.runtime.ktx)+    testImplementation(libs.androidx.work.testing)+    testImplementation(libs.mockito.core) }
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadCoreTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadCoreTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadCoreTest.ktnew file mode 100644index 0000000000..771298e0f4--- /dev/null+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadCoreTest.kt@@ -0,0 +1,308 @@+package com.vayunmathur.library.downloadservice++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.net.InetSocketAddress+import java.security.MessageDigest+import java.util.concurrent.atomic.AtomicInteger+import java.util.concurrent.atomic.AtomicReference+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class DownloadCoreTest {++    private val context: Context = ApplicationProvider.getApplicationContext()+    private val ds: DataStoreUtils = DataStoreUtils.getInstance(context)++    private fun sha256(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++    private fun tempDir(prefix: String): File =+        kotlin.io.path.createTempDirectory(prefix).toFile()++    /** Tiny loopback HTTP fixture: [handler] writes the response for each request. */+    private class Server(val handler: (exchange: com.sun.net.httpserver.HttpExchange) -> Unit) {+        val hits = AtomicInteger(0)+        val lastRange = AtomicReference<String?>(null)+        private val server: HttpServer = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)++        init {+            server.createContext("/") { exchange ->+                hits.incrementAndGet()+                lastRange.set(exchange.requestHeaders.getFirst("Range"))+                handler(exchange)+            }+            server.start()+        }++        fun url(path: String): String = "http://127.0.0.1:${server.address.port}/$path"+        fun stop() = server.stop(0)+    }++    private fun serveBytes(bytes: ByteArray): Server = Server { exchange ->+        val range = exchange.requestHeaders.getFirst("Range")+        if (range != null) {+            val start = range.removePrefix("bytes=").removeSuffix("-").toInt()+            val rest = bytes.copyOfRange(start, bytes.size)+            exchange.responseHeaders.set("Content-Range", "bytes $start-${bytes.size - 1}/${bytes.size}")+            exchange.sendResponseHeaders(206, rest.size.toLong())+            exchange.responseBody.use { it.write(rest) }+        } else {+            exchange.sendResponseHeaders(200, bytes.size.toLong())+            exchange.responseBody.use { it.write(bytes) }+        }+    }++    @Test+    fun freshDownloadVerifiesAndFinalizes() = runBlocking<Unit> {+        val payload = ByteArray(5_000) { (it % 251).toByte() }+        val server = serveBytes(payload)+        val dir = tempDir("dl_fresh")+        try {+            val spec = DownloadSpec(+                fileName = "model.bin", description = "Model",+                url = server.url("model.bin"), sha256 = sha256(payload),+                expectedBytes = payload.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            val file = File(dir, "model.bin")+            assertTrue(file.isFile)+            assertTrue(file.readBytes().contentEquals(payload))+            assertFalse(File(dir, "model.bin.part").exists())+            assertEquals(1.0, ds.getDoubleForTest("progress_model.bin"))+            assertEquals(sha256(payload), ds.getString("verified_model.bin"))+        } finally {+            server.stop()+        }+    }++    @Test+    fun downloadIntoSubdirectoryCreatesParents() = runBlocking<Unit> {+        val payload = "nested-payload".toByteArray()+        val server = serveBytes(payload)+        val dir = tempDir("dl_nested")+        try {+            val spec = DownloadSpec(+                fileName = "small100/encoder.bin", description = "Encoder",+                url = server.url("encoder.bin"), sha256 = sha256(payload),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "small100/encoder.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop()+        }+    }++    @Test+    fun alreadyVerifiedFileIsSkippedWithoutNetwork() = runBlocking<Unit> {+        val payload = "already-here".toByteArray()+        val dir = tempDir("dl_skip")+        File(dir, "cached.bin").writeBytes(payload)+        val spec = DownloadSpec(+            fileName = "cached.bin", description = "Cached",+            url = "http://127.0.0.1:1/cached.bin", sha256 = sha256(payload),+            expectedBytes = payload.size.toLong(),+        )+        markVerified(ds, spec)+        assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+        assertEquals(1.0, ds.getDoubleForTest("progress_cached.bin"))+    }++    @Test+    fun unmarkedExistingFileIsHashedThenMarked() = runBlocking<Unit> {+        val payload = "hash-me".toByteArray()+        val dir = tempDir("dl_hash")+        File(dir, "unmarked.bin").writeBytes(payload)+        val spec = DownloadSpec(+            fileName = "unmarked.bin", description = "Unmarked",+            url = "http://127.0.0.1:1/unmarked.bin", sha256 = sha256(payload),+        )+        assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+        // The launch gate marker now exists, written from the real hash.+        assertEquals(sha256(payload), ds.getString("verified_unmarked.bin"))+    }++    @Test+    fun staleOrTruncatedFileIsRedownloaded() = runBlocking<Unit> {+        val good = "the-good-bytes".toByteArray()+        val server = serveBytes(good)+        val dir = tempDir("dl_stale")+        try {+            File(dir, "stale.bin").writeBytes("old".toByteArray())+            val spec = DownloadSpec(+                fileName = "stale.bin", description = "Stale",+                url = server.url("stale.bin"), sha256 = sha256(good),+                expectedBytes = good.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "stale.bin").readBytes().contentEquals(good))+            assertEquals(1, server.hits.get())+        } finally {+            server.stop()+        }+    }++    @Test+    fun resumeAppendsWithRangeHeader() = runBlocking<Unit> {+        val payload = ByteArray(4_000) { (it % 253).toByte() }+        val server = serveBytes(payload)+        val dir = tempDir("dl_resume")+        try {+            File(dir, "big.bin.part").writeBytes(payload.copyOfRange(0, 1_500))+            val spec = DownloadSpec(+                fileName = "big.bin", description = "Big",+                url = server.url("big.bin"), sha256 = sha256(payload),+                expectedBytes = payload.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertEquals("bytes=1500-", server.lastRange.get())+            assertTrue(File(dir, "big.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop()+        }+    }++    @Test+    fun serverIgnoringRangeRestartsFromScratch() = runBlocking<Unit> {+        val payload = "full-body".toByteArray()+        // Always 200 with the whole body, whatever Range was asked for.+        val server = Server { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.use { it.write(payload) }+        }+        val dir = tempDir("dl_restart")+        try {+            File(dir, "restart.bin.part").writeBytes("junkjunk".toByteArray())+            val spec = DownloadSpec(+                fileName = "restart.bin", description = "Restart",+                url = server.url("restart.bin"), sha256 = sha256(payload),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "restart.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop()+        }+    }++    @Test+    fun checksumMismatchExhaustsAttemptsAndReportsFailure() = runBlocking<Unit> {+        val served = "tampered".toByteArray()+        val server = serveBytes(served)+        val dir = tempDir("dl_tamper")+        try {+            val spec = DownloadSpec(+                fileName = "tampered.bin", description = "Tampered",+                url = server.url("tampered.bin"), sha256 = sha256("honest".toByteArray()),+            )+            assertFalse(runDownloadsCore(context, ds, listOf(spec), dir))+            assertFalse(File(dir, "tampered.bin").exists())+            assertFalse(File(dir, "tampered.bin.part").exists())+            assertEquals(4, server.hits.get())+        } finally {+            server.stop()+        }+    }++    @Test+    fun httpErrorReportsFailureAndKeepsGoingToNextFile() = runBlocking<Unit> {+        val payload = "second-file".toByteArray()+        val good = serveBytes(payload)+        val dir = tempDir("dl_mixed")+        try {+            val missing = DownloadSpec(+                fileName = "missing.bin", description = "Missing",+                url = "http://127.0.0.1:1/missing.bin",+            )+            val present = DownloadSpec(+                fileName = "second.bin", description = "Second",+                url = good.url("second.bin"), sha256 = sha256(payload),+            )+            assertFalse(runDownloadsCore(context, ds, listOf(missing, present), dir))+            assertTrue(File(dir, "second.bin").isFile)+        } finally {+            good.stop()+        }+    }++    @Test+    fun emptySpecListSucceeds() = runBlocking<Unit> {+        assertTrue(runDownloadsCore(context, ds, emptyList(), tempDir("dl_empty")))+    }++    @Test+    fun checksumMatchesCoversUnpinnedMismatchAndMarkerFastPath() = runBlocking<Unit> {+        val payload = "check".toByteArray()+        val dir = tempDir("dl_checksum")+        val file = File(dir, "c.bin").also { it.writeBytes(payload) }+        val unpinned = DownloadSpec("c.bin", "C", "http://x/c.bin", sha256 = null)+        assertTrue(checksumMatches(file, ds, unpinned))+        val matching = DownloadSpec("c.bin", "C", "http://x/c.bin", sha256 = sha256(payload))+        assertTrue(checksumMatches(file, ds, matching))+        assertEquals(sha256(payload), ds.getString("verified_c.bin"))+        val wrong = DownloadSpec("c.bin", "C", "http://x/c.bin", sha256 = sha256("nope".toByteArray()))+        assertFalse(checksumMatches(file, ds, wrong))+    }++    @Test+    fun markVerifiedIgnoresUnpinnedSpecs() = runBlocking<Unit> {+        markVerified(ds, DownloadSpec("plain.bin", "P", "http://x/plain.bin", sha256 = null))+        assertEquals(null, ds.getString("verified_plain.bin"))+        val sha = sha256("x".toByteArray())+        markVerified(ds, DownloadSpec("pinned.bin", "P", "http://x/pinned.bin", sha256 = sha))+        assertEquals(sha, ds.getString("verified_pinned.bin"))+    }++    @Test+    fun downloadModelsMapsItemsToSpecs() = runBlocking<Unit> {+        val payload = "via-models".toByteArray()+        val server = serveBytes(payload)+        try {+            val item = ModelDownloadItem(+                url = server.url("m.bin"), fileName = "dlmodels/m.bin",+                description = "M", sha256 = sha256(payload),+                expectedBytes = payload.size.toLong(),+            )+            // No targetDir override: writes under the app external files dir.+            assertTrue(downloadModels(context, ds, listOf(item)))+            val written = File(context.getExternalFilesDir(null), "dlmodels/m.bin")+            assertTrue(written.isFile)+            assertTrue(written.readBytes().contentEquals(payload))+            written.delete()+        } finally {+            server.stop()+        }+    }++    @Test+    fun manifestGateReadsMarkersThroughDataStore() = runBlocking<Unit> {+        val dir = tempDir("dl_gate")+        File(dir, "gate.bin").writeBytes(ByteArray(8))+        val sha = "ab".repeat(32)+        ds.setString("verified_gate.bin", sha)+        val manifest = specsToManifest(+            listOf(DownloadSpec("gate.bin", "G", "http://x/gate.bin", sha256 = sha, expectedBytes = 8L)),+        )+        // Wait for the synchronous mirror to observe the write.+        val deadline = System.currentTimeMillis() + 5_000+        var satisfied = false+        while (System.currentTimeMillis() < deadline && !satisfied) {+            satisfied = manifestSatisfied(dir, ds, manifest)+            if (!satisfied) Thread.sleep(20)+        }+        assertTrue(satisfied)+    }+}++// No synchronous double getter exists; the flow's first value is the stored one.+private suspend fun DataStoreUtils.getDoubleForTest(key: String): Double =+    kotlinx.coroutines.withTimeout(10_000) { doubleFlow(key).first() }
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.ktnew file mode 100644index 0000000000..ab343a0437--- /dev/null+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadEdgeTest.kt@@ -0,0 +1,179 @@+package com.vayunmathur.library.downloadservice++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.net.InetSocketAddress+import java.security.MessageDigest+import java.util.concurrent.atomic.AtomicInteger+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class DownloadEdgeTest {++    private val context: Context = ApplicationProvider.getApplicationContext()+    private val ds: DataStoreUtils = DataStoreUtils.getInstance(context)++    private fun sha256(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++    @Test+    fun transientHttpFailureIsRetriedAndThenSucceeds() = runBlocking<Unit> {+        val payload = "second-attempt".toByteArray()+        val hits = AtomicInteger(0)+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            if (hits.incrementAndGet() == 1) {+                exchange.sendResponseHeaders(500, -1)+                exchange.close()+            } else {+                exchange.sendResponseHeaders(200, payload.size.toLong())+                exchange.responseBody.use { it.write(payload) }+            }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_flaky").toFile()+            val spec = DownloadSpec(+                fileName = "flaky.bin", description = "Flaky",+                url = "http://127.0.0.1:${server.address.port}/flaky.bin",+                sha256 = sha256(payload),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertEquals(2, hits.get())+            assertTrue(File(dir, "flaky.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun chunkedResponseWithoutContentLengthDownloads() = runBlocking<Unit> {+        val payload = "no-length".toByteArray()+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            // 0 means chunked: HttpURLConnection reports contentLengthLong == -1.+            exchange.sendResponseHeaders(200, 0)+            exchange.responseBody.use { it.write(payload) }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_chunked").toFile()+            val spec = DownloadSpec(+                fileName = "chunked.bin", description = "Chunked",+                url = "http://127.0.0.1:${server.address.port}/chunked.bin",+                sha256 = sha256(payload),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "chunked.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun slowDripPublishesProgressAndSpeed() = runBlocking<Unit> {+        val payload = ByteArray(64 * 1024) { (it % 241).toByte() }+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.use { out ->+                var offset = 0+                while (offset < payload.size) {+                    val chunk = minOf(4096, payload.size - offset)+                    out.write(payload, offset, chunk)+                    out.flush()+                    offset += chunk+                    Thread.sleep(80)+                }+            }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_drip").toFile()+            val spec = DownloadSpec(+                fileName = "drip.bin", description = "Drip",+                url = "http://127.0.0.1:${server.address.port}/drip.bin",+                sha256 = sha256(payload), expectedBytes = payload.size.toLong(),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "drip.bin").readBytes().contentEquals(payload))+            // The throttled publisher ran during the ~1.3 s stream.+            val progress = withTimeout(10_000) { ds.doubleFlow("progress_drip.bin").first() }+            assertEquals(1.0, progress)+            val speed = withTimeout(10_000) { ds.doubleFlow("speed_drip.bin").first() }+            assertEquals(0.0, speed)+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun legacyDownloadManagerClaimIsSeveredOnce() = runBlocking<Unit> {+        val payload = "legacy-file".toByteArray()+        val dir = kotlin.io.path.createTempDirectory("dl_legacy_claim").toFile()+        File(dir, "legacy.bin").writeBytes(payload)+        ds.setLong("dlid_legacy.bin", 12345L)+        val spec = DownloadSpec(+            fileName = "legacy.bin", description = "Legacy",+            url = "http://127.0.0.1:1/legacy.bin", sha256 = sha256(payload),+        )+        assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+        // File survived the migration and the stale id was cleared.+        assertTrue(File(dir, "legacy.bin").readBytes().contentEquals(payload))+        val deadline = System.currentTimeMillis() + 5_000+        var cleared: Long? = 12345L+        while (System.currentTimeMillis() < deadline && cleared != 0L) {+            cleared = ds.getLong("dlid_legacy.bin")+            if (cleared != 0L) Thread.sleep(20)+        }+        assertEquals(0L, cleared)+    }++    @Test+    fun strayMigratingFileIsRestored() = runBlocking<Unit> {+        val payload = "restore-me".toByteArray()+        val dir = kotlin.io.path.createTempDirectory("dl_restore").toFile()+        // Crash leftover: only the .migrating copy exists.+        File(dir, "restored.bin.migrating").writeBytes(payload)+        val spec = DownloadSpec(+            fileName = "restored.bin", description = "Restored",+            url = "http://127.0.0.1:1/restored.bin", sha256 = sha256(payload),+        )+        assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+        assertTrue(File(dir, "restored.bin").readBytes().contentEquals(payload))+    }++    @Test+    fun staleDlidWithoutFileIsCleared() = runBlocking<Unit> {+        val payload = "fresh".toByteArray()+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.use { it.write(payload) }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_dlid").toFile()+            ds.setLong("dlid_fresh.bin", 999L)+            val spec = DownloadSpec(+                fileName = "fresh.bin", description = "Fresh",+                url = "http://127.0.0.1:${server.address.port}/fresh.bin",+                sha256 = sha256(payload),+            )+            assertTrue(runDownloadsCore(context, ds, listOf(spec), dir))+            assertTrue(File(dir, "fresh.bin").isFile)+        } finally {+            server.stop(0)+        }+    }+}
library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadWorkerAndUiTest.kt
diff --git a/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadWorkerAndUiTest.kt b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadWorkerAndUiTest.ktnew file mode 100644index 0000000000..839ce31a81--- /dev/null+++ b/library/downloadservice/src/test/java/com/vayunmathur/library/downloadservice/DownloadWorkerAndUiTest.kt@@ -0,0 +1,313 @@+package com.vayunmathur.library.downloadservice++import android.content.Context+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.work.Configuration+import androidx.work.Data+import androidx.work.WorkInfo+import androidx.work.WorkManager+import androidx.work.testing.SynchronousExecutor+import androidx.work.testing.TestListenableWorkerBuilder+import androidx.work.testing.WorkManagerTestInitHelper+import com.sun.net.httpserver.HttpServer+import com.vayunmathur.library.util.DataStoreUtils+import java.io.File+import java.net.InetSocketAddress+import java.security.MessageDigest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith++@RunWith(AndroidJUnit4::class)+class DownloadWorkerAndUiTest {++    @get:Rule+    val composeRule = createComposeRule()++    private val context: Context = ApplicationProvider.getApplicationContext()++    private fun sha256(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }++    private fun initWorkManager() {+        val config = Configuration.Builder()+            .setExecutor(SynchronousExecutor())+            .setTaskExecutor(SynchronousExecutor())+            .build()+        WorkManagerTestInitHelper.initializeTestWorkManager(context, config)+    }++    private fun await(desc: String, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 10_000+        while (System.currentTimeMillis() < deadline) {+            if (condition()) return+            Thread.sleep(20)+        }+        throw AssertionError("timed out: $desc")+    }++    // ---- Worker enqueue / unique work ----++    @Test+    fun enqueueKeepsOneRunAndRetryReplacesIt() {+        initWorkManager()+        val specs = listOf(+            DownloadSpec("w1.bin", "W1", "http://127.0.0.1:1/w1.bin"),+        )+        ModelDownloadWorker.enqueue(context, specs)+        val name = ModelDownloadWorker.uniqueName(specs)+        val wm = WorkManager.getInstance(context)+        await("enqueued") {+            wm.getWorkInfosForUniqueWork(name).get().any { it.state == WorkInfo.State.ENQUEUED }+        }+        // KEEP: a second enqueue for the same specs does not stack a second run.+        ModelDownloadWorker.enqueue(context, specs)+        assertEquals(1, wm.getWorkInfosForUniqueWork(name).get().count { it.state == WorkInfo.State.ENQUEUED })+        // REPLACE swaps the run rather than adding another.+        ModelDownloadWorker.retry(context, specs)+        await("replaced run enqueued") {+            wm.getWorkInfosForUniqueWork(name).get().any { it.state == WorkInfo.State.ENQUEUED }+        }+        wm.cancelUniqueWork(name)+    }++    @Test+    fun enqueueToCarriesTargetDirModels() {+        initWorkManager()+        val dir = kotlin.io.path.createTempDirectory("dl_wmto").toFile()+        val models = listOf(+            ModelDownloadItem("http://127.0.0.1:1/a.bin", "a.bin", "A", sha256 = "ab".repeat(32), expectedBytes = 3L),+            ModelDownloadItem("http://127.0.0.1:1/b.bin", "sub/b.bin", "B"),+        )+        ModelDownloadWorker.enqueueTo(context, models, dir, requireUnmetered = true, replaceExisting = true)+        val specs = models.map {+            DownloadSpec(it.fileName, it.description, it.url, it.sha256, it.expectedBytes)+        }+        val name = ModelDownloadWorker.uniqueName(specs)+        val wm = WorkManager.getInstance(context)+        await("enqueueTo enqueued") {+            wm.getWorkInfosForUniqueWork(name).get().any { it.state == WorkInfo.State.ENQUEUED }+        }+        wm.cancelUniqueWork(name)+    }++    // ---- Worker doWork via TestListenableWorkerBuilder ----++    private fun inputDataFor(+        specs: List<DownloadSpec>,+        targetDir: File? = null,+    ): Data = Data.Builder()+        .putStringArray("urls", specs.map { it.url }.toTypedArray())+        .putStringArray("fileNames", specs.map { it.fileName }.toTypedArray())+        .putStringArray("descriptions", specs.map { it.description }.toTypedArray())+        .putStringArray("hashes", specs.map { it.sha256 ?: "" }.toTypedArray())+        .putLongArray("sizes", specs.map { it.expectedBytes ?: -1L }.toLongArray())+        .apply { targetDir?.let { putString("targetDir", it.absolutePath) } }+        .putBoolean("unmetered", false)+        .build()++    @Test+    fun doWorkSucceedsWhenDownloadCompletes() = runBlocking<Unit> {+        val payload = "worker-payload".toByteArray()+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.use { it.write(payload) }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_worker").toFile()+            val spec = DownloadSpec(+                fileName = "w.bin", description = "W",+                url = "http://127.0.0.1:${server.address.port}/w.bin",+                sha256 = sha256(payload), expectedBytes = payload.size.toLong(),+            )+            val worker = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+                .setInputData(inputDataFor(listOf(spec), dir))+                .build()+            assertEquals(androidx.work.ListenableWorker.Result.success(), worker.doWork())+            assertTrue(File(dir, "w.bin").readBytes().contentEquals(payload))+        } finally {+            server.stop(0)+        }+    }++    @Test+    fun doWorkFailsOnEmptyOrMismatchedInput() = runBlocking<Unit> {+        val empty = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+            .setInputData(Data.EMPTY)+            .build()+        assertEquals(androidx.work.ListenableWorker.Result.failure(), empty.doWork())++        val mismatched = Data.Builder()+            .putStringArray("urls", arrayOf("http://x/a"))+            .putStringArray("fileNames", arrayOf("a.bin", "b.bin"))+            .putStringArray("descriptions", arrayOf("A"))+            .putStringArray("hashes", arrayOf(""))+            .build()+        val bad = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+            .setInputData(mismatched)+            .build()+        assertEquals(androidx.work.ListenableWorker.Result.failure(), bad.doWork())+    }++    @Test+    fun doWorkRetriesTransientFailureThenGivesUpAtAttemptCap() = runBlocking<Unit> {+        val spec = DownloadSpec("gone.bin", "Gone", "http://127.0.0.1:1/gone.bin")+        val dir = kotlin.io.path.createTempDirectory("dl_retry").toFile()+        val firstTry = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+            .setInputData(inputDataFor(listOf(spec), dir))+            .setRunAttemptCount(0)+            .build()+        assertEquals(androidx.work.ListenableWorker.Result.retry(), firstTry.doWork())+        val lastTry = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+            .setInputData(inputDataFor(listOf(spec), dir))+            .setRunAttemptCount(5)+            .build()+        assertEquals(androidx.work.ListenableWorker.Result.failure(), lastTry.doWork())+    }++    @Test+    fun doWorkWithoutSizesDefaultsToUnknown() = runBlocking<Unit> {+        // Old enqueues predate the sizes array: readSpecs must still accept them.+        val payload = "legacy".toByteArray()+        val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)+        server.createContext("/") { exchange ->+            exchange.sendResponseHeaders(200, payload.size.toLong())+            exchange.responseBody.use { it.write(payload) }+        }+        server.start()+        try {+            val dir = kotlin.io.path.createTempDirectory("dl_legacy").toFile()+            val data = Data.Builder()+                .putStringArray("urls", arrayOf("http://127.0.0.1:${server.address.port}/l.bin"))+                .putStringArray("fileNames", arrayOf("l.bin"))+                .putStringArray("descriptions", arrayOf("L"))+                .putStringArray("hashes", arrayOf(sha256(payload)))+                .apply { putString("targetDir", dir.absolutePath) }+                .build()+            val worker = TestListenableWorkerBuilder<ModelDownloadWorker>(context)+                .setInputData(data)+                .build()+            assertEquals(androidx.work.ListenableWorker.Result.success(), worker.doWork())+            assertTrue(File(dir, "l.bin").isFile)+        } finally {+            server.stop(0)+        }+    }++    // ---- ModelUrls on-disk helpers ----++    @Test+    fun gemmaModelDirAndDownloadedFlagFollowDisk() {+        val dir = ModelUrls.GemmaMaml.modelDir(context)+        assertTrue(dir.path.endsWith(ModelUrls.GemmaMaml.DIR))+        // A fresh Robolectric sandbox has none of the multi-GB files.+        assertEquals(false, ModelUrls.GemmaMaml.isDownloaded(context))+        dir.mkdirs()+        for (item in ModelUrls.GemmaMaml.FILES) {+            val file = File(context.getExternalFilesDir(null), item.fileName)+            file.parentFile?.mkdirs()+            file.writeBytes(byteArrayOf(1))+        }+        assertTrue(ModelUrls.GemmaMaml.isDownloaded(context))+        // Removing one file flips the flag back.+        assertTrue(File(context.getExternalFilesDir(null), ModelUrls.GemmaMaml.FILES.first().fileName).delete())+        assertEquals(false, ModelUrls.GemmaMaml.isDownloaded(context))+    }++    // ---- Compose UI ----++    @Test+    fun fileProgressItemShowsDoneState() {+        composeRule.setContent {+            MaterialTheme {+                Surface {+                    FileProgressItem(label = "Text Model", progress = 1.0, speedMbps = 0.0, isDone = true)+                }+            }+        }+        composeRule.onNodeWithText("Text Model").assertIsDisplayed()+        composeRule.onNodeWithText("Completed").assertIsDisplayed()+        composeRule.onNodeWithText("100.0%").assertIsDisplayed()+    }++    @Test+    fun fileProgressItemShowsDownloadingStateWithSpeed() {+        composeRule.setContent {+            MaterialTheme {+                Surface {+                    FileProgressItem(label = "Embeddings", progress = 0.5, speedMbps = 12.34, isDone = false)+                }+            }+        }+        composeRule.onNodeWithText("Embeddings").assertIsDisplayed()+        composeRule.onNodeWithText("Downloading.").assertIsDisplayed()+        composeRule.onNodeWithText("50.0%").assertIsDisplayed()+    }++    @Test+    fun fileProgressItemAtZeroHidesSpeedChip() {+        composeRule.setContent {+            MaterialTheme {+                Surface {+                    FileProgressItem(label = "Tokenizer", progress = 0.0, speedMbps = 0.0, isDone = false)+                }+            }+        }+        composeRule.onNodeWithText("Tokenizer").assertIsDisplayed()+        composeRule.onNodeWithText("0.0%").assertIsDisplayed()+    }++    @Test+    fun checkerGoesStraightToMainPageWhenFilesPresent() {+        val ds = DataStoreUtils.getInstance(context)+        val dir = context.getExternalFilesDir(null)+        assertNotNull(dir)+        val file = File(dir, "gate-present.bin")+        file.writeBytes(byteArrayOf(1, 2, 3))+        composeRule.setContent {+            MaterialTheme {+                InitialDownloadChecker(+                    ds = ds,+                    filesToDownload = listOf(+                        Triple("http://127.0.0.1:1/gate-present.bin", "gate-present.bin", "Present"),+                    ),+                ) {+                    androidx.compose.material3.Text("MAIN PAGE")+                }+            }+        }+        composeRule.onNodeWithText("MAIN PAGE").assertIsDisplayed()+        file.delete()+    }++    @Test+    fun checkerShowsDownloadScreenWhenFilesMissing() {+        initWorkManager()+        val ds = DataStoreUtils.getInstance(context)+        composeRule.setContent {+            MaterialTheme {+                InitialModelDownloadChecker(+                    ds = ds,+                    models = listOf(+                        ModelDownloadItem("http://127.0.0.1:1/absent.bin", "gate-absent.bin", "Absent Model"),+                    ),+                ) {+                    androidx.compose.material3.Text("MAIN PAGE")+                }+            }+        }+        composeRule.onNodeWithText("Absent Model").assertIsDisplayed()+    }+}