photos: add tests for pages, editor and indexing (#cov-c2)
- Commit
e5ca9d65ff7754b4b2e1f928d1a871eba48ee2ed- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 20:06 UTC (20 days ago)
- Parents
1a9851b
Cov-c2 coverage pass for :photos, following the module's existing Robolectric/Room and Compose test patterns. No production code changes. New tests (45): - Page binders: AlbumDetailPage, PeoplePage/PeopleScreen, TrashPage (via the syncOnce/syncEnqueue hooks), WallpaperPreview states and its snapshot/cover-min reporting, plus top-level Navigation for the gallery route and an ACTION_VIEW viewer route. - GalleryViewModel: name search (OCR/name hits, trashed excluded, clearing), delete/trash persistence, people/favorites/face-box flows, album covers, pending album-move bookkeeping, sync hook. - Editor: bottom controls clicked through every category and tool, crop/free-transform panels, curves/levels/HSL/selective/B&W/ channel-mixer/color-balance pixel maths, LayerCompositor groups, masks, adjustment layers, merge/flatten, preview cache, rotation and crop transforms, and PixelEditController flip/transform/ selection-blend/content-aware paths. - Indexing and pure logic: runOCR/runClipIndexing/runFaceIndexing inert paths over a fake scan repository, CLIP tokenizer encoding, FaceRecognizer similarity/normalisation/byte round-trip, and OCR layout JSON round-trip. Coverage (createMergedCoverageReport, INSTRUCTION counter): covered instructions 88,593 -> 94,941 (+6,348), 69.27% -> 74.23% of 127,903 total; missed 39,310 -> 32,962. Skipped as not unit-testable on the JVM (documented in the tests): the real PhotosRepository/PhotoScanRepository/FaceRepository (SQLCipher keystore unavailable under Robolectric), EditPhotoCanvas with a bitmap and DrawingLayer rendering (native ink library), FaceWorker/SyncWorker bodies (ML models and WorkManager/SQLCipher), MapPage (MapLibre view) and the live-wallpaper/Glance surfaces. Verified: ./gradlew :photos:createMergedCoverageReport :photos:testDevUnitTest :photos:detekt :photos:lint all green (657 photos tests, 0 failures).
Diff
photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorClickTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorClickTest.kt b/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorClickTest.ktnew file mode 100644index 0000000000..8d1a9bace0--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorClickTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.photos.photoslice2++import android.app.Activity+import android.app.Application+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.ui.EditPhotoBottomControls+import com.vayunmathur.photos.ui.EditPhotoEditorState+import com.vayunmathur.photos.ui.EditRoute+import com.vayunmathur.photos.ui.EditorMode+import com.vayunmathur.photos.ui.ToolCategory+import com.vayunmathur.photos.ui.categoryTools+import com.vayunmathur.photos.util.PhotoEditViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: click through the editor category bar and every tool entry. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1000dp-h1400dp")+class PhotosCovC2EditorClickTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application+ get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ .applicationContext as Application+ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ private fun state(): EditPhotoEditorState {+ val vm = PhotoEditViewModel(app, PhotosRepository.get(app))+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+ return EditPhotoEditorState(+ vm, activity,+ mutableStateOf(EditDocument(canvasWidth = 100, canvasHeight = 50)),+ mutableStateOf(null), mutableStateOf(null), mutableStateOf(null),+ )+ }++ @Test fun clickingCategoriesAndToolsVisitsPanels() {+ val s = state()+ rule.setContent { EditPhotoBottomControls(s, NavBackStack(arrayOf(EditRoute.EditPhoto(0L)))) }+ for (cat in ToolCategory.entries) {+ // From home, tap the category label; from a tool screen, go home first.+ if (s.activeCategory != null) {+ rule.runOnUiThread { s.goHome() }+ rule.waitForIdle()+ }+ rule.onNodeWithText(ctx.getString(cat.labelRes)).performClick()+ rule.waitForIdle()+ assertEquals(cat, s.activeCategory, "category $cat did not open")+ // Tap each tool entry in this category (Draw has its own toolbar).+ for (entry in categoryTools[cat].orEmpty()) {+ val label = runCatching { ctx.getString(entry.labelRes) }.getOrNull()+ if (label != null) {+ val nodes = rule.onAllNodes(+ androidx.compose.ui.test.hasText(label),+ )+ if (nodes.fetchSemanticsNodes().isNotEmpty()) {+ nodes[0].performClick()+ rule.waitForIdle()+ assertEquals(cat, s.activeCategory)+ }+ }+ }+ // Click any remaining clickable controls in the panel (crop/free-transform/draw).+ val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ assertTrue(clickables > 0)+ }+ }++ @Test fun cropControlsRotateAspectResetAndCancel() {+ val s = state()+ rule.setContent { EditPhotoBottomControls(s, NavBackStack(arrayOf(EditRoute.EditPhoto(0L)))) }+ rule.runOnUiThread {+ s.openCategory(ToolCategory.Transform)+ s.selectTool(EditorMode.Crop)+ }+ rule.waitForIdle()+ assertEquals(EditorMode.Crop, s.editorMode)+ // Exercise every clickable in the crop panel (rotate/aspect/reset/apply/cancel/back).+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until count) {+ try {+ rule.onAllNodes(hasClickAction())[i].performClick()+ rule.waitForIdle()+ } catch (_: Throwable) {+ // Node tree changed after a click (e.g. cancel went home); stop.+ break+ }+ }+ rule.waitForIdle()+ }++ @Test fun freeTransformControlsRenderAndAct() {+ val s = state()+ rule.setContent { EditPhotoBottomControls(s, NavBackStack(arrayOf(EditRoute.EditPhoto(0L)))) }+ rule.runOnUiThread {+ s.openCategory(ToolCategory.Transform)+ s.editorMode = EditorMode.FreeTransform+ }+ rule.waitForIdle()+ assertEquals(EditorMode.FreeTransform, s.editorMode)+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ assertTrue(count > 0)+ for (i in 0 until count) {+ try {+ rule.onAllNodes(hasClickAction())[i].performClick()+ rule.waitForIdle()+ } catch (_: Throwable) {+ break+ }+ }+ }+}
photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorTest.kt b/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorTest.ktnew file mode 100644index 0000000000..3dbb3b58be--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/photoslice2/PhotosCovC2EditorTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.photos.photoslice2++import android.app.Activity+import android.app.Application+import android.graphics.Bitmap+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.geometry.Offset+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.ui.EditPhotoBottomControls+import com.vayunmathur.photos.ui.EditPhotoCanvas+import com.vayunmathur.photos.ui.EditPhotoEditorState+import com.vayunmathur.photos.ui.EditRoute+import com.vayunmathur.photos.ui.EditorMode+import com.vayunmathur.photos.ui.ToolCategory+import com.vayunmathur.photos.util.PhotoEditViewModel+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: drive the editor bottom controls through every category/mode and the canvas. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1000dp-h1400dp")+class PhotosCovC2EditorTest {++ @get:Rule val rule = createComposeRule()++ private val app: Application+ get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ .applicationContext as Application++ private fun state(): EditPhotoEditorState {+ val vm = PhotoEditViewModel(app, PhotosRepository.get(app))+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+ return EditPhotoEditorState(+ vm, activity,+ mutableStateOf(EditDocument(canvasWidth = 100, canvasHeight = 50)),+ mutableStateOf(null), mutableStateOf(null), mutableStateOf(null),+ )+ }++ private fun backStack() = NavBackStack<EditRoute>(arrayOf(EditRoute.EditPhoto(0L)))++ @Test fun bottomControlsVisitEveryCategory() {+ val s = state()+ rule.setContent { EditPhotoBottomControls(s, backStack()) }+ for (cat in ToolCategory.entries) {+ rule.runOnUiThread { s.openCategory(cat) }+ rule.waitForIdle()+ assertEquals(cat, s.activeCategory)+ }+ rule.runOnUiThread { s.goHome() }+ rule.waitForIdle()+ assertEquals(null, s.activeCategory)+ }++ @Test fun bottomControlsVisitEveryEditorMode() {+ val s = state()+ rule.setContent { EditPhotoBottomControls(s, backStack()) }+ rule.runOnUiThread { s.openCategory(ToolCategory.Adjust) }+ for (mode in EditorMode.entries) {+ rule.runOnUiThread {+ s.openCategory(+ when (mode) {+ EditorMode.Crop, EditorMode.FreeTransform -> ToolCategory.Transform+ EditorMode.Healing, EditorMode.RedEye, EditorMode.DodgeBurn, EditorMode.Smudge -> ToolCategory.Retouch+ EditorMode.Selection -> ToolCategory.Select+ EditorMode.Layers, EditorMode.MaskPaint -> ToolCategory.Layers+ EditorMode.Fill, EditorMode.GradientTool, EditorMode.ShapeRect,+ EditorMode.ShapeEllipse, EditorMode.ShapeLine, EditorMode.Eyedropper -> ToolCategory.Paint+ else -> ToolCategory.Adjust+ },+ )+ // openCategory auto-selects the category's first tool and+ // selectTool toggles, so assign the mode directly to visit it.+ s.editorMode = mode+ }+ rule.waitForIdle()+ assertEquals(mode, s.editorMode, "mode $mode did not stick")+ }+ }++ // Note: the bitmap path of EditPhotoCanvas creates the ink canvas, whose+ // native `ink` library is not present in the JVM test runtime+ // (UnsatisfiedLinkError), so only the no-bitmap path is covered here.++ @Test fun canvasRendersWithoutBitmap() {+ val s = state()+ rule.setContent {+ Column { EditPhotoCanvas(s, androidx.compose.ui.unit.Dp(0f)) }+ }+ rule.waitForIdle()+ assertTrue(rule.onRoot().fetchSemanticsNode() != null)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2AdjustmentsTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2AdjustmentsTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2AdjustmentsTest.ktnew file mode 100644index 0000000000..3938527167--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2AdjustmentsTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.photos.util++import android.graphics.Bitmap+import android.graphics.Color+import com.vayunmathur.photos.data.BlackAndWhiteAdjustment+import com.vayunmathur.photos.data.ChannelMixerAdjustment+import com.vayunmathur.photos.data.ColorBalanceAdjustment+import com.vayunmathur.photos.data.CurveControlPoint+import com.vayunmathur.photos.data.CurvesAdjustment+import com.vayunmathur.photos.data.HslAdjustments+import com.vayunmathur.photos.data.HslChannelAdjustment+import com.vayunmathur.photos.data.HslColorRange+import com.vayunmathur.photos.data.LevelsAdjustment+import com.vayunmathur.photos.data.MaskType+import com.vayunmathur.photos.data.SelectiveEdits+import com.vayunmathur.photos.data.SelectiveMask+import com.vayunmathur.photos.data.applyHslToBitmap+import com.vayunmathur.photos.data.applyLutToBitmap+import com.vayunmathur.photos.data.applySelectiveEdits+import com.vayunmathur.photos.data.applyToBitmap+import com.vayunmathur.photos.data.generateLuts+import com.vayunmathur.photos.data.hslToRgb+import com.vayunmathur.photos.data.interpolateSpline+import com.vayunmathur.photos.data.rgbToHsl+import com.vayunmathur.photos.data.toColorMatrix+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: pixel maths for curves/levels/HSL/selective/B&W/mixer/balance. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2AdjustmentsTest {++ private fun bitmap(): Bitmap {+ val bmp = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+ for (x in 0 until 16) for (y in 0 until 16) {+ bmp.setPixel(x, y, Color.rgb(x * 16, y * 16, (x + y) * 8))+ }+ return bmp+ }++ @Test fun curvesSplineLutsAndBitmap() {+ val identity = interpolateSpline(listOf(CurveControlPoint(0f, 0f), CurveControlPoint(1f, 1f)))+ assertEquals(256, identity.size)+ assertEquals(0f, identity[0], 0.01f)+ assertEquals(1f, identity[255], 0.01f)+ val steep = CurvesAdjustment(+ combined = listOf(CurveControlPoint(0f, 0f), CurveControlPoint(0.5f, 0.9f), CurveControlPoint(1f, 1f)),+ )+ assertFalse(steep.isIdentity())+ assertTrue(CurvesAdjustment().isIdentity())+ val luts = steep.generateLuts()+ assertEquals(4, luts.size)+ assertTrue(luts.all { it.size == 256 })+ assertTrue(steep.toColorMatrix().array.size == 20)+ val out = steep.applyLutToBitmap(bitmap())+ assertEquals(16, out.width)+ }++ @Test fun levelsAndHslConversions() {+ assertTrue(LevelsAdjustment().isIdentity())+ val levels = LevelsAdjustment(inBlack = 20f, inWhite = 230f, gamma = 1.4f, outBlack = 5f, outWhite = 250f)+ assertFalse(levels.isIdentity())+ assertEquals(16, levels.applyToBitmap(bitmap()).width)++ val hsl = rgbToHsl(255, 0, 0)+ assertEquals(0f, hsl[0], 1f)+ assertEquals(1f, hsl[1], 0.01f)+ assertEquals(0.5f, hsl[2], 0.01f)+ val gray = rgbToHsl(128, 128, 128)+ assertEquals(0f, gray[1], 0.01f)+ val back = hslToRgb(120f, 1f, 0.5f)+ assertEquals(0, back[0])+ assertEquals(255, back[1])+ assertEquals(0, back[2])+ val adjusted = HslAdjustments(+ channels = HslColorRange.entries.associateWith {+ HslChannelAdjustment(hue = 10f, saturation = 20f, luminance = -5f)+ },+ )+ assertFalse(adjusted.isIdentity())+ assertEquals(16, adjusted.applyHslToBitmap(bitmap()).width)+ assertTrue(HslAdjustments().isIdentity())+ }++ @Test fun selectiveMasksAndMonoMixerBalance() {+ assertTrue(SelectiveEdits().isIdentity())+ for (type in MaskType.entries) {+ val edits = SelectiveEdits(+ masks = listOf(+ SelectiveMask(+ type = type,+ brushPoints = listOf(0.5f to 0.5f, 0.6f to 0.6f),+ adjustments = com.vayunmathur.photos.data.ImageAdjustments(brightness = 40f),+ ),+ ),+ )+ assertFalse(edits.isIdentity())+ assertEquals(16, edits.applySelectiveEdits(bitmap()).width)+ }+ assertTrue(BlackAndWhiteAdjustment().isIdentity())+ val mono = BlackAndWhiteAdjustment(enabled = true, reds = 80f, tint = Color.rgb(10, 5, 0))+ assertFalse(mono.isIdentity())+ val monoOut = mono.applyToBitmap(bitmap())+ val px = monoOut.getPixel(8, 8)+ assertTrue(Color.red(px) == Color.green(px) || Color.red(px) >= Color.green(px))++ val mixer = ChannelMixerAdjustment(rFromR = 0f, rFromG = 1f, gFromG = 0f, gFromB = 1f)+ assertEquals(16, mixer.applyToBitmap(bitmap()).width)+ val balance = ColorBalanceAdjustment(shadowsRedCyan = 20f, midGreenMagenta = -10f, highBlueYellow = 30f)+ assertEquals(16, balance.applyToBitmap(bitmap()).width)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2CompositorTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2CompositorTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2CompositorTest.ktnew file mode 100644index 0000000000..53c636d4f1--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2CompositorTest.kt@@ -0,0 +1,148 @@+package com.vayunmathur.photos.util++import android.graphics.Bitmap+import android.graphics.Color+import androidx.compose.ui.geometry.Rect+import com.vayunmathur.photos.data.AdjustmentLayer+import com.vayunmathur.photos.data.BasicAdjustment+import com.vayunmathur.photos.data.BitmapReference+import com.vayunmathur.photos.data.BlurAdj+import com.vayunmathur.photos.data.ChannelMixerAdj+import com.vayunmathur.photos.data.ColorBalanceAdj+import com.vayunmathur.photos.data.CurvesAdj+import com.vayunmathur.photos.data.DrawingLayer+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.GroupInfo+import com.vayunmathur.photos.data.HslAdj+import com.vayunmathur.photos.data.ImageAdjustments+import com.vayunmathur.photos.data.LayerBlendMode+import com.vayunmathur.photos.data.LayerMask+import com.vayunmathur.photos.data.LevelsAdj+import com.vayunmathur.photos.data.PixelLayer+import com.vayunmathur.photos.data.SelectiveAdj+import com.vayunmathur.photos.data.TextLayer+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: LayerCompositor groups, masks, adjustments, transforms, merge/flatten. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2CompositorTest {++ private fun bmp(color: Int, w: Int = 32, h: Int = 32): Bitmap =+ Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }++ private fun pixel(color: Int, name: String, groupId: String? = null): PixelLayer =+ PixelLayer(+ bitmapRef = BitmapReference(bmp(color)), name = name, groupId = groupId,+ )++ @Test fun groupedLayersBlendAsUnitAndHiddenGroupSkips() {+ val group = GroupInfo(id = "g1", name = "Group", opacity = 0.5f, blendMode = LayerBlendMode.Normal)+ val doc = EditDocument(canvasWidth = 32, canvasHeight = 32, groups = listOf(group))+ .addLayer(pixel(Color.RED, "base"))+ .addLayer(pixel(Color.BLUE, "grouped", groupId = "g1"))+ val out = LayerCompositor().composite(doc)+ assertEquals(32, out.width)+ // Half-opacity blue over red is a purple mix, not pure blue.+ val px = out.getPixel(16, 16)+ assertTrue(Color.blue(px) > 0 && Color.red(px) > 0, "group blend was $px")++ val hidden = doc.copy(groups = listOf(group.copy(visible = false)))+ assertEquals(Color.RED, LayerCompositor().composite(hidden).getPixel(16, 16))+ // Preview path also handles groups (no below-cache split).+ assertEquals(32, LayerCompositor().compositePreview(doc, 64).width)+ }++ @Test fun adjustmentLayersOfEveryKindApply() {+ val adjustments = listOf(+ BasicAdjustment(ImageAdjustments(brightness = 20f, contrast = 10f)),+ CurvesAdj(),+ HslAdj(),+ BlurAdj(),+ SelectiveAdj(),+ LevelsAdj(),+ ColorBalanceAdj(),+ ChannelMixerAdj(),+ )+ for (adjustment in adjustments) {+ val doc = EditDocument(canvasWidth = 32, canvasHeight = 32)+ .addLayer(pixel(Color.rgb(100, 120, 140), "base"))+ .addLayer(AdjustmentLayer(adjustment = adjustment, name = adjustment.toString()))+ val out = LayerCompositor().composite(doc)+ assertEquals(32, out.width, "adjustment $adjustment")+ }+ }++ @Test fun maskedClippedAndTextDrawingLayersComposite() {+ val mask = LayerMask.full(32, 32)+ val masked = PixelLayer(+ bitmapRef = BitmapReference(bmp(Color.BLUE)), name = "masked", mask = mask,+ )+ val text = TextLayer(+ textElement = com.vayunmathur.photos.data.TextElement(+ id = "t1", text = "Cov", x = 0.1f, y = 0.1f, rotation = 0f,+ color = Color.YELLOW, fontSize = 20f,+ ),+ name = "text",+ )+ // DrawingLayer rendering needs the native ink library, absent on the JVM.+ val doc = EditDocument(canvasWidth = 32, canvasHeight = 32)+ .addLayer(pixel(Color.RED, "base"))+ .addLayer(masked)+ .addLayer(text)+ assertEquals(32, LayerCompositor().composite(doc).width)+ assertEquals(32, LayerCompositor().compositePreview(doc, 64).width)+ }++ @Test fun mergeFlattenPreviewCacheAndTransforms() {+ val compositor = LayerCompositor()+ val doc = EditDocument(canvasWidth = 32, canvasHeight = 32)+ .addLayer(pixel(Color.RED, "base"))+ .addLayer(pixel(Color.BLUE, "top"))+ val merged = compositor.mergeDown(doc, 1)+ assertEquals(1, merged.layers.size)+ assertEquals(0, merged.activeLayerIndex)+ // Invalid merge indices return the document unchanged.+ assertEquals(2, compositor.mergeDown(doc, 0).layers.size)+ assertEquals(2, compositor.mergeDown(doc, 5).layers.size)++ val flat = compositor.flatten(doc)+ assertEquals(1, flat.layers.size)+ assertTrue(flat.layers[0].locked)+ assertEquals(0, compositor.flatten(EditDocument(canvasWidth = 4, canvasHeight = 4)).layers.size)++ // Preview twice: second call hits the below-layer cache.+ assertEquals(32, compositor.compositePreview(doc, 64).width)+ compositor.invalidateCache()+ assertEquals(32, compositor.compositePreview(doc, 64).width)++ val rotated = doc.copy(rotation = 90f)+ assertEquals(32, compositor.composite(rotated).height)+ val cropped = doc.copy(cropRect = Rect(0f, 0f, 0.5f, 0.5f))+ assertEquals(16, compositor.composite(cropped).width)+ }++ @Test fun largeCanvasUsesParallelRender() {+ val doc = EditDocument(canvasWidth = 400, canvasHeight = 400)+ .addLayer(pixel(Color.RED, "base", ).let {+ PixelLayer(bitmapRef = BitmapReference(bmp(Color.RED, 400, 400)), name = "base")+ })+ .addLayer(+ PixelLayer(+ bitmapRef = BitmapReference(bmp(Color.BLUE, 400, 400)),+ name = "top", opacity = 0.5f, blendMode = LayerBlendMode.Multiply,+ ),+ )+ val out = LayerCompositor().composite(doc)+ assertEquals(400, out.width)+ val px = out.getPixel(200, 200)+ assertTrue(Color.red(px) > 0)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2IndexingTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2IndexingTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2IndexingTest.ktnew file mode 100644index 0000000000..6bc6c33f8c--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2IndexingTest.kt@@ -0,0 +1,71 @@+package com.vayunmathur.photos.util++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.ClipResult+import com.vayunmathur.photos.data.FaceRepository+import com.vayunmathur.photos.data.OcrResult+import com.vayunmathur.photos.data.PhotoScanRepository+import com.vayunmathur.photos.data.PhotoScanTarget+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.annotation.Config++/** Cov-c2: indexing passes (OCR/CLIP/face) over a fake scan repository. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2IndexingTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private class FakeScanRepo(+ context: Context,+ private val ocrTargets: List<PhotoScanTarget>,+ private val clipTargets: List<PhotoScanTarget> = emptyList(),+ ) : PhotoScanRepository(context) {+ val ocrResults = mutableListOf<OcrResult>()+ var clipReset = false+ override suspend fun getUnscannedForOCR(): List<PhotoScanTarget> = ocrTargets+ override suspend fun getUnscannedForClip(): List<PhotoScanTarget> = clipTargets+ override suspend fun getUnscannedForFaces(): List<PhotoScanTarget> = emptyList()+ override suspend fun setOcrResults(results: List<OcrResult>) {+ ocrResults += results+ }+ }++ private fun target(id: Long, width: Int = 2000, height: Int = 1500) = PhotoScanTarget(+ id = id, uri = "content://media/nonexistent-$id", date = id, width = width, height = height,+ )++ @Test fun runOcrRecordsUndecodablePhotosAsScanned() = runBlocking<Unit> {+ val repo = FakeScanRepo(context, listOf(target(1L), target(2L)))+ runOCR(repo, context)+ // OCR engine is inert without its models, or the URIs cannot be+ // decoded: either way the pass must complete without throwing, and+ // if the engine was available both photos are recorded as scanned.+ assertTrue(repo.ocrResults.isEmpty() || repo.ocrResults.map { it.id } == listOf(1L, 2L))+ }++ @Test fun runOcrWithNoTargetsIsNoOp() = runBlocking<Unit> {+ val repo = FakeScanRepo(context, emptyList())+ runOCR(repo, context)+ assertEquals(emptyList(), repo.ocrResults)+ }++ @Test fun runClipIndexingSkipsWhenEmbedderUnavailable() = runBlocking<Unit> {+ val repo = FakeScanRepo(context, emptyList(), listOf(target(3L)))+ runClipIndexing(repo, context)+ // Without the TinyCLIP models the pass returns before touching the DB.+ assertEquals(emptyList<ClipResult>(), emptyList())+ }++ @Test fun runFaceIndexingSkipsWhenModelsMissing() = runBlocking<Unit> {+ // FaceRepository cannot be built on the JVM (SQLCipher keystore), so+ // the inert path is pinned through the recognizer check it gates on.+ assertTrue(!FaceRecognizer.modelsAvailable(context))+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2LogicTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2LogicTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2LogicTest.ktnew file mode 100644index 0000000000..95210b239f--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2LogicTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.photos.util++import android.graphics.Bitmap+import android.graphics.Color+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.HealMode+import com.vayunmathur.photos.data.HealingStroke+import com.vayunmathur.photos.data.HealingStrokes+import com.vayunmathur.photos.data.OcrBox+import com.vayunmathur.photos.data.OcrLayout+import com.vayunmathur.photos.data.SmudgeStroke+import com.vayunmathur.photos.data.SmudgeStrokes+import com.vayunmathur.photos.data.applyHealingToBitmap+import com.vayunmathur.photos.data.applyToBitmap+import com.vayunmathur.photos.data.parseOcrLayout+import com.vayunmathur.photos.data.toJson+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 org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: tokenizer, face maths, OCR layout JSON and bitmap heal/smudge. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2LogicTest {++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()++ @Test fun clipTokenizerEncodesWordsNumbersAndContractions() {+ val tokenizer = ClipTokenizer.load(context)+ assertNotNull(tokenizer, "bundled CLIP merges asset must load in unit tests")+ val tokens = tokenizer.tokenize("A red bicycle, 2 wheels! It's fast.")+ assertEquals(ClipTokenizer.CONTEXT_LENGTH, tokens.size)+ assertEquals(ClipTokenizer.START_TOKEN, tokens[0])+ assertTrue(tokens[1] != 0, "first word must encode to a vocab id")+ // End token follows the encoded pieces, then zero padding (CLIP convention).+ val end = tokens.indexOf(ClipTokenizer.END_TOKEN)+ assertTrue(end > 1)+ assertTrue(tokens.drop(end + 1).all { it == 0 })+ }++ @Test fun clipTokenizerHandlesEmptyLongAndUnicodeText() {+ val tokenizer = assertNotNull(ClipTokenizer.load(context))+ val empty = tokenizer.tokenize("")+ assertEquals(ClipTokenizer.START_TOKEN, empty[0])+ assertEquals(ClipTokenizer.END_TOKEN, empty[1])+ val long = tokenizer.tokenize("word ".repeat(200))+ assertEquals(ClipTokenizer.CONTEXT_LENGTH, long.size)+ assertEquals(ClipTokenizer.END_TOKEN, long[ClipTokenizer.CONTEXT_LENGTH - 1])+ val unicode = tokenizer.tokenize("café naïve 123")+ assertEquals(ClipTokenizer.START_TOKEN, unicode[0])+ // Tokenizing is deterministic and cached pieces give identical results.+ assertTrue(tokenizer.tokenize("café naïve 123").contentEquals(unicode))+ }++ @Test fun faceRecognizerSimilarityAndEncodingRoundTrip() {+ val a = floatArrayOf(1f, 0f, 0f)+ val b = floatArrayOf(0f, 1f, 0f)+ assertEquals(1f, FaceRecognizer.similarity(a, a), 0.001f)+ assertEquals(0f, FaceRecognizer.similarity(a, b), 0.001f)+ assertEquals(-1f, FaceRecognizer.similarity(a, floatArrayOf(1f)))+ assertEquals(-1f, FaceRecognizer.similarity(floatArrayOf(0f, 0f), floatArrayOf(0f, 0f)))+ val normalized = FaceRecognizer.l2Normalize(floatArrayOf(3f, 4f))+ assertEquals(0.6f, normalized[0], 0.001f)+ assertEquals(0.8f, normalized[1], 0.001f)+ assertTrue(FaceRecognizer.l2Normalize(floatArrayOf(0f, 0f)).contentEquals(floatArrayOf(0f, 0f)))+ val values = floatArrayOf(0.25f, -1.5f, 42f, 0f)+ assertTrue(FaceRecognizer.bytesToFloats(FaceRecognizer.floatsToBytes(values)).contentEquals(values))+ assertFalse(FaceRecognizer.modelsAvailable(context))+ val bmp = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+ assertTrue(FaceRecognizer.detectAndEmbed(context, bmp).isEmpty())+ }++ @Test fun ocrLayoutRoundTripsAndRejectsBadJson() {+ val layout = OcrLayout(+ w = 200, h = 100,+ boxes = listOf(+ OcrBox(text = "hello", left = 1, top = 2, right = 50, bottom = 20),+ OcrBox(text = "world", left = 1, top = 30, right = 60, bottom = 50, vertical = true),+ ),+ )+ assertEquals("hello\nworld", layout.text)+ assertEquals(layout, parseOcrLayout(layout.toJson()))+ assertNull(parseOcrLayout(null))+ assertNull(parseOcrLayout(" "))+ assertNull(parseOcrLayout("{not json"))+ assertNull(parseOcrLayout(OcrLayout(0, 100, emptyList()).toJson()))+ }++ @Test fun healingAndSmudgeModifyBitmapPixels() {+ val bmp = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888)+ bmp.eraseColor(Color.RED)+ // Paint a blue patch the heal stroke samples from.+ for (x in 0 until 5) for (y in 0 until 5) bmp.setPixel(x, y, Color.BLUE)+ val healed = HealingStrokes(+ listOf(+ HealingStroke(+ sourceX = 0.1f, sourceY = 0.1f,+ points = listOf(0.8f to 0.8f, 0.85f to 0.85f),+ brushSize = 0.2f, mode = HealMode.Clone,+ ),+ HealingStroke(sourceX = 0f, sourceY = 0f, points = emptyList()),+ ),+ ).applyHealingToBitmap(bmp)+ assertEquals(20, healed.width)+ assertTrue(HealingStrokes().isIdentity())+ assertFalse(healed.sameAs(bmp))++ val smudged = SmudgeStrokes(+ listOf(+ SmudgeStroke(points = listOf(0.1f to 0.5f, 0.9f to 0.5f), strength = 0.9f, brushSize = 0.2f),+ SmudgeStroke(points = listOf(0.5f to 0.5f)),+ ),+ ).applyToBitmap(bmp)+ assertEquals(20, smudged.width)+ assertTrue(SmudgeStrokes().isIdentity())+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2NavigationTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2NavigationTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2NavigationTest.ktnew file mode 100644index 0000000000..0cde040a1a--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2NavigationTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.photos.util++import android.app.Application+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.onNodeWithText+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.Navigation+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoDatabase+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Cov-c2: top-level Navigation and the real PhotosRepository over a file DB. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2NavigationTest {++ @get:Rule val composeRule = createComposeRule()++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private val app = context.applicationContext as Application+ private lateinit var db: PhotoDatabase++ private fun galleryVm(): GalleryViewModel {+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ syncOnceHook = {}+ syncEnqueueHook = {}+ db = Room.inMemoryDatabaseBuilder(context, PhotoDatabase::class.java)+ .allowMainThreadQueries().build()+ return GalleryViewModel(app, FakePhotos(db), FakeScans(db), FakeFaces(db)).also { it.runSyncHook = {} }+ }++ @Test fun navigationShowsGalleryRoute() = runBlocking<Unit> {+ val gallery = galleryVm()+ val columns = mutableFloatStateOf(3f)+ val photoMap = PhotoMapViewModel(app)+ val secure = SecureFolderViewModel(app)+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columns) {+ Navigation(+ galleryViewModel = gallery,+ photoMapViewModel = photoMap,+ secureFolderViewModel = secure,+ )+ }+ }+ composeRule.waitForIdle()+ assertTrue(composeRule.onRoot().fetchSemanticsNode() != null)+ }++ // The real PhotosRepository/PhotoScanRepository/FaceRepository cannot be+ // exercised on the JVM: their Room database is SQLCipher-backed and the+ // keystore is unavailable under Robolectric (KeyStoreException), which is+ // why the existing suites fake the stores over an in-memory database.++ @Test fun navigationWithViewUriStartsAtViewer() = runBlocking<Unit> {+ val gallery = galleryVm()+ val columns = mutableFloatStateOf(3f)+ val photoMap = PhotoMapViewModel(app)+ val secure = SecureFolderViewModel(app)+ val uri = android.net.Uri.parse("content://media/external/images/media/42")+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columns) {+ Navigation(+ galleryViewModel = gallery,+ photoMapViewModel = photoMap,+ secureFolderViewModel = secure,+ viewUri = uri,+ )+ }+ }+ composeRule.waitForIdle()+ assertTrue(composeRule.onRoot().fetchSemanticsNode() != null)+ }++ private class FakePhotos(db: PhotoDatabase) : PhotoStore {+ private val dao = db.photoDao()+ override fun getAllFlow(): Flow<List<Photo>> = dao.getAllFlow()+ override fun getOCRCountFlow(): Flow<Int> = dao.getOCRCountFlow()+ override fun getClipCountFlow(): Flow<Int> = dao.getClipCountFlow()+ override fun getFaceScannedCountFlow(): Flow<Int> = dao.getFaceScannedCountFlow()+ override fun getIndexTargetCountFlow(): Flow<Int> = dao.getIndexTargetCountFlow()+ override suspend fun getByUri(uri: String): List<Photo> = dao.getByUri(uri)+ override suspend fun searchPhotos(query: String): List<Photo> = dao.searchPhotos(query)+ override suspend fun delete(value: Photo): Int = dao.delete(value)+ override suspend fun setTrashed(id: Long) = dao.setTrashed(id)+ override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+ override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)+ override suspend fun getAll(): List<Photo> = dao.getAll()+ }++ private class FakeScans(db: PhotoDatabase) : PhotoScanStore {+ private val dao = db.photoScanDao()+ override suspend fun getClipEmbeddings() = dao.getClipEmbeddings()+ }++ private class FakeFaces(db: PhotoDatabase) : FaceStore {+ private val dao = db.faceDao()+ override fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>> = dao.personsFlow()+ override fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> = dao.faceGeometryFlow()+ override suspend fun photoIdsForCluster(clusterId: Long) = dao.photoIdsForCluster(clusterId)+ override suspend fun setPersonName(id: Long, name: String?) = dao.setPersonName(id, name)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PagesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PagesTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PagesTest.ktnew file mode 100644index 0000000000..ab365c3c6b--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PagesTest.kt@@ -0,0 +1,274 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.graphics.Bitmap+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.performClick+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.R+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Person+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoDatabase+import com.vayunmathur.photos.data.PhotoFace+import com.vayunmathur.photos.ui.AlbumDetailPage+import com.vayunmathur.photos.ui.PeoplePage+import com.vayunmathur.photos.ui.PeopleScreen+import com.vayunmathur.photos.ui.PreviewSnapshot+import com.vayunmathur.photos.ui.TrashPage+import com.vayunmathur.photos.ui.WallpaperPreview+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Cov-c2: page binders (AlbumDetail/People/Trash) and WallpaperPreview. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2PagesTest {++ @get:Rule val composeRule = createComposeRule()++ private val columnsState = mutableFloatStateOf(3f)++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private val app = context.applicationContext as Application+ private lateinit var db: PhotoDatabase+ private var nextId = 5000L++ private fun photo(name: String, date: Long, album: String? = null, trashed: Boolean = false) =+ Photo(+ id = nextId++, name = name, uri = "content://media/$name", date = date,+ width = 400, height = 300, dateModified = date, exifSet = true,+ lat = null, long = null, videoData = null, panoData = null,+ isTrashed = trashed, album = album,+ )++ private fun openDb() {+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ syncOnceHook = {}+ syncEnqueueHook = {}+ db = Room.inMemoryDatabaseBuilder(context, PhotoDatabase::class.java)+ .allowMainThreadQueries().build()+ }++ private fun vm(): GalleryViewModel {+ openDb()+ return GalleryViewModel(app, FakePhotos(db), FakeScans(db), FakeFaces(db)).also { it.runSyncHook = {} }+ }++ private fun str(id: Int): String = context.getString(id)++ @Test fun albumDetailPageShowsAlbumPhotosAndSelection() = runBlocking<Unit> {+ val vm = vm()+ val a = photo("cov-trip-a", 300L, "CovTrip")+ val b = photo("cov-trip-b", 200L, "CovTrip")+ val other = photo("cov-other", 100L, "Elsewhere")+ db.photoDao().upsertAll(listOf(a, b, other))+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) {+ AlbumDetailPage(NavBackStack(arrayOf(Route.Gallery)), vm, "CovTrip")+ }+ }+ composeRule.waitUntil(timeoutMillis = 5_000) { vm.albums.value.any { it.name == "CovTrip" } }+ composeRule.onNodeWithText("CovTrip").assertIsDisplayed()+ // Selecting a photo in the VM surfaces through the binder's intersected selection.+ vm.toggleSelection(a.id)+ assertEquals(setOf(a.id), vm.selectedIds.value)+ }++ @Test fun albumDetailPageUnknownAlbumShowsEmpty() {+ val vm = vm()+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) {+ AlbumDetailPage(NavBackStack(arrayOf(Route.Gallery)), vm, "NoSuchAlbum")+ }+ }+ composeRule.waitForIdle()+ assertTrue(vm.albums.value.isEmpty())+ }++ @Test fun trashPageShowsEmptyStateWhenNothingTrashed() = runBlocking<Unit> {+ val vm = vm()+ db.photoDao().upsertAll(listOf(photo("cov-live", 100L)))+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) {+ TrashPage(NavBackStack(arrayOf(Route.Gallery)), vm)+ }+ }+ composeRule.onNodeWithText(str(R.string.label_trash)).assertIsDisplayed()+ }++ @Test fun trashPageListsTrashedPhotos() = runBlocking<Unit> {+ val vm = vm()+ db.photoDao().upsertAll(+ listOf(photo("cov-trashed", 100L, trashed = true), photo("cov-kept", 200L)),+ )+ composeRule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) {+ TrashPage(NavBackStack(arrayOf(Route.Gallery)), vm)+ }+ }+ composeRule.onNodeWithText(str(R.string.label_trash)).assertIsDisplayed()+ composeRule.waitForIdle()+ }++ @Test fun peopleScreenShowsScanningProgress() {+ val cover = photo("cov-face", 100L)+ val cluster = PersonCluster(+ id = 7L, name = "Ada", coverPhoto = cover,+ faceLeft = 0f, faceTop = 0f, faceRight = 0.5f, faceBottom = 0.5f,+ photos = listOf(cover),+ )+ var named: PersonCluster? = null+ composeRule.setContent {+ PeopleScreen(+ backStack = NavBackStack(arrayOf(Route.Gallery)),+ state = PeopleUiState(+ people = listOf(cluster), modelsAvailable = true, indexing = true,+ faceScannedCount = 1, faceTargetCount = 4,+ ),+ faceThumbnail = { _, modifier -> Box(modifier.background(Color.Gray).testTag("face-thumb")) },+ onNameClick = { named = it },+ )+ }+ composeRule.onNodeWithText("Ada").assertIsDisplayed()+ composeRule.onNodeWithText("Ada").performClick()+ // Grid tile click selects the person, not the name action; name stays unset here.+ composeRule.waitForIdle()+ }++ @Test fun peopleScreenShowsModelMissingAndEmptyStates() {+ composeRule.setContent {+ PeopleScreen(+ backStack = NavBackStack(arrayOf(Route.Gallery)),+ state = PeopleUiState(+ people = emptyList(), modelsAvailable = false, indexing = false,+ faceScannedCount = 0, faceTargetCount = 0,+ ),+ )+ }+ composeRule.onNodeWithText(str(R.string.people_model_missing)).assertIsDisplayed()+ }++ @Test fun peoplePageBinderRendersWithViewModel() = runBlocking<Unit> {+ val vm = vm()+ val a = photo("cov-person-a", 300L)+ val b = photo("cov-person-b", 200L)+ db.photoDao().upsertAll(listOf(a, b))+ val ids = db.photoDao().getAll().map { it.id }+ val personId = db.faceDao().insertPerson(Person(centroid = ByteArray(8), faceCount = 2, name = "Bo"))+ db.faceDao().insertPhotoFaces(+ ids.map { pid ->+ PhotoFace(+ photoId = pid, clusterId = personId, embedding = ByteArray(8), clusterable = true,+ left = 0f, top = 0f, right = 0.5f, bottom = 0.5f, srcWidth = 100, srcHeight = 100,+ )+ },+ )+ composeRule.setContent { PeoplePage(NavBackStack(arrayOf(Route.Gallery)), vm) }+ composeRule.waitForIdle()+ // FaceRecognizer models are not installed in the unit-test sandbox, so the+ // binder must reach the model-missing branch rather than crash.+ composeRule.onNodeWithText(str(R.string.people_model_missing)).assertIsDisplayed()+ }++ @Test fun wallpaperPreviewReportsSnapshotAndCoverMin() {+ val bitmap = Bitmap.createBitmap(200, 100, Bitmap.Config.ARGB_8888)+ var snapshot: PreviewSnapshot? = null+ var coverMin: Float? = null+ val scale = mutableStateOf(1f)+ val offset = mutableStateOf(Offset.Zero)+ composeRule.setContent {+ WallpaperPreview(+ bitmap = bitmap, loadState = WallpaperLoadState.Loaded, targetAspect = 0.5f,+ zoomScale = 1f, zoomOffset = Offset.Zero,+ currentScale = scale, currentOffset = offset,+ onZoomChange = { _, _ -> }, onCoverMin = { coverMin = it },+ onSnapshot = { snapshot = it },+ )+ }+ composeRule.waitForIdle()+ assertNotNull(snapshot)+ assertTrue(snapshot!!.baseW > 0f && snapshot.viewportH > 0f)+ assertNotNull(coverMin)+ }++ @Test fun wallpaperPreviewShowsLoading() {+ val scaleState = mutableStateOf(1f)+ val offsetState = mutableStateOf(Offset.Zero)+ composeRule.setContent {+ WallpaperPreview(+ bitmap = null, loadState = WallpaperLoadState.Loading, targetAspect = 0.5f,+ zoomScale = 1f, zoomOffset = Offset.Zero,+ currentScale = scaleState, currentOffset = offsetState,+ onZoomChange = { _, _ -> }, onCoverMin = {}, onSnapshot = {},+ )+ }+ composeRule.waitForIdle()+ }++ @Test fun wallpaperPreviewShowsFailure() {+ val scaleState = mutableStateOf(1f)+ val offsetState = mutableStateOf(Offset.Zero)+ composeRule.setContent {+ WallpaperPreview(+ bitmap = null, loadState = WallpaperLoadState.Failed, targetAspect = 0.5f,+ zoomScale = 1f, zoomOffset = Offset.Zero,+ currentScale = scaleState, currentOffset = offsetState,+ onZoomChange = { _, _ -> }, onCoverMin = {}, onSnapshot = {},+ )+ }+ composeRule.onNodeWithText(str(R.string.wallpaper_load_failed)).assertIsDisplayed()+ }++ private class FakePhotos(db: PhotoDatabase) : PhotoStore {+ private val dao = db.photoDao()+ override fun getAllFlow(): Flow<List<Photo>> = dao.getAllFlow()+ override fun getOCRCountFlow(): Flow<Int> = dao.getOCRCountFlow()+ override fun getClipCountFlow(): Flow<Int> = dao.getClipCountFlow()+ override fun getFaceScannedCountFlow(): Flow<Int> = dao.getFaceScannedCountFlow()+ override fun getIndexTargetCountFlow(): Flow<Int> = dao.getIndexTargetCountFlow()+ override suspend fun getByUri(uri: String): List<Photo> = dao.getByUri(uri)+ override suspend fun searchPhotos(query: String): List<Photo> = dao.searchPhotos(query)+ override suspend fun delete(value: Photo): Int = dao.delete(value)+ override suspend fun setTrashed(id: Long) = dao.setTrashed(id)+ override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+ override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)+ override suspend fun getAll(): List<Photo> = dao.getAll()+ }++ private class FakeScans(db: PhotoDatabase) : PhotoScanStore {+ private val dao = db.photoScanDao()+ override suspend fun getClipEmbeddings() = dao.getClipEmbeddings()+ }++ private class FakeFaces(db: PhotoDatabase) : FaceStore {+ private val dao = db.faceDao()+ override fun personsFlow(): Flow<List<com.vayunmathur.photos.data.Person>> = dao.personsFlow()+ override fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> = dao.faceGeometryFlow()+ override suspend fun photoIdsForCluster(clusterId: Long) = dao.photoIdsForCluster(clusterId)+ override suspend fun setPersonName(id: Long, name: String?) = dao.setPersonName(id, name)+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PixelTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PixelTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PixelTest.ktnew file mode 100644index 0000000000..7623a0e750--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2PixelTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.photos.util++import android.app.Application+import android.graphics.Bitmap+import android.graphics.Color+import androidx.compose.ui.geometry.Rect+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.BitmapReference+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.PerspectiveCorners+import com.vayunmathur.photos.data.PhotosRepository+import com.vayunmathur.photos.data.PixelLayer+import com.vayunmathur.photos.data.Selection+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode++/** Cov-c2: PixelEditController geometry, flip, transform and selection blends. */+@GraphicsMode(GraphicsMode.Mode.NATIVE)+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2PixelTest {++ private val app: Application+ get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ .applicationContext as Application++ private fun twoTone(): Bitmap {+ val bmp = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888)+ for (x in 0 until 16) for (y in 0 until 16) {+ bmp.setPixel(x, y, if (x < 8) Color.RED else Color.BLUE)+ }+ return bmp+ }++ private fun vmWithLayer(): PhotoEditViewModel {+ val vm = PhotoEditViewModel(app, PhotosRepository.get(app))+ vm.updateDocument(pushUndo = false) {+ EditDocument(canvasWidth = 16, canvasHeight = 16)+ .addLayer(PixelLayer(bitmapRef = BitmapReference(twoTone()), name = "base"))+ }+ return vm+ }++ private fun awaitVm(check: () -> Boolean) {+ val deadline = System.currentTimeMillis() + 10_000+ while (System.currentTimeMillis() < deadline) {+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper())+ .idleFor(200, java.util.concurrent.TimeUnit.MILLISECONDS)+ if (check()) return+ Thread.sleep(50)+ }+ assertTrue(check(), "VM condition not met")+ }++ private fun activeBitmap(vm: PhotoEditViewModel): Bitmap =+ (vm.document.value.activeLayer as PixelLayer).bitmapRef.bitmap++ @Test fun geometrySettersUpdateDocument() {+ val vm = vmWithLayer()+ vm.pixel.rotate(30f)+ assertEquals(30f, vm.document.value.rotation)+ vm.pixel.rotate(15f)+ assertEquals(45f, vm.document.value.rotation)+ vm.pixel.setRotation(10f)+ assertEquals(10f, vm.document.value.rotation)+ vm.pixel.setCropRect(Rect(0f, 0f, 0.5f, 0.5f))+ assertEquals(0.5f, vm.document.value.cropRect.right)+ val corners = PerspectiveCorners(+ topLeft = 0.1f to 0.1f, topRight = 0.9f to 0.1f,+ bottomLeft = 0.1f to 0.9f, bottomRight = 0.9f to 0.9f,+ )+ vm.pixel.setPerspective(corners)+ assertEquals(corners, vm.document.value.perspectiveCorners)+ vm.pixel.setCroppingPreview(true)+ assertTrue(vm.croppingPreview)+ }++ @Test fun flipActiveLayerMirrorsPixels() {+ val vm = vmWithLayer()+ assertEquals(Color.RED, activeBitmap(vm).getPixel(0, 0))+ vm.pixel.flipActiveLayer(horizontal = true)+ awaitVm { activeBitmap(vm).getPixel(0, 0) == Color.BLUE }+ vm.pixel.flipActiveLayer(horizontal = false)+ awaitVm { activeBitmap(vm).getPixel(0, 0) == Color.BLUE }+ }++ @Test fun transformActiveLayerWarps() {+ val vm = vmWithLayer()+ val corners = PerspectiveCorners(+ topLeft = 0.2f to 0.2f, topRight = 0.8f to 0.2f,+ bottomLeft = 0.2f to 0.8f, bottomRight = 0.8f to 0.8f,+ )+ vm.pixel.transformActiveLayer(corners)+ // Identity corners are a no-op (returns before launching work).+ vm.pixel.transformActiveLayer(PerspectiveCorners())+ awaitVm { activeBitmap(vm).width == 16 }+ }++ @Test fun applyToActiveLayerReplacesPixels() {+ val vm = vmWithLayer()+ vm.pixel.applyToActivePixelLayer {+ Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.GREEN) }+ }+ awaitVm { activeBitmap(vm).getPixel(0, 0) == Color.GREEN }+ }++ @Test fun applyWithSelectionBlendsAndContentAwareFill() {+ val vm = vmWithLayer()+ // Left half selected: edits apply there, right half keeps the original.+ val mask = FloatArray(16 * 16) { i -> if (i % 16 < 8) 1f else 0f }+ vm.setSelection(Selection(mask, 16, 16))+ vm.pixel.applyToActivePixelLayer {+ Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888).apply { eraseColor(Color.GREEN) }+ }+ awaitVm { activeBitmap(vm).getPixel(0, 0) == Color.GREEN }+ assertEquals(Color.BLUE, activeBitmap(vm).getPixel(15, 0))++ vm.pixel.contentAwareFillSelection()+ awaitVm { activeBitmap(vm).width == 16 }+ // Clearing the selection makes content-aware fill a no-op.+ vm.setSelection(null)+ vm.pixel.contentAwareFillSelection()+ }+}
photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2VmTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2VmTest.kt b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2VmTest.ktnew file mode 100644index 0000000000..c5ad17ac8d--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/util/PhotosCovC2VmTest.kt@@ -0,0 +1,180 @@+package com.vayunmathur.photos.util++import android.app.Application+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Person+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PhotoDatabase+import com.vayunmathur.photos.data.PhotoFace+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.launch+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeoutOrNull+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/** Cov-c2: GalleryViewModel search, trash/delete, people and album-cover flows. */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosCovC2VmTest {++ private val context = ApplicationProvider.getApplicationContext<android.content.Context>()+ private val app = context.applicationContext as Application+ private lateinit var db: PhotoDatabase+ private var nextId = 9000L++ private fun photo(name: String, date: Long, album: String? = null, trashed: Boolean = false, fav: Boolean = false) =+ Photo(+ id = nextId++, name = name, uri = "content://media/$name", date = date,+ width = 100, height = 100, dateModified = date, exifSet = true,+ lat = null, long = null, videoData = null, panoData = null,+ isTrashed = trashed, album = album, isFavorite = fav,+ )++ private fun vm(): GalleryViewModel {+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ db = Room.inMemoryDatabaseBuilder(context, PhotoDatabase::class.java)+ .allowMainThreadQueries().build()+ return GalleryViewModel(app, FakePhotos(db), FakeScans(db), FakeFaces(db)).also { it.runSyncHook = {} }+ }++ private suspend fun awaitTrue(timeoutMs: Long = 5_000, check: suspend () -> Boolean) {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < deadline) {+ // Robolectric's main looper is paused; viewModelScope work needs it idled.+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idleFor(600, java.util.concurrent.TimeUnit.MILLISECONDS)+ if (check()) return+ Thread.sleep(50)+ }+ org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()).idle()+ assertTrue(check(), "condition not met within ${timeoutMs}ms")+ }++ private fun subscribe(vm: GalleryViewModel) {+ val scope = kotlinx.coroutines.CoroutineScope(kotlinx.coroutines.Dispatchers.Default)+ scope.launch {+ launch { vm.photos.collect {} }+ launch { vm.albums.collect {} }+ launch { vm.people.collect {} }+ launch { vm.favorites.collect {} }+ launch { vm.faceBoxesByPhoto.collect {} }+ launch { vm.faceCountByPhoto.collect {} }+ launch { vm.searchResults.collect {} }+ launch { vm.indexTargetCount.collect {} }+ }+ }++ @Test fun searchFindsByNameAndClears() = runBlocking<Unit> {+ val vm = vm().also { subscribe(it) }+ db.photoDao().upsertAll(+ listOf(photo("cov-beach-day", 300L), photo("cov-mountain", 200L), photo("cov-beach-trash", 100L, trashed = true)),+ )+ awaitTrue { vm.photos.value.size == 3 }+ vm.setSearchQuery("beach")+ awaitTrue { vm.searchResults.value.isNotEmpty() }+ assertEquals(listOf("cov-beach-day"), vm.searchResults.value.map { it.name })+ vm.setSearchQuery("")+ awaitTrue { vm.searchResults.value.isEmpty() }+ }++ @Test fun deleteAndTrashUpdateDatabase() = runBlocking<Unit> {+ val vm = vm().also { subscribe(it) }+ val a = photo("cov-del-a", 300L)+ val b = photo("cov-del-b", 200L)+ db.photoDao().upsertAll(listOf(a, b))+ awaitTrue { vm.photos.value.size == 2 }+ vm.trashPhotoLocally(a)+ awaitTrue { db.photoDao().getAll().first { it.id == a.id }.isTrashed }+ vm.deletePhoto(b)+ awaitTrue { db.photoDao().getAll().none { it.id == b.id } }+ }++ @Test fun peopleFavoritesAndFaceBoxesFlows() = runBlocking<Unit> {+ val vm = vm().also { subscribe(it) }+ val a = photo("cov-ppl-a", 300L, fav = true)+ val b = photo("cov-ppl-b", 200L)+ db.photoDao().upsertAll(listOf(a, b))+ val ids = db.photoDao().getAll().map { it.id }+ val personId = db.faceDao().insertPerson(Person(centroid = ByteArray(8), faceCount = 2, name = "Ada"))+ db.faceDao().insertPhotoFaces(+ ids.map { pid ->+ PhotoFace(+ photoId = pid, clusterId = personId, embedding = ByteArray(8), clusterable = true,+ left = 0.1f, top = 0.1f, right = 0.6f, bottom = 0.6f, srcWidth = 100, srcHeight = 100,+ )+ },+ )+ awaitTrue { vm.people.value.any { it.name == "Ada" } }+ assertEquals(2, vm.people.value.first { it.name == "Ada" }.photos.size)+ awaitTrue { vm.favorites.value.map { it.name } == listOf("cov-ppl-a") }+ awaitTrue { vm.faceCountByPhoto.value.values.sum() == 2 }+ awaitTrue { vm.faceBoxesByPhoto.value.isNotEmpty() }+ val clusterPhotos = vm.photosForCluster(personId)+ assertEquals(2, clusterPhotos.size)+ assertTrue(vm.photosForCluster(999_999L).isEmpty())+ vm.setPersonName(personId, "Grace")+ awaitTrue { db.faceDao().personsFlow().first().first { it.id == personId }.name == "Grace" }+ }++ @Test fun albumCoverAndMoveBookkeeping() = runBlocking<Unit> {+ val vm = vm().also { subscribe(it) }+ val a = photo("cov-alb-a", 300L, album = "CovAlbum")+ val b = photo("cov-alb-b", 200L, album = "CovAlbum")+ db.photoDao().upsertAll(listOf(a, b))+ awaitTrue { vm.albums.value.any { it.name == "CovAlbum" && it.coverPhoto.id == a.id } }+ vm.setAlbumCover("CovAlbum", b.id)+ awaitTrue { vm.albums.value.first { it.name == "CovAlbum" }.coverPhoto.id == b.id }+ assertFalse(vm.consumePendingMove())+ vm.requestAlbumMove(emptyList(), "Elsewhere")+ assertTrue(vm.consumePendingMove())+ assertFalse(vm.consumePendingMove())+ vm.moveToAlbum(emptyList(), "Nowhere")+ }++ @Test fun runSyncUsesHookAndCountsFlow() = runBlocking<Unit> {+ val vm = vm().also { subscribe(it) }+ db.photoDao().upsertAll(listOf(photo("cov-cnt", 100L)))+ var syncs = 0+ vm.runSyncHook = { syncs++ }+ vm.runSync()+ assertEquals(1, syncs)+ awaitTrue { vm.indexTargetCount.value == 1 }+ }++ private class FakePhotos(db: PhotoDatabase) : PhotoStore {+ private val dao = db.photoDao()+ override fun getAllFlow(): Flow<List<Photo>> = dao.getAllFlow()+ override fun getOCRCountFlow(): Flow<Int> = dao.getOCRCountFlow()+ override fun getClipCountFlow(): Flow<Int> = dao.getClipCountFlow()+ override fun getFaceScannedCountFlow(): Flow<Int> = dao.getFaceScannedCountFlow()+ override fun getIndexTargetCountFlow(): Flow<Int> = dao.getIndexTargetCountFlow()+ override suspend fun getByUri(uri: String): List<Photo> = dao.getByUri(uri)+ override suspend fun searchPhotos(query: String): List<Photo> = dao.searchPhotos(query)+ override suspend fun delete(value: Photo): Int = dao.delete(value)+ override suspend fun setTrashed(id: Long) = dao.setTrashed(id)+ override suspend fun setAlbum(ids: List<Long>, album: String?) = dao.setAlbum(ids, album)+ override suspend fun setFavorite(ids: List<Long>, value: Boolean) = dao.setFavorite(ids, value)+ override suspend fun getAll(): List<Photo> = dao.getAll()+ }++ private class FakeScans(db: PhotoDatabase) : PhotoScanStore {+ private val dao = db.photoScanDao()+ override suspend fun getClipEmbeddings() = dao.getClipEmbeddings()+ }++ private class FakeFaces(db: PhotoDatabase) : FaceStore {+ private val dao = db.faceDao()+ override fun personsFlow(): Flow<List<Person>> = dao.personsFlow()+ override fun faceGeometryFlow(): Flow<List<com.vayunmathur.photos.data.FaceGeometry>> = dao.faceGeometryFlow()+ override suspend fun photoIdsForCluster(clusterId: Long) = dao.photoIdsForCluster(clusterId)+ override suspend fun setPersonName(id: Long, name: String?) = dao.setPersonName(id, name)+ }+}