Modern Apps git

← Modern-Apps.git

library/image: add tests for caches, fetchers, loader and SVG

Commit
8ae58c71c2a90ba61c93b200c20bb07ec227c7f8
Author
Vayun Mathur <[email protected]>
When
2026-11-07 05:16 UTC (29 days ago)
Parents
3d67ebd
Covers MemoryCache/DiskCache (LRU trim, overwrite, clear), the fetcher registry (byte-array/bitmap/file/asset/content), ImageRequest/ImageLoader (bitmap fast path, byte-array decode with memory-cache hits, error results, singleton), SVG decoding (shapes, colours, path commands, lenient invalid input), BitmapDecoder PNG decode and sampling, and AsyncImage state reporting under Robolectric Compose.

Coverage (merged, instructions): 0.8% -> 67.7% (93/11121 -> 7528/11121). Full suite passes via gslot ./gradlew :library:image:createMergedCoverageReport.

Bugs fixed: none. Untestable remainder: VideoFrameDecoder (needs real media), coilcompat shim (migration surface, not a target), and SVG element types whose Canvas calls are not shadowed under Robolectric (ellipse/line/arc render paths return null there but work on device).

(cherry picked from commit 5e5790eebb2be38b1b7717eba58182d4da4168af)

Diff

library/image/src/test/java/com/vayunmathur/library/image/CacheAndFetcherTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/CacheAndFetcherTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/CacheAndFetcherTest.ktnew file mode 100644index 0000000000..b55967fe1a--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/CacheAndFetcherTest.kt@@ -0,0 +1,126 @@+package com.vayunmathur.library.image++import android.content.Context+import android.graphics.Bitmap+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.image.fetchers.AssetFetcher+import com.vayunmathur.library.image.fetchers.BitmapFetcher+import com.vayunmathur.library.image.fetchers.ByteArrayFetcher+import com.vayunmathur.library.image.fetchers.ContentResolverFetcher+import com.vayunmathur.library.image.fetchers.FetchResult+import com.vayunmathur.library.image.fetchers.FileFetcher+import com.vayunmathur.library.image.util.ensureExists+import com.vayunmathur.library.image.util.sha256+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class CacheAndFetcherTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()+    private fun bitmap() = Bitmap.createBitmap(4, 3, Bitmap.Config.ARGB_8888)++    @Test fun `sha256 matches known vectors`() {+        assertEquals("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "".sha256())+        assertEquals("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc".sha256())+    }++    @Test fun `memory cache put get remove clear and eviction by bytes`() {+        val cache = MemoryCache.Builder().build()+        val bmp = bitmap()+        assertNull(cache.get("k"))+        cache.put("k", bmp)+        assertEquals(bmp, cache.get("k"))+        cache.remove("k"); assertNull(cache.get("k"))+        cache.put("a", bmp); cache.clear(); assertNull(cache.get("a"))+        assertEquals(10 * 1024 * 1024, MemoryCache.MAX_BYTES)+    }++    @Test fun `disk cache round trip, overwrite, remove, clear`() {+        val dir = File(ctx.cacheDir, "disk-test-${System.nanoTime()}").ensureExists()+        val cache = DiskCache(dir, 1024 * 1024)+        assertNull(cache.get("missing"))+        cache.put("k1", byteArrayOf(1, 2, 3))+        assertTrue(cache.get("k1")!!.contentEquals(byteArrayOf(1, 2, 3)))+        cache.put("k1", byteArrayOf(9, 9))+        assertTrue(cache.get("k1")!!.contentEquals(byteArrayOf(9, 9)))+        cache.put("k2", ByteArray(10) { it.toByte() })+        assertEquals(10, cache.get("k2")!!.size)+        cache.remove("k1"); assertNull(cache.get("k1"))+        cache.remove("missing") // no-op+        cache.clear(); assertNull(cache.get("k2"))+        dir.deleteRecursively()+    }++    @Test fun `disk cache trims oldest entries over the byte limit`() {+        val dir = File(ctx.cacheDir, "disk-trim-${System.nanoTime()}").ensureExists()+        val cache = DiskCache(dir, 100)+        cache.put("old", ByteArray(60))+        Thread.sleep(5)+        dir.listFiles()!!.first().setLastModified(1000)+        cache.put("new", ByteArray(60)) // 120 > 100 triggers trim of the oldest+        val total = dir.listFiles()!!.sumOf { it.length() }+        assertTrue(total <= 100, "expected trimmed to <=100 bytes, was $total")+        assertTrue(cache.get("new") != null)+        dir.deleteRecursively()+    }++    @Test fun `disk cache builder requires a directory`() {+        assertFailsWith<IllegalStateException> { DiskCache.Builder().build() }+        val dir = File(ctx.cacheDir, "disk-builder-${System.nanoTime()}")+        assertTrue(DiskCache.Builder().directory(dir).build().get("x") == null)+        assertTrue(dir.exists())+        dir.deleteRecursively()+    }++    @Test fun `byte array and bitmap fetchers only handle their types`(): Unit = runBlocking {+        val bytes = byteArrayOf(1, 2)+        assertTrue((ByteArrayFetcher().fetch(bytes, ctx) as FetchResult.Bytes).bytes.contentEquals(bytes))+        assertNull(ByteArrayFetcher().fetch("text", ctx))+        val bmp = bitmap()+        assertEquals(bmp, (BitmapFetcher().fetch(bmp, ctx) as FetchResult.BitmapResult).bitmap)+        assertNull(BitmapFetcher().fetch(bytes, ctx))+    }++    @Test fun `file fetcher reads files by file, uri and path, rejects others`(): Unit = runBlocking {+        val file = File(ctx.cacheDir, "fetch-${System.nanoTime()}.bin").apply { writeBytes(byteArrayOf(7, 8, 9)) }+        assertTrue((FileFetcher().fetch(file, ctx) as FetchResult.Bytes).bytes.contentEquals(byteArrayOf(7, 8, 9)))+        assertTrue((FileFetcher().fetch(Uri.fromFile(file), ctx) as FetchResult.Bytes).bytes.contentEquals(byteArrayOf(7, 8, 9)))+        assertTrue((FileFetcher().fetch("file://${file.absolutePath}", ctx) as FetchResult.Bytes).bytes.contentEquals(byteArrayOf(7, 8, 9)))+        assertTrue((FileFetcher().fetch(file.absolutePath, ctx) as FetchResult.Bytes).bytes.contentEquals(byteArrayOf(7, 8, 9)))+        assertNull(FileFetcher().fetch(File(ctx.cacheDir, "missing.bin"), ctx))+        assertNull(FileFetcher().fetch("https://example.org/x.png", ctx))+        assertNull(FileFetcher().fetch("relative/path.png", ctx))+        assertNull(FileFetcher().fetch(42, ctx))+        file.delete()+    }++    @Test fun `asset and content fetchers gate on scheme and path`(): Unit = runBlocking {+        assertNull(AssetFetcher().fetch("file:///android_asset/missing.png", ctx))+        assertNull(AssetFetcher().fetch("file:///android_asset/", ctx))+        assertNull(AssetFetcher().fetch("https://example.org/a.png", ctx))+        assertNull(AssetFetcher().fetch(42, ctx))+        val content = ContentResolverFetcher().fetch("content://media/external/images/1", ctx)+        assertTrue(content is FetchResult.Source)+        assertNull(ContentResolverFetcher().fetch("file:///x.png", ctx))+        assertNull(ContentResolverFetcher().fetch(42, ctx))+    }++    @Test fun `size and ensureExists helpers`() {+        assertTrue(Size.Original.isOriginal())+        assertTrue(Size(-1, 100).isOriginal())+        assertTrue(!Size(100, 100).isOriginal())+        assertEquals(Size(50, 50), Size(50))+        val dir = File(ctx.cacheDir, "ensure-${System.nanoTime()}/nested")+        assertEquals(dir, dir.ensureExists())+        assertTrue(dir.exists())+        dir.deleteRecursively()+    }+}
library/image/src/test/java/com/vayunmathur/library/image/RequestAndLoaderTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/RequestAndLoaderTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/RequestAndLoaderTest.ktnew file mode 100644index 0000000000..b493827335--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/RequestAndLoaderTest.kt@@ -0,0 +1,93 @@+package com.vayunmathur.library.image++import android.content.Context+import android.graphics.Bitmap+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class RequestAndLoaderTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<Context>()++    private class ScaleTransformation(override val cacheKey: String = "scale") : Transformation {+        override suspend fun transform(input: Bitmap, size: Size): Bitmap = input+    }++    @Test fun `request builder assembles every field and defaults`() {+        val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)+        val req = ImageRequest.Builder(ctx)+            .data(bmp)+            .memoryCacheKey("mem")+            .diskCacheKey("disk")+            .crossfade(true, 300)+            .size(100)+            .transformations(ScaleTransformation())+            .videoFrameMillis(1234L)+            .allowHardware(false)+            .build()+        assertEquals(bmp, req.data)+        assertEquals("mem", req.memoryCacheKey)+        assertEquals("disk", req.diskCacheKey)+        assertTrue(req.crossfade)+        assertEquals(Size(100, 100), req.size)+        assertEquals(1, req.transformations.size)+        assertEquals(1234L, req.videoFrameMillis)+        assertFalse(req.allowHardware)+        val empty = ImageRequest.Builder().build()+        assertNull(empty.data); assertFalse(empty.crossfade); assertEquals(true, empty.allowHardware)+        val sized = ImageRequest.Builder().size(10, 20).size(Size(3, 4)).build()+        assertEquals(Size(30, 40).let { Size(3, 4) }, sized.size)+    }++    @Test fun `builder extension videoFrameMillis ignores null`() {+        val req = ImageRequest.Builder().videoFrameMillis(null).build()+        assertNull(req.videoFrameMillis)+        val req2 = ImageRequest.Builder().videoFrameMillis(99L).build()+        assertEquals(99L, req2.videoFrameMillis)+    }++    @Test fun `bitmap requests execute directly and transform`() = runBlocking {+        val loader = ImageLoader.Builder(ctx).build()+        val bmp = Bitmap.createBitmap(4, 4, Bitmap.Config.ARGB_8888)+        val result = loader.execute(ImageRequest.Builder(ctx).data(bmp).build())+        assertTrue(result is ImageResult.Success)+        assertEquals(bmp, (result as ImageResult.Success).bitmap)+        assertEquals(ImageResult.DataSource.MEMORY, result.dataSource)+        assertFalse(result.isFromMemory)+        assertTrue(result.drawable.bitmap === bmp)+        assertTrue(result.asBitmapDrawable(ctx.resources).bitmap === bmp)+    }++    @Test fun `peek memory cache misses for bitmap data and unknown keys`() = runBlocking {+        val loader = ImageLoader.Builder(ctx).build()+        val bmp = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)+        assertNull(loader.peekMemoryCache(ImageRequest.Builder(ctx).data(bmp).build()))+        assertNull(loader.peekMemoryCache(ImageRequest.Builder(ctx).data("https://example.org/x.png").build()))+        // Seed by executing a bitmap request with an explicit key, then peek a byte request with same key:+        // bitmap data peeks null by design, so instead assert a second execute still succeeds from transform path+        val again = loader.execute(ImageRequest.Builder(ctx).data(bmp).memoryCacheKey("k").build())+        assertTrue(again is ImageResult.Success)+    }++    @Test fun `unfetchable data returns error result`() = runBlocking {+        val loader = ImageLoader.Builder(ctx).build()+        val result = loader.execute(ImageRequest.Builder(ctx).data("https://example.org/nothing.png").build())+        assertTrue(result is ImageResult.Error, "expected Error, got $result")+    }++    @Test fun `singleton get is stable and setDefault replaces it`() {+        val first = ImageLoader.get(ctx)+        assertTrue(first === ImageLoader.get(ctx))+        val custom = ImageLoader.Builder(ctx).build()+        ImageLoader.setDefault(custom)+        assertTrue(custom === ImageLoader.get(ctx))+        ImageLoader.setDefault(first)+    }+}
library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapAndComposeTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapAndComposeTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapAndComposeTest.ktnew file mode 100644index 0000000000..48bde924e7--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/decoders/BitmapAndComposeTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.library.image.decoders++import android.graphics.Bitmap+import android.graphics.Color+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithContentDescription+import androidx.compose.ui.test.assertIsDisplayed+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.image.ImageLoader+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.Size+import com.vayunmathur.library.image.compose.AsyncImage+import com.vayunmathur.library.image.compose.AsyncImageState+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.ByteArrayOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class BitmapAndComposeTest {+    @get:Rule val rule = createComposeRule()+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    private fun pngBytes(width: Int = 16, height: Int = 12): ByteArray {+        val bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)+        bmp.eraseColor(Color.BLUE)+        val out = ByteArrayOutputStream()+        bmp.compress(Bitmap.CompressFormat.PNG, 100, out)+        return out.toByteArray()+    }++    @Test fun `isSvg sniffs tag and xml declaration`() {+        assertTrue(BitmapDecoder.isSvg("<svg></svg>".toByteArray()))+        assertTrue(BitmapDecoder.isSvg("<?xml version=\"1.0\"?><svg></svg>".toByteArray()))+        assertFalse(BitmapDecoder.isSvg("<?xml version=\"1.0\"?><html></html>".toByteArray()))+        assertFalse(BitmapDecoder.isSvg("png".toByteArray()))+        assertFalse(BitmapDecoder.isSvg(ByteArray(0)))+    }++    @Test fun `decode png bytes at original and sampled sizes`(): Unit = runBlocking {+        val bytes = pngBytes()+        assertTrue(bytes.isNotEmpty())+        val full = BitmapDecoder.decode(bytes, ImageRequest.Builder(ctx).build(), allowHardware = false)+        assertNotNull(full)+        assertEquals(16, full.width); assertEquals(12, full.height)+        val thumb = BitmapDecoder.decode(bytes, ImageRequest.Builder(ctx).size(Size(4, 4)).build(), allowHardware = false)+        assertNotNull(thumb)+        assertTrue(thumb.width <= 16 && thumb.height <= 12)+        // Robolectric BitmapFactory fabricates a placeholder for undecodable bytes, so no null assertion here+    }++    @Test fun `image loader decodes byte array requests and caches in memory`(): Unit = runBlocking {+        val loader = ImageLoader.Builder(ctx).build()+        val request = ImageRequest.Builder(ctx).data(pngBytes()).memoryCacheKey("png-1").build()+        val first = loader.execute(request)+        assertTrue(first is com.vayunmathur.library.image.ImageResult.Success, "got $first")+        val second = loader.execute(request)+        assertTrue(second is com.vayunmathur.library.image.ImageResult.Success)+        assertTrue((second as com.vayunmathur.library.image.ImageResult.Success).isFromMemory)+        assertNotNull(loader.peekMemoryCache(request))+    }++    @Test fun `async image renders bitmap model and reports state`() {+        val bmp = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)+        val states = mutableListOf<AsyncImageState>()+        rule.setContent {+            AsyncImage(model = bmp, contentDescription = "sample image", onState = { states += it })+        }+        rule.waitUntil(timeoutMillis = 10_000) { states.any { it is AsyncImageState.Success } }+        rule.onNodeWithContentDescription("sample image").assertExists()+    }++    @Test fun `async image with null model reports empty`() {+        val states = mutableListOf<AsyncImageState>()+        rule.setContent {+            AsyncImage(model = null, contentDescription = null, onState = { states += it })+        }+        assertTrue(states.contains(AsyncImageState.Empty) || states.isEmpty())+    }+}
library/image/src/test/java/com/vayunmathur/library/image/decoders/SvgDecoderTest.kt
diff --git a/library/image/src/test/java/com/vayunmathur/library/image/decoders/SvgDecoderTest.kt b/library/image/src/test/java/com/vayunmathur/library/image/decoders/SvgDecoderTest.ktnew file mode 100644index 0000000000..a4591151e6--- /dev/null+++ b/library/image/src/test/java/com/vayunmathur/library/image/decoders/SvgDecoderTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.library.image.decoders++import android.graphics.Color+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.Size+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++@RunWith(RobolectricTestRunner::class)+class SvgDecoderTest {+    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    private fun svg(body: String, attrs: String = """width="100" height="80" viewBox="0 0 100 80"""") =+        """<svg xmlns="http://www.w3.org/2000/svg" $attrs>$body</svg>""".toByteArray()++    @Test fun `canDecode detects svg by hint and by content`() {+        assertTrue(SvgDecoder.canDecode(ByteArray(0), "icon.svg"))+        assertTrue(SvgDecoder.canDecode(ByteArray(0), "icon.svg?w=10"))+        assertTrue(SvgDecoder.canDecode(ByteArray(0), "image/svg+xml"))+        assertTrue(SvgDecoder.canDecode(svg("<rect/>"), null))+        assertTrue(SvgDecoder.canDecode("  <svg></svg>".toByteArray(), null))+        assertFalse(SvgDecoder.canDecode(byteArrayOf(1, 2, 3), null))+        assertFalse(SvgDecoder.canDecode(byteArrayOf(1, 2, 3), "photo.png"))+    }++    @Test fun `decode renders shapes at requested and default sizes`(): Unit = runBlocking {+        val sized = SvgDecoder.decode(+            svg("""<rect x="0" y="0" width="100" height="80" fill="#ff0000"/><circle cx="50" cy="40" r="10" fill="blue"/>"""),+            ImageRequest.Builder(ctx).size(Size(50, 40)).build(),+        )+        assertNotNull(sized)+        assertEquals(50, sized.width); assertEquals(40, sized.height)+        val defaulted = SvgDecoder.decode(svg("""<path d="M0 0 L100 80" stroke="black"/>"""), ImageRequest.Builder(ctx).build())+        assertNotNull(defaulted)+        assertEquals(512, defaulted.width)+    }++    @Test fun `decode handles additional shapes and invalid input`(): Unit = runBlocking {+        val complex = svg(+            """<rect x="1" y="1" width="10" height="10" fill="#00ff00"/><circle cx="20" cy="20" r="5" fill="red"/><path d="M0 0 L10 10" stroke="black"/>"""+        )+        assertNotNull(SvgDecoder.decode(complex, ImageRequest.Builder(ctx).size(Size(20, 20)).build()))+        // Malformed text decodes to null; empty and non-svg input yield blank bitmaps, never a crash+        assertNull(SvgDecoder.decode("not xml at all".toByteArray(), ImageRequest.Builder(ctx).build()))+        assertNotNull(SvgDecoder.decode(ByteArray(0), ImageRequest.Builder(ctx).build())) // empty input still yields a blank bitmap+        assertNotNull(SvgDecoder.decode("<html><body/></html>".toByteArray(), ImageRequest.Builder(ctx).size(Size(8, 8)).build())) // non-svg XML renders blank+    }++    @Test fun `color parsing covers hex functional keywords and alpha`() {+        assertEquals(Color.RED, parseColorString("#ff0000"))+        assertEquals(Color.RED, parseColorString("red"))+        assertEquals(Color.RED, parseColorString("rgb(255,0,0)"))+        assertEquals(Color.RED, parseColorString("rgb(100%,0%,0%)"))+        assertEquals(Color.TRANSPARENT, parseColorString("transparent"))+        assertNull(parseColorString("none"))+        assertNull(parseColorString(""))+        assertNull(parseColorString(null))+        assertNull(parseColorString("not-a-color"))+        assertEquals(255, parseRgbComp("100%"))+        assertEquals(128, parseRgbComp("128"))+        assertEquals(0, parseRgbComp("junk"))+        assertEquals(0.5f, parseAlphaComp("50%"))+        assertEquals(0.5f, parseAlphaComp("0.5"))+        assertEquals(1f, parseAlphaComp("junk"))+        assertEquals(1f, normalizeAlpha(255f))+        assertEquals(0f, normalizeAlpha(-1f))+    }++    @Test fun `path data parses every command family`() {+        val path = parsePathData("M10 10 H90 V90 L10 90 Z")+        assertFalse(path.isEmpty)+        val curve = parsePathData("M0 0 C10 10 20 10 30 0 S40 -10 50 0 Q60 10 70 0 T80 0 A10 10 0 0 1 90 10 m5 5 l5 5 h5 v5 z")+        assertFalse(curve.isEmpty)+        assertTrue(parsePathData("").isEmpty)+        assertTrue(parsePathData("garbage").isEmpty)+    }++    @Test fun `length parsing handles units andjunk`() {+        assertEquals(10f, parseLength("10"))+        assertEquals(10f, parseLength("10px"))+        assertNull(parseLength(null))+        assertNull(parseLength("abc"))+        assertEquals(100f, parseDocLength("100"))+        assertNull(parseDocLength(null))+    }+}