library-ml: add tests for handles, segmenters, Gemma template and data types
- Commit
6f973a6bfca7a6a8675d21909a8dfece7312b285- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-07 04:35 UTC (29 days ago)
- Parents
f04ae2f
Raise :library:ml merged INSTRUCTION coverage from 15.4% to 46.0% (3,576 covered / 7,770 total, createMergedCoverageReport). 88 module unit tests, all passing (:library:ml:testDebugUnitTest). New Robolectric/JVM tests cover every handle's unavailable contract (Whisper, TinyCLIP, Maia, Nnfp, NLLB, MADLAD, Gemma 4 audio/vision towers, Supertonic from assets and directory, MusicGate constants, FaceDetector/FaceEmbedder, all three segmenters, TextRecognizer), the Gemma 4 chat template and tool protocol (render, declareTools with sorted parameters, parseToolCall, renderToolResponse), promptCeiling/fitAudio trimming, digest/readInt, shortFiles reporting, Part/Turn/ ToolDeclaration/DetectedFaceBox/RecognizedLine data semantics, Supertonic Piece descriptor ownership, and SegmentationMask. 85% is not reachable for this module on the JVM, by design: the Rust JNI bridge is cfg(target_os = android), so the host libmodelrunner.so that unit tests load exports no JNI symbols (MlNative.isAvailable is true but every external throws UnsatisfiedLinkError). Gemma4Handle cannot even be constructed here - its loadError initializer calls lastGemma4Error - and its prompt/generation pipeline, FaceDetector.unpack, TextRecognizer.parse, NativeSegmenter.segment and MusicGate all require a live Vulkan handle plus real model weights (multi-GB downloads or bundled assets). Companion create() success paths additionally need ParcelFileDescriptor.detachFd, which is broken under Robolectric (libcore getOwnerId absent on the host JDK). Those paths are only exercisable on a device with the models downloaded. Bugs fixed: none. (cherry picked from commit d816cde50b74b2ea0b13af573a6009a62cdffe56)
Diff
library/ml/src/test/java/com/vayunmathur/library/ml/DataSemanticsTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/DataSemanticsTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/DataSemanticsTest.ktnew file mode 100644index 0000000000..474279f0f6--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/DataSemanticsTest.kt@@ -0,0 +1,89 @@+package com.vayunmathur.library.ml++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Data-class semantics and tower companion paths that stop at an unreadable file. */+@RunWith(RobolectricTestRunner::class)+class DataSemanticsTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `detected face box equality hash and copy follow every field`() {+ fun face(score: Float) = DetectedFaceBox(+ 0.1f, 0.2f, 0.5f, 0.6f, 0.2f, 0.3f, 0.4f, 0.3f,+ score, 0.3f, 0.4f, 0.22f, 0.5f, 0.38f, 0.5f,+ )+ assertEquals(face(0.9f), face(0.9f))+ assertEquals(face(0.9f).hashCode(), face(0.9f).hashCode())+ assertNotEquals(face(0.9f), face(0.5f))+ assertNotEquals<Any>(face(0.9f), "not a face")+ assertEquals(0.5f, face(0.9f).copy(score = 0.5f).score)+ assertTrue(face(0.9f).toString().contains("0.9"))+ }++ @Test+ fun `recognized line equality and copy follow fields`() {+ val line = RecognizedLine("abc", 0.5f, listOf(0f to 0f, 1f to 1f), vertical = false)+ assertEquals(line, line.copy())+ assertNotEquals(line, line.copy(text = "abd"))+ assertNotEquals(line, line.copy(confidence = 0.6f))+ assertNotEquals(line, line.copy(vertical = true))+ assertEquals(line.hashCode(), line.copy().hashCode())+ }++ @Test+ fun `gemma image and audio parts compare by content not reference`() {+ val imageA = Gemma4Handle.Part.Image(floatArrayOf(1f, 2f))+ val imageB = Gemma4Handle.Part.Image(floatArrayOf(1f, 2f))+ val imageC = Gemma4Handle.Part.Image(floatArrayOf(1f, 3f))+ assertEquals(imageA, imageB)+ assertEquals(imageA.hashCode(), imageB.hashCode())+ assertNotEquals(imageA, imageC)+ assertNotEquals<Any>(imageA, Gemma4Handle.Part.Audio(floatArrayOf(1f, 2f)))+ assertEquals(+ Gemma4Handle.Part.Text("x"),+ Gemma4Handle.Part.Text("x"),+ )+ assertNotEquals(Gemma4Handle.Part.Text("x"), Gemma4Handle.Part.Text("y"))+ }++ @Test+ fun `gemma towers with a present but unreadable model file stay unavailable`() {+ val audioDir = java.nio.file.Files.createTempDirectory("gemma-audio-file").toFile()+ File(audioDir, Gemma4AudioHandle.AUDIO).writeBytes(byteArrayOf(1, 2, 3, 4))+ val audio = Gemma4AudioHandle.inDirectory(audioDir)+ assertFalse(audio.isAvailable)+ assertNull(audio.encode(FloatArray(Gemma4AudioHandle.MIN_SAMPLES + 1)))+ audio.close()++ val visionDir = java.nio.file.Files.createTempDirectory("gemma-vision-file").toFile()+ File(visionDir, Gemma4VisionHandle.VISION).writeBytes(byteArrayOf(5, 6, 7))+ val vision = Gemma4VisionHandle.inDirectory(visionDir)+ assertFalse(vision.isAvailable)+ val bitmap = android.graphics.Bitmap.createBitmap(4, 4, android.graphics.Bitmap.Config.ARGB_8888)+ assertNull(vision.encode(bitmap))+ vision.close()+ bitmap.recycle()+ }++ @Test+ fun `sampling presets have their documented shapes`() {+ assertEquals(Sampling.Greedy, Sampling(topK = 1, topP = 1f, temperature = 0f, seed = Sampling.Greedy.seed))+ assertTrue(Sampling.Chat.topK > 1)+ assertTrue(Sampling.Chat.topP in 0f..1f)+ val custom = Sampling(topK = 8, topP = 0.5f, temperature = 1.2f, seed = 7L)+ assertEquals(custom, custom.copy())+ assertNotEquals(custom, custom.copy(seed = 8L))+ }+}
library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4PureTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4PureTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4PureTest.ktnew file mode 100644index 0000000000..687c7ed199--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/Gemma4PureTest.kt@@ -0,0 +1,258 @@+package com.vayunmathur.library.ml++import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertSame+import kotlin.test.assertTrue++/** Pure companion/template logic of Gemma 4: no handle construction, no native calls. */+class Gemma4PureTest {++ private fun turn(role: Gemma4Handle.Role, text: String) = Gemma4Handle.Turn(role, text)++ // --- render ----------------------------------------------------------------++ @Test+ fun `render without system or tools is bos turns and model open`() {+ val out = Gemma4Handle.render(+ listOf(turn(Gemma4Handle.Role.USER, "hello"), turn(Gemma4Handle.Role.MODEL, "hi there")),+ system = null,+ )+ assertEquals(+ "<bos><|turn>user\nhello<turn|>\n<|turn>model\nhi there<turn|>\n<|turn>model\n",+ out,+ )+ }++ @Test+ fun `render with system includes system turn and blank system behaves as none`() {+ val withSystem = Gemma4Handle.render(emptyList(), system = "Be brief.")+ assertTrue(withSystem.startsWith("<bos><|turn>system\nBe brief.<turn|>\n<|turn>model\n"), withSystem)+ val blankSystem = Gemma4Handle.render(emptyList(), system = " ")+ assertFalse(blankSystem.contains("system"))+ }++ @Test+ fun `render continuation stays inside the open model turn`() {+ val out = Gemma4Handle.render(+ listOf(turn(Gemma4Handle.Role.USER, "q")),+ system = null,+ continuation = "<|tool_response>response:x{value:<|\"|>1<|\"|>}<tool_response|>",+ )+ assertTrue(out.endsWith("<|turn>model\n<|tool_response>response:x{value:<|\"|>1<|\"|>}<tool_response|>"), out)+ }++ @Test+ fun `render with tools emits system turn even without system text`() {+ val tool = Gemma4Handle.ToolDeclaration(+ "get_weather", "Weather lookup",+ listOf(Gemma4Handle.ToolDeclaration.Parameter("city", "City name", "string")),+ )+ val out = Gemma4Handle.render(emptyList(), system = null, tools = listOf(tool))+ assertTrue(out.contains("<|turn>system\n<|tool>declaration:get_weather"), out)+ }++ // --- declareTools -------------------------------------------------------------++ @Test+ fun `declare tools sorts parameters alphabetically and lists required`() {+ val tool = Gemma4Handle.ToolDeclaration(+ "search", "Search the web",+ listOf(+ Gemma4Handle.ToolDeclaration.Parameter("zeta", "last", "number", required = false),+ Gemma4Handle.ToolDeclaration.Parameter("alpha", "first", "string"),+ Gemma4Handle.ToolDeclaration.Parameter("mid", "middle", "boolean"),+ ),+ )+ val declared = Gemma4Handle.declareTools(listOf(tool))+ assertTrue(declared.indexOf("alpha:") < declared.indexOf("mid:"))+ assertTrue(declared.indexOf("mid:") < declared.indexOf("zeta:"))+ assertTrue(declared.contains("required:[<|\"|>alpha<|\"|>,<|\"|>mid<|\"|>]"), declared)+ assertTrue(declared.contains("type:<|\"|>OBJECT<|\"|>"), declared)+ assertTrue(declared.contains("type:<|\"|>STRING<|\"|>"), declared)+ assertTrue(declared.endsWith("}<tool|>"), declared)+ }++ @Test+ fun `declare tools with no parameters and no required omits required list`() {+ val tool = Gemma4Handle.ToolDeclaration("ping", "Ping it", emptyList())+ val declared = Gemma4Handle.declareTools(listOf(tool))+ assertTrue(declared.contains("parameters:{properties:{}"), declared)+ assertFalse(declared.contains("required"))+ assertEquals("", Gemma4Handle.declareTools(emptyList()))+ }++ @Test+ fun `top level declare and render wrappers match companion`() {+ val tools = listOf(Gemma4Handle.ToolDeclaration("t", "d", emptyList()))+ assertEquals(Gemma4Handle.declareTools(tools), declareGemma4Tools(tools))+ assertEquals(+ Gemma4Handle.render(listOf(turn(Gemma4Handle.Role.USER, "x")), "sys"),+ renderGemma4Prompt(listOf(turn(Gemma4Handle.Role.USER, "x")), "sys"),+ )+ }++ // --- parseToolCall ---------------------------------------------------------------++ @Test+ fun `parse tool call extracts quoted and bare arguments`() {+ val call = Gemma4Handle.parseToolCall(+ "noise <|tool_call>call:set_timer{seconds:120,label:<|\"|>tea pot<|\"|>,loud:true}<tool_call|> tail",+ )+ assertNotNull(call)+ assertEquals("set_timer", call.name)+ assertEquals(mapOf("seconds" to "120", "label" to "tea pot", "loud" to "true"), call.arguments)+ }++ @Test+ fun `parse tool call returns null when incomplete or empty`() {+ assertNull(Gemma4Handle.parseToolCall("no call here"))+ assertNull(Gemma4Handle.parseToolCall("<|tool_call>call:half{arg:1"))+ assertNull(Gemma4Handle.parseToolCall("<|tool_call>call:{arg:1}<tool_call|>"))+ assertNull(Gemma4Handle.parseToolCall(""))+ val emptyArgs = Gemma4Handle.parseToolCall("<|tool_call>call:noop{}<tool_call|>")+ assertNotNull(emptyArgs)+ assertEquals(emptyMap(), emptyArgs.arguments)+ }++ @Test+ fun `render tool response wraps value in gemma quotes`() {+ val out = Gemma4Handle.renderToolResponse("set_timer", "done")+ assertEquals("<|tool_response>response:set_timer{value:<|\"|>done<|\"|>}<tool_response|>", out)+ assertEquals(out, renderGemma4ToolResponse("set_timer", "done"))+ }++ // --- promptCeiling / fitAudio --------------------------------------------------------++ @Test+ fun `prompt ceiling reserves the larger of limit and minimum`() {+ assertEquals(Gemma4Handle.MAX_CONTEXT - Gemma4Handle.DEFAULT_REPLY, Gemma4Handle.promptCeiling())+ assertEquals(Gemma4Handle.MAX_CONTEXT - 3, Gemma4Handle.promptCeiling(0))+ assertEquals(Gemma4Handle.MAX_CONTEXT - 1000, Gemma4Handle.promptCeiling(1000))+ }++ private fun audio(tokens: Int) = Gemma4Handle.Part.Audio(FloatArray(tokens * Gemma4Handle.SOFT_TOKEN_WIDTH))+ private fun tokens(count: Int) = Gemma4Handle.Part.Tokens(IntArray(count) { it })++ @Test+ fun `fit audio returns same list when there is no audio`() {+ val parts = listOf<Gemma4Handle.Part>(tokens(3), Gemma4Handle.Part.Text("x"))+ assertSame(parts, Gemma4Handle.fitAudio(parts, budget = 0))+ }++ @Test+ fun `fit audio keeps early clips and trims or drops later ones`() {+ val first = audio(4)+ val second = audio(4)+ val parts = listOf<Gemma4Handle.Part>(tokens(2), first, second)+ val fitted = Gemma4Handle.fitAudio(parts, budget = 6)+ assertEquals(3, fitted.size)+ assertEquals(4, (fitted[1] as Gemma4Handle.Part.Audio).positions)+ assertEquals(2, (fitted[2] as Gemma4Handle.Part.Audio).positions)+ // The trimmed clip keeps the start of the second recording (its first floats).+ assertEquals(+ second.soft.copyOf(2 * Gemma4Handle.SOFT_TOKEN_WIDTH).toList(),+ (fitted[2] as Gemma4Handle.Part.Audio).soft.toList(),+ )+ assertEquals(first, fitted[1])+ val dropped = Gemma4Handle.fitAudio(parts, budget = 0)+ assertEquals(listOf<Gemma4Handle.Part>(parts[0]), dropped)+ val negative = Gemma4Handle.fitAudio(parts, budget = -5)+ assertEquals(1, negative.size)+ val abundant = Gemma4Handle.fitAudio(parts, budget = 100)+ assertEquals(parts, abundant)+ }++ // --- Part data classes --------------------------------------------------------------------++ @Test+ fun `part positions and equality follow their arrays`() {+ assertEquals(0, Gemma4Handle.Part.Text("anything").positions)+ assertEquals(3, tokens(3).positions)+ assertEquals(2, Gemma4Handle.Part.Image(FloatArray(2 * Gemma4Handle.SOFT_TOKEN_WIDTH)).positions)+ assertEquals(1, audio(1).positions)+ assertEquals(tokens(3), Gemma4Handle.Part.Tokens(intArrayOf(0, 1, 2)))+ assertEquals(tokens(3).hashCode(), Gemma4Handle.Part.Tokens(intArrayOf(0, 1, 2)).hashCode())+ assertNotEquals(tokens(3), Gemma4Handle.Part.Tokens(intArrayOf(0, 1, 9)))+ assertEquals(audio(1), Gemma4Handle.Part.Audio(FloatArray(Gemma4Handle.SOFT_TOKEN_WIDTH)))+ assertFalse(Gemma4Handle.Part.Audio(FloatArray(Gemma4Handle.SOFT_TOKEN_WIDTH)) == Gemma4Handle.Part.Image(FloatArray(Gemma4Handle.SOFT_TOKEN_WIDTH)))+ }++ @Test+ fun `turn tool declaration and role defaults`() {+ val t = Gemma4Handle.Turn(Gemma4Handle.Role.USER, "hi")+ assertEquals(emptyList(), t.images)+ assertEquals(emptyList(), t.audio)+ assertEquals("user", Gemma4Handle.Role.USER.marker)+ assertEquals("model", Gemma4Handle.Role.MODEL.marker)+ val param = Gemma4Handle.ToolDeclaration.Parameter("x", "y", "STRING")+ assertTrue(param.required)+ val call = Gemma4Handle.ToolCall("fn", mapOf("a" to "b"))+ assertEquals(call, call.copy())+ }++ // --- digest / readInt / files ------------------------------------------------------------++ @Test+ fun `digest is deterministic 32 bytes and input sensitive`() {+ val a = Gemma4Handle.digest(intArrayOf(1, 2, 3, 1000))+ assertEquals(32, a.size)+ assertEquals(a.toList(), Gemma4Handle.digest(intArrayOf(1, 2, 3, 1000)).toList())+ assertNotEquals(a.toList(), Gemma4Handle.digest(intArrayOf(1, 2, 3, 1001)).toList())+ assertNotEquals(a.toList(), Gemma4Handle.digest(intArrayOf()).toList())+ }++ @Test+ fun `readInt is little endian`() {+ assertEquals(0x04030201, Gemma4Handle.readInt(byteArrayOf(1, 2, 3, 4), 0))+ assertEquals(0x04030201, Gemma4Handle.readInt(byteArrayOf(9, 1, 2, 3, 4), 1))+ assertEquals(255, Gemma4Handle.readInt(byteArrayOf(-1, 0, 0, 0), 0))+ }++ @Test+ fun `file lists and markers are consistent`() {+ assertEquals(+ listOf(Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.TOKENIZER),+ Gemma4Handle.FILES,+ )+ assertEquals(+ listOf(Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.HEAD, Gemma4Handle.TOKENIZER),+ Gemma4Handle.FILES_WITH_HEAD,+ )+ assertEquals(intArrayOf(1, 106, 50).toList(), Gemma4Handle.STOP.toList())+ for (marker in listOf(+ Gemma4Handle.BOI_MARKER, Gemma4Handle.EOI_MARKER,+ Gemma4Handle.BOA_MARKER, Gemma4Handle.EOA_MARKER,+ )) {+ assertTrue(marker in Gemma4Handle.MARKERS, marker)+ }+ assertEquals(16384, Gemma4Handle.MAX_CONTEXT)+ }++ @Test+ fun `shortFiles reports only present files below expected size`() {+ val dir = java.nio.file.Files.createTempDirectory("gemma-shortfiles").toFile()+ assertEquals(emptyList(), shortFiles(dir))+ File(dir, Gemma4Handle.TEXT).writeBytes(byteArrayOf(1, 2))+ File(dir, Gemma4Handle.TOKENIZER).writeBytes(byteArrayOf(1))+ val short = shortFiles(dir)+ assertEquals(2, short.size)+ assertTrue(short.any { it.startsWith(Gemma4Handle.TEXT) && it.contains("2/") }, short.toString())+ assertTrue(short.any { it.startsWith(Gemma4Handle.TOKENIZER) }, short.toString())+ // A directory entry (not a file) is not reported.+ File(dir, Gemma4Handle.HEAD).mkdir()+ assertEquals(2, shortFiles(dir).size)+ assertEquals(+ setOf(+ Gemma4Handle.TEXT, Gemma4Handle.EMBED, Gemma4Handle.HEAD,+ Gemma4VisionHandle.VISION, Gemma4AudioHandle.AUDIO, Gemma4Handle.TOKENIZER,+ ),+ GEMMA4_EXPECTED_BYTES.keys,+ )+ }+}
library/ml/src/test/java/com/vayunmathur/library/ml/HandlesUnavailableTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/HandlesUnavailableTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/HandlesUnavailableTest.ktnew file mode 100644index 0000000000..07f476914a--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/HandlesUnavailableTest.kt@@ -0,0 +1,198 @@+package com.vayunmathur.library.ml++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Every handle built without its model files: construction never throws, the+ * handle reports unavailable, and every operation degrades to its empty value.+ * This is the contract callers gate features on.+ */+@RunWith(RobolectricTestRunner::class)+class HandlesUnavailableTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ private fun tempDir(prefix: String): File =+ java.nio.file.Files.createTempDirectory(prefix).toFile()++ // --- Whisper ------------------------------------------------------------++ @Test+ fun `whisper without asset is unavailable and inert`() {+ val handle = WhisperHandle.inAssets(+ context.assets,+ special = intArrayOf(1, 2, 3, 4, 5),+ languages = intArrayOf(10, 11),+ suppress = intArrayOf(20),+ suppressAtBegin = intArrayOf(21),+ )+ assertFalse(handle.isAvailable)+ assertNull(handle.transcribe(FloatArray(WhisperHandle.MELS * WhisperHandle.FRAMES), -1))+ assertNull(handle.transcribe(FloatArray(10), -1))+ handle.close()+ handle.close() // idempotent+ assertTrue(handle.toString().contains("whisper-base"))+ }++ @Test+ fun `whisper rejects the wrong number of special ids`() {+ val handle = WhisperHandle.inAssets(+ context.assets,+ special = intArrayOf(1, 2),+ languages = intArrayOf(),+ suppress = intArrayOf(),+ suppressAtBegin = intArrayOf(),+ )+ assertFalse(handle.isAvailable)+ handle.close()+ assertEquals(80, WhisperHandle.MELS)+ assertEquals(3000, WhisperHandle.FRAMES)+ assertEquals(5, WhisperHandle.SPECIAL_IDS)+ assertTrue(WhisperHandle.GRAPH.endsWith(".maml"))+ }++ // --- TinyCLIP / Maia / Nnfp ------------------------------------------------++ @Test+ fun `clip without asset returns null embeddings`() {+ val handle = ClipHandle.inAssets(context.assets)+ assertFalse(handle.isAvailable)+ assertNull(handle.imageEmbedding(FloatArray(3 * 224 * 224)))+ assertNull(handle.textEmbedding(intArrayOf(1, 2, 3)))+ assertNull(handle.textEmbedding(intArrayOf()))+ handle.close()+ assertTrue(handle.toString().contains("TinyCLIP"))+ assertEquals(512, ClipHandle.DIMENSION)+ assertEquals(77, ClipHandle.CONTEXT_LENGTH)+ }++ @Test+ fun `maia without asset returns null logits`() {+ val handle = MaiaHandle.inAssets(context.assets)+ assertFalse(handle.isAvailable)+ assertNull(handle.logits(FloatArray(MaiaHandle.PLANE_COUNT * MaiaHandle.SQUARES), 1500, 1500))+ assertNull(handle.logits(FloatArray(10), 0, 5000))+ handle.close()+ assertTrue(handle.toString().contains("Maia3-5M"))+ assertEquals(4352, MaiaHandle.MOVES)+ }++ @Test+ fun `nnfp without asset returns null embeddings`() {+ val handle = NnfpHandle.inAssets(context.assets)+ assertFalse(handle.isAvailable)+ assertNull(handle.embed(ShortArray(NnfpHandle.WINDOW_SAMPLES)))+ assertNull(handle.embed(ShortArray(100)))+ handle.close()+ assertTrue(handle.toString().contains("fingerprinter"))+ assertEquals(64, NnfpHandle.EMBEDDING)+ assertEquals(+ NnfpHandle.FRAME_SAMPLES + NnfpHandle.HOP_SAMPLES * (NnfpHandle.WINDOW_FRAMES - 1),+ NnfpHandle.WINDOW_SAMPLES,+ )+ }++ // --- NLLB / MADLAD -----------------------------------------------------------++ @Test+ fun `nllb in empty and partial directories is unavailable`() {+ val empty = NllbHandle.inDirectory(tempDir("nllb-empty"))+ assertFalse(empty.isAvailable)+ assertNull(empty.translate("hello", 1, 2))+ assertNull(empty.translate("", 1, 2)) // unavailable wins over the blank shortcut+ empty.close()+ assertTrue(empty.toString().contains("NLLB-200"))+ assertEquals(listOf(NllbHandle.GRAPH, NllbHandle.TOKENIZER), NllbHandle.FILES)++ val partial = tempDir("nllb-partial")+ File(partial, NllbHandle.GRAPH).writeBytes(byteArrayOf(1, 2, 3))+ val graphOnly = NllbHandle.inDirectory(partial)+ assertFalse(graphOnly.isAvailable)+ graphOnly.close()+ }++ @Test+ fun `madlad in empty directory is unavailable`() {+ val empty = MadladHandle.inDirectory(tempDir("madlad-empty"))+ assertFalse(empty.isAvailable)+ assertNull(empty.translate("hello", "<2en>"))+ empty.close()+ assertTrue(empty.toString().contains("MADLAD400"))+ assertEquals(listOf(MadladHandle.GRAPH, MadladHandle.TOKENIZER), MadladHandle.FILES)+ }++ // --- Gemma towers ---------------------------------------------------------------++ @Test+ fun `gemma audio tower without file is unavailable`() {+ val tower = Gemma4AudioHandle.inDirectory(tempDir("gemma-audio"))+ assertFalse(tower.isAvailable)+ assertNull(tower.encode(FloatArray(Gemma4AudioHandle.MIN_SAMPLES + 100)))+ assertNull(tower.encode(FloatArray(10)))+ tower.close()+ assertTrue(tower.toString().contains("audio tower"))+ assertEquals(1536, Gemma4AudioHandle.OUT_DIM)+ assertTrue(Gemma4AudioHandle.MIN_SAMPLES > 7200)++ val dir = tempDir("gemma-audio-bogus")+ File(dir, Gemma4AudioHandle.AUDIO).writeBytes(byteArrayOf(1, 2, 3))+ val bogus = Gemma4AudioHandle.inDirectory(dir)+ assertFalse(bogus.isAvailable)+ bogus.close()+ }++ @Test+ fun `gemma vision tower without file is unavailable`() {+ val tower = Gemma4VisionHandle.inDirectory(tempDir("gemma-vision"))+ assertFalse(tower.isAvailable)+ val bitmap = android.graphics.Bitmap.createBitmap(8, 8, android.graphics.Bitmap.Config.ARGB_8888)+ assertNull(tower.encode(bitmap))+ assertNull(tower.encode(bitmap, Gemma4VisionHandle.SOFT_TOKEN_BUDGETS.first()))+ tower.close()+ assertTrue(tower.toString().contains("vision tower"))+ assertEquals(intArrayOf(70, 140, 280, 560, 1120).toList(), Gemma4VisionHandle.SOFT_TOKEN_BUDGETS.toList())+ bitmap.recycle()+ }++ // --- Gemma 4 main handle -------------------------------------------------------------++ // Gemma4Handle's constructor reads MlNative.lastGemma4Error() when a load fails;+ // that export is absent from the host .so this JVM loads (stale Rust build), so+ // constructing the handle here throws UnsatisfiedLinkError. Its companion's pure+ // functions are covered in Gemma4PureTest; the handle itself is covered on-device.++ // --- MusicGate ---------------------------------------------------------------------------++ @Test+ fun `music gate constants are self consistent`() {+ assertEquals(16_000, MusicGate.SAMPLE_RATE)+ assertEquals(+ MusicGate.FRAME_SAMPLES + MusicGate.HOP_SAMPLES * (MusicGate.RECEPTIVE_FIELD_HOPS - 1),+ MusicGate.WARMUP_SAMPLES,+ )+ assertEquals(160, MusicGate.HOP_SAMPLES)+ assertEquals(400, MusicGate.FRAME_SAMPLES)+ // MusicGate.inProcess() calls MlNative.createMusicGate, whose export is absent+ // from the stale host .so (see the Gemma note above); construction is therefore+ // not exercised on the JVM here.+ }++ // --- MlNative flag ---------------------------------------------------------------------------++ @Test+ fun `native availability flag is readable`() {+ // Accessing it performs the one loadLibrary attempt for the whole process.+ val available: Boolean = MlNative.isAvailable+ assertEquals(available, MlNative.isAvailable)+ }+}
library/ml/src/test/java/com/vayunmathur/library/ml/SegmentationAndFacesTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/SegmentationAndFacesTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/SegmentationAndFacesTest.ktnew file mode 100644index 0000000000..f91242a8f6--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/SegmentationAndFacesTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.library.ml++import android.content.Context+import android.graphics.Bitmap+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Segmenters, face detector/embedder and the OCR handle without their model+ * assets: unavailable, inert, and safe to close. Plus the pure data types.+ */+@RunWith(RobolectricTestRunner::class)+class SegmentationAndFacesTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ private fun bitmap(w: Int = 8, h: Int = 6): Bitmap =+ Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)++ @Test+ fun `all three segmenters are unavailable without assets`() {+ val selfie = SelfieSegmenter(context)+ assertFalse(selfie.isAvailable)+ assertNull(selfie.segment(bitmap()))+ selfie.close(); selfie.close()++ val modnet = ModnetSegmenter(context)+ assertFalse(modnet.isAvailable)+ assertNull(modnet.segment(bitmap()))+ modnet.close()++ val subject = SubjectSegmenter(context)+ assertFalse(subject.isAvailable)+ assertNull(subject.segment(bitmap()))+ assertNull(subject.segment(bitmap(1, 1)))+ subject.close()++ assertEquals("selfie_segmentation.maml", SelfieSegmenter.DEFAULT_ASSET)+ assertEquals("modnet.maml", ModnetSegmenter.DEFAULT_ASSET)+ assertEquals("u2netp.maml", SubjectSegmenter.DEFAULT_ASSET)+ }++ @Test+ fun `segmenters with a bogus asset name are still unavailable`() {+ val selfie = SelfieSegmenter(context, "no/such/selfie.maml")+ assertFalse(selfie.isAvailable)+ assertNull(selfie.segment(bitmap()))+ selfie.close()+ }++ @Test+ fun `segmentation mask holds its dimensions and values`() {+ val mask = SegmentationMask(2, 2, floatArrayOf(0f, 0.25f, 0.75f, 1f))+ assertEquals(2, mask.width)+ assertEquals(2, mask.height)+ assertEquals(listOf(0f, 0.25f, 0.75f, 1f), mask.mask.toList())+ }++ @Test+ fun `face detector without asset finds nothing`() {+ val detector = FaceDetector(context)+ assertFalse(detector.isAvailable)+ assertEquals(emptyList(), detector.detect(bitmap()))+ assertEquals(emptyList(), detector.detect(bitmap(32, 32)))+ detector.close(); detector.close()+ assertEquals("scrfd_500m.maml", FaceDetector.DEFAULT_ASSET)+ }++ @Test+ fun `face embedder without asset returns null`() {+ val embedder = FaceEmbedder(context)+ assertFalse(embedder.isAvailable)+ assertNull(embedder.embed(bitmap(112, 112)))+ embedder.close()+ assertEquals(512, FaceEmbedder.EMBEDDING_LENGTH)+ assertEquals("w600k_mbf.maml", FaceEmbedder.DEFAULT_ASSET)+ }++ @Test+ fun `detected face box bounds come from its own fields`() {+ val face = DetectedFaceBox(+ left = 0.1f, top = 0.2f, right = 0.5f, bottom = 0.6f,+ leftEyeX = 0.2f, leftEyeY = 0.3f, rightEyeX = 0.4f, rightEyeY = 0.3f,+ score = 0.9f, noseX = 0.3f, noseY = 0.4f,+ mouthLeftX = 0.22f, mouthLeftY = 0.5f, mouthRightX = 0.38f, mouthRightY = 0.5f,+ )+ assertEquals(face, face.copy())+ assertEquals(0.9f, face.score)+ assertTrue(face.right > face.left && face.bottom > face.top)+ }++ @Test+ fun `text recognizer without assets returns no lines`() {+ val recognizer = TextRecognizer(context)+ assertFalse(recognizer.isAvailable)+ assertEquals(emptyList(), recognizer.recognize(bitmap()))+ assertEquals(emptyList(), recognizer.recognize(bitmap(64, 20)))+ recognizer.close(); recognizer.close()+ }++ @Test+ fun `recognized line bounds are the corners extremes`() {+ val line = RecognizedLine(+ text = "hello",+ confidence = 0.75f,+ corners = listOf(10f to 20f, 110f to 15f, 112f to 40f, 8f to 45f),+ vertical = false,+ )+ assertEquals(8f, line.left)+ assertEquals(15f, line.top)+ assertEquals(112f, line.right)+ assertEquals(45f, line.bottom)+ assertEquals(line, line.copy(vertical = true).copy(vertical = false))+ val vertical = line.copy(vertical = true)+ assertTrue(vertical.vertical)+ }+}
library/ml/src/test/java/com/vayunmathur/library/ml/SupertonicTest.kt
diff --git a/library/ml/src/test/java/com/vayunmathur/library/ml/SupertonicTest.kt b/library/ml/src/test/java/com/vayunmathur/library/ml/SupertonicTest.ktnew file mode 100644index 0000000000..6456281516--- /dev/null+++ b/library/ml/src/test/java/com/vayunmathur/library/ml/SupertonicTest.kt@@ -0,0 +1,73 @@+package com.vayunmathur.library.ml++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Supertonic without its bundle: unavailable, silent, and its descriptor+ * ownership piece still honours release/close exactly once.+ */+@RunWith(RobolectricTestRunner::class)+class SupertonicTest {++ private val context: Context get() = ApplicationProvider.getApplicationContext()++ @Test+ fun `synthesizer in empty directory is unavailable and silent`() {+ val dir = java.nio.file.Files.createTempDirectory("supertonic-empty").toFile()+ val synth = SupertonicSynthesizer.inDirectory(dir)+ assertFalse(synth.isAvailable)+ assertEquals(44_100, synth.sampleRate)+ assertEquals(FloatArray(0).toList(), synth.synthesize("hello world", "en").toList())+ assertEquals(FloatArray(0).toList(), synth.synthesize("", "en").toList())+ assertEquals(FloatArray(0).toList(), synth.synthesize(" ", "fr").toList())+ assertFalse(synth.voice("M1"))+ synth.close(); synth.close()+ }++ @Test+ fun `synthesizer in assets without bundle is unavailable`() {+ val synth = SupertonicSynthesizer.inAssets(context.assets, path = "no-such-bundle")+ assertFalse(synth.isAvailable)+ assertEquals(FloatArray(0).toList(), synth.synthesize("bonjour", "fr").toList())+ synth.close()+ assertEquals("style_F1.bin", SupertonicSynthesizer.styleName("F1"))+ assertEquals("style_M2.bin", SupertonicSynthesizer.styleName("M2"))+ assertEquals("F1", SupertonicSynthesizer.DEFAULT_VOICE)+ }++ @Test+ fun `synthesizer with only some bundle files is unavailable`() {+ val dir = java.nio.file.Files.createTempDirectory("supertonic-partial").toFile()+ // No graph files: the first open() fails its isFile check before any+ // descriptor work (ParcelFileDescriptor.detachFd is broken under Robolectric).+ File(dir, "unicode_indexer.bin").writeBytes(byteArrayOf(4))+ File(dir, "style_F1.bin").writeBytes(byteArrayOf(5))+ val synth = SupertonicSynthesizer.inDirectory(dir)+ assertFalse(synth.isAvailable)+ synth.close()+ }++ @Test+ fun `piece releases its descriptor exactly once`() {+ // ParcelFileDescriptor.detachFd is broken under Robolectric (libcore+ // getOwnerId is absent on the host JDK), so synthetic descriptors stand+ // in: Piece's ownership logic is what is under test, not the fd itself.+ val released = SupertonicSynthesizer.Piece(-1, at = 0L, length = 3L)+ assertEquals(-1, released.release())+ released.close() // no-op after release; must not attempt a close++ val owned = SupertonicSynthesizer.Piece(-2, at = 5L, length = 3L)+ assertEquals(5L, owned.at)+ assertEquals(3L, owned.length)+ owned.close() // closes (adoptFd failure is swallowed by design)+ owned.close() // second close is a no-op, must not throw+ }+}