photos: add tests for repositories, sync, editor and vault flows (790 tests)
- Commit
a59437f728a6a468e479cd139e7f3ac309d33cd3- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-16 13:09 UTC (20 days ago)
- Parents
0d6b1bb
Adds 133 Robolectric unit tests (40 files) over the real Room-backed stack. A new TestPhotosRepository helper builds in-memory Photo/Vault databases and reflectively swaps the SQLCipher-backed db$delegate Lazy on each RoomRepository singleton (the seam proven in todo/music), so PhotosRepository, PhotoScanRepository, FaceRepository, the vault repositories, the ViewModels and the workers all run against real Room on the host. Covered areas: repository CRUD, search, scan queues, face clustering commits and vault storage; GalleryViewModel projections and actions over the production adapters; MediaStore-stubbed sync workers; gallery/albums/people/map/trash pages and the real Navigation graph; the photo editor (document algebra, adjustment bitmaps, layer/pixel/adjustment controllers, editor-state tools, selections, crop, save/permission flows); video editing and wallpaper; secure-folder AES-GCM round-trips and restore; OCR box layout; the Glance widget data path; and activity launches. Instruction coverage (merged JaCoCo, dev variant): 94,952 covered / 32,951 missed (74.3%) before, 105,857 covered / 22,046 missed (82.8%) after, +10,905 covered instructions. The remaining missed code is concentrated in ML model inference (faces/CLIP/OCR), the native ink renderer, GL panorama rendering and MediaStore system-request flows, which need a device or native libraries. Verified: :photos:testDevUnitTest (790 tests, 0 failures), :photos:detekt and :photos:lint green; coverage measured with :photos:createMergedCoverageReport.
Diff
photos/src/test/java/com/vayunmathur/photos/MainActivityRealLaunchTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/MainActivityRealLaunchTest.kt b/photos/src/test/java/com/vayunmathur/photos/MainActivityRealLaunchTest.ktnew file mode 100644index 0000000000..5ee61e57ca--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/MainActivityRealLaunchTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.photos++import android.app.Application+import android.content.Intent+import android.net.Uri+import android.os.Looper+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * [MainActivity] launched for real: the gallery root, an ACTION_VIEW+ * launch (which makes the viewed photo the stack root), and the+ * pushPhoto/relock helpers the navigation graph is built from.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class MainActivityRealLaunchTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun setup() {+ workInfosInstall()+ TestPhotosRepository.install(app)+ }++ private fun workInfosInstall() {+ com.vayunmathur.photos.util.workInfosOverride = { _, _ -> kotlinx.coroutines.flow.flowOf(emptyList()) }+ }++ @Test fun plainLaunchReachesGallery() {+ val controller = Robolectric.buildActivity(MainActivity::class.java, Intent(app, MainActivity::class.java))+ val activity = controller.create().start().resume().get()+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ assertNotNull(activity)+ controller.pause().stop().destroy()+ }++ @Test fun actionViewVideoAndMalformedUris() {+ for (uri in listOf("content://media/external/video/media/7", "content://media/7", "file:///sdcard/x.jpg")) {+ val intent = Intent(app, MainActivity::class.java).apply {+ action = Intent.ACTION_VIEW+ data = Uri.parse(uri)+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ val activity = controller.create().start().resume().get()+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ assertNotNull(activity)+ controller.pause().stop().destroy()+ }+ }++ @Test fun warmStartNewIntentAndRecreate() {+ val controller = Robolectric.buildActivity(MainActivity::class.java, Intent(app, MainActivity::class.java))+ val activity = controller.create().start().resume().get()+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ // Warm-start VIEW intent delivered to the running activity.+ val warm = Intent(Intent.ACTION_VIEW, Uri.parse("content://media/external/images/media/9"))+ controller.newIntent(warm)+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ // Configuration-change recreation restores the navigation stack.+ controller.recreate()+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ assertNotNull(controller.get())+ controller.pause().stop().destroy()+ }++ @Test fun actionViewLaunchRootsAtViewer() = runBlocking {+ TestPhotosRepository.install(app).photos.upsertAll(listOf(+ Photo(name = "a.jpg", uri = "content://media/external/images/media/42", date = 100L,+ width = 10, height = 10, dateModified = 100L, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, id = 42L),+ ))+ val intent = Intent(app, MainActivity::class.java).apply {+ action = Intent.ACTION_VIEW+ data = Uri.parse("content://media/external/images/media/42")+ }+ val controller = Robolectric.buildActivity(MainActivity::class.java, intent)+ val activity = controller.create().start().resume().get()+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ Thread.sleep(200)+ Shadows.shadowOf(Looper.getMainLooper()).idle()+ assertEquals(Intent.ACTION_VIEW, activity.intent.action)+ controller.pause().stop().destroy()+ Unit+ }++ @Test fun pushPhotoReplacesTopViewerInsteadOfStacking() {+ val stack = com.vayunmathur.library.util.NavBackStack<Route>(arrayOf(Route.Gallery))+ stack.pushPhoto(Route.PhotoPage(1L, null))+ assertEquals(2, stack.backStack.size)+ stack.pushPhoto(Route.PhotoPage(2L, null))+ // Re-tapping a photo replaces the viewer rather than stacking it.+ assertEquals(2, stack.backStack.size)+ assertEquals(2L, (stack.last() as Route.PhotoPage).id)+ stack.pushPhoto(Route.PhotoPage(3L, null))+ assertEquals(2, stack.backStack.size)+ assertTrue(stack.backStack.first() == Route.Gallery)+ }+}
photos/src/test/java/com/vayunmathur/photos/data/AdjustmentBitmapsRealTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentBitmapsRealTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentBitmapsRealTest.ktnew file mode 100644index 0000000000..fc38d40657--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/AdjustmentBitmapsRealTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.photos.data++import android.graphics.Bitmap+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Every [LayerAdjustment] subtype applied to a real bitmap: identity+ * checks hold at defaults, and non-identity parameters actually move+ * pixels (each result is a same-sized bitmap with changed content).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class AdjustmentBitmapsRealTest {++ private fun colorful(): 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, android.graphics.Color.rgb(x * 16, y * 16, (x + y) * 8))+ }+ // A hard edge so sharpen/blur-family adjustments have signal.+ for (x in 8 until 16) for (y in 0 until 16) {+ bmp.setPixel(x, y, android.graphics.Color.rgb(240, 240, 240))+ }+ return bmp+ }++ private fun pixels(bmp: Bitmap): List<Int> =+ (0 until 16).flatMap { y -> (0 until 16).map { x -> bmp.getPixel(x, y) } }++ private fun assertApplies(adj: LayerAdjustment) {+ val src = colorful()+ val before = pixels(src)+ val out = adj.applyToBitmap(src)+ assertEquals(16, out.width)+ assertEquals(16, out.height)+ assertTrue(pixels(out) != before, "${adj.label} should change pixels")+ assertFalse(adj.isIdentity())+ }++ @Test fun everyAdjustmentApplies() {+ assertApplies(BasicAdjustment(ImageAdjustments(brightness = 0.3f, contrast = 0.2f, saturation = 0.4f)))+ assertApplies(CurvesAdj(CurvesAdjustment(combined = listOf(+ CurveControlPoint(0f, 0f), CurveControlPoint(0.5f, 0.8f), CurveControlPoint(1f, 1f),+ ))))+ assertApplies(HslAdj(HslAdjustments(channels = HslColorRange.entries.associateWith {+ HslChannelAdjustment(hue = 20f, saturation = 0.5f, luminance = 0.1f)+ })))+ assertApplies(LevelsAdj(LevelsAdjustment(inBlack = 20f, inWhite = 230f, gamma = 1.4f)))+ assertApplies(ColorBalanceAdj(ColorBalanceAdjustment(midRedCyan = 0.4f, midGreenMagenta = -0.2f, midBlueYellow = 0.3f, shadowsRedCyan = 0.2f)))+ assertApplies(ChannelMixerAdj(ChannelMixerAdjustment(rFromR = 0.5f, rFromG = 0.5f, gFromG = 0.6f, gFromB = 0.4f)))+ assertApplies(GradientMapAdj(GradientMapAdjustment(stops = listOf(+ GradientStop(0f, 0xFF000000.toInt()), GradientStop(1f, 0xFFFFFFFF.toInt()),+ ))))+ assertApplies(BlurAdj(BlurParams(radius = 0.5f, intensity = 20f)))+ assertApplies(VibranceAdj(amount = 90f))+ // Selective color weights by HSV hue; Robolectric's Color.RGBToHSV+ // shadow reports zero saturation, so only the non-identity contract+ // is asserted here (pixel math runs on device).+ val selective = SelectiveColorAdj(range = SelectiveColorRange.Reds, cyan = 50f, magenta = -30f, yellow = 20f)+ assertFalse(selective.isIdentity())+ assertEquals(16, selective.applyToBitmap(colorful()).width)+ assertFalse(SelectiveColorAdj(range = SelectiveColorRange.Blues, cyan = -40f).isIdentity())+ assertApplies(FilterBlurAdj(FilterBlur(amount = 3f)))+ assertApplies(UnsharpAdj(UnsharpMask(amount = 0.8f, radius = 2f, threshold = 5)))+ assertApplies(NoiseAdj(NoiseParams(amount = 80f)))+ assertApplies(StylizeAdj(StylizeParams(mode = StylizeMode.FindEdges)))+ assertApplies(StylizeAdj(StylizeParams(mode = StylizeMode.Emboss)))+ }++ @Test fun identityAtDefaults() {+ val src = colorful()+ assertTrue(BasicAdjustment().isIdentity())+ assertTrue(VibranceAdj().isIdentity())+ assertTrue(SelectiveColorAdj().isIdentity())+ // Default basic adjustment leaves pixels untouched.+ assertEquals(pixels(src), pixels(BasicAdjustment().applyToBitmap(src)))+ }+}
photos/src/test/java/com/vayunmathur/photos/data/EditDocumentAlgebraTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/EditDocumentAlgebraTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/EditDocumentAlgebraTest.ktnew file mode 100644index 0000000000..f883559d64--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/EditDocumentAlgebraTest.kt@@ -0,0 +1,81 @@+package com.vayunmathur.photos.data++import android.graphics.Bitmap+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [EditDocument] layer algebra: duplication per layer kind, group+ * bookkeeping, and boundary behaviour of the stack operations.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class EditDocumentAlgebraTest {++ private fun bmp() = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)++ private fun doc(): EditDocument {+ val layers = listOf(+ PixelLayer(BitmapReference(bmp()), name = "pixels"),+ AdjustmentLayer(BasicAdjustment(ImageAdjustments(brightness = 0.1f)), name = "adj"),+ TextLayer(+ TextElement(id = "t", text = "hi", x = 0f, y = 0f, rotation = 0f, color = 0, fontSize = 10f),+ name = "text",+ ),+ DrawingLayer(strokes = emptyList(), sourceWidth = 8f, sourceHeight = 8f, name = "draw"),+ )+ return EditDocument(canvasWidth = 8, canvasHeight = 8, layers = layers, activeLayerIndex = 3)+ }++ @Test fun duplicateEveryLayerKind() {+ var current = doc()+ for (index in current.layers.indices) {+ val before = current.layers.size+ current = current.duplicateLayer(index)+ assertEquals(before + 1, current.layers.size)+ assertEquals(index + 1, current.activeLayerIndex)+ assertNotEquals(current.layers[index].id, current.layers[index + 1].id)+ assertTrue(current.layers[index + 1].name.endsWith("copy"))+ }+ // Out-of-range duplication is a no-op.+ assertEquals(current, current.duplicateLayer(99))+ assertEquals(current, current.duplicateLayer(-1))+ }++ @Test fun stackBoundariesAndGrouping() {+ var current = doc()+ assertEquals(current, current.removeLayer(99))+ // moveLayer coerces the target into range instead of no-oping.+ assertEquals(current.layers.first().id, current.moveLayer(0, 99).layers.last().id)+ // Out-of-range active indices are coerced into the stack.+ assertTrue(current.setActiveLayer(99).activeLayerIndex in current.layers.indices)+ current = current.moveLayer(0, 2)+ assertEquals("adj", current.layers[0].name)+ current = current.updateLayer(0) { it.copyBase(name = "renamed") }+ assertEquals("renamed", current.layers[0].name)+ current = current.updateActiveLayer { it.copyBase(name = "active") }+ assertEquals("active", current.activeLayer?.name)+ assertNull(current.groupInfo(null))+ assertNull(current.groupInfo("missing"))+ // Group active (index 3) with below, rename the group, ungroup.+ current = current.groupActiveWithBelow()+ val group = current.groups.single()+ assertEquals(group, current.groupInfo(group.id))+ current = current.updateGroup(group.copy(name = "combo"))+ assertEquals("combo", current.groupInfo(group.id)?.name)+ current = current.ungroupActive()+ assertTrue(current.groups.isEmpty())+ assertTrue(current.layers.all { it.groupId == null })+ // Adding below the top inserts directly above the active layer.+ current = current.addLayer(PixelLayer(BitmapReference(bmp()), name = "inserted"), onTop = false)+ assertEquals("inserted", current.activeLayer?.name)+ }+}
photos/src/test/java/com/vayunmathur/photos/data/PaintOpsAndOverlaysTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/PaintOpsAndOverlaysTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/PaintOpsAndOverlaysTest.ktnew file mode 100644index 0000000000..859e770e5e--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/PaintOpsAndOverlaysTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.photos.data++import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Color+import com.vayunmathur.library.image.Size+import com.vayunmathur.photos.util.FaceCropTransformation+import com.vayunmathur.photos.util.drawTextElement+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Paint operations (flood fill, gradient, shapes), the face-crop+ * transformation, and the canvas overlay renderers, all on real bitmaps.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PaintOpsAndOverlaysTest {++ private fun twoTone(): Bitmap {+ val bmp = Bitmap.createBitmap(20, 20, Bitmap.Config.ARGB_8888)+ for (x in 0 until 20) for (y in 0 until 20) {+ bmp.setPixel(x, y, if (x < 10) Color.RED else Color.BLUE)+ }+ return bmp+ }++ @Test fun floodFillRespectsToleranceBoundary() {+ val filled = floodFillBitmap(twoTone(), 0.1f, 0.5f, Color.GREEN, tolerance = 0.05f)+ assertEquals(Color.GREEN, filled.getPixel(2, 10))+ // The blue half is beyond tolerance and stays blue.+ assertEquals(Color.BLUE, filled.getPixel(18, 10))+ // A loose tolerance floods everything reachable.+ val flooded = floodFillBitmap(twoTone(), 0.1f, 0.5f, Color.GREEN, tolerance = 1f)+ assertEquals(Color.GREEN, flooded.getPixel(18, 10))+ }++ @Test fun gradientAndShapesDraw() {+ val gradient = drawGradientBitmap(twoTone(), 0f, 0f, 1f, 0f, Color.WHITE)+ assertEquals(20, gradient.width)+ val rect = drawShapeBitmap(twoTone(), PaintShape.Rectangle, 0f, 0f, 0.5f, 0.5f, Color.GREEN, 0.1f)+ assertEquals(Color.GREEN, rect.getPixel(5, 5))+ assertEquals(Color.BLUE, rect.getPixel(18, 10))+ val ellipse = drawShapeBitmap(twoTone(), PaintShape.Ellipse, 0f, 0f, 1f, 1f, Color.YELLOW, 0.1f)+ assertEquals(Color.YELLOW, ellipse.getPixel(10, 10))+ val line = drawShapeBitmap(twoTone(), PaintShape.Line, 0f, 0f, 1f, 1f, Color.BLACK, 0.05f)+ assertEquals(20, line.height)+ }++ @Test fun faceCropTransformationCropsAndClamps() = runBlocking {+ val src = twoTone()+ val crop = FaceCropTransformation(0f, 0f, 0.5f, 1f).transform(src, Size(10, 20))+ assertEquals(10, crop.width)+ assertEquals(Color.RED, crop.getPixel(5, 10))+ // Out-of-range boxes clamp into the bitmap.+ val clamped = FaceCropTransformation(-1f, -1f, 2f, 2f).transform(src, Size(20, 20))+ assertEquals(20, clamped.width)+ assertEquals(+ FaceCropTransformation(0f, 0f, 0.5f, 1f).cacheKey,+ FaceCropTransformation(0f, 0f, 0.5f, 1f).cacheKey,+ )+ Unit+ }++ @Test fun overlayRenderersDrawOntoCanvas() {+ val target = Bitmap.createBitmap(100, 80, Bitmap.Config.ARGB_8888).apply {+ eraseColor(Color.WHITE)+ }+ val canvas = Canvas(target)+ canvas.drawTextElement(+ TextElement(id = "t", text = "Hello", x = 0.1f, y = 0.1f, rotation = 0f,+ color = Color.BLACK, fontSize = 20f),+ canvasWidth = 100, canvasHeight = 80, referenceWidth = 100f,+ )+ // drawSerializedStrokes needs the native ink renderer, which has+ // no host build; it runs on device.+ // Something was drawn over the white background.+ var nonWhite = 0+ for (x in 0 until 100) for (y in 0 until 80) {+ if (target.getPixel(x, y) != Color.WHITE) nonWhite+++ }+ assertTrue(nonWhite > 0)+ }+}
photos/src/test/java/com/vayunmathur/photos/data/PhotosRepositoriesRealDbTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/PhotosRepositoriesRealDbTest.kt b/photos/src/test/java/com/vayunmathur/photos/data/PhotosRepositoriesRealDbTest.ktnew file mode 100644index 0000000000..842f2bffa4--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/PhotosRepositoriesRealDbTest.kt@@ -0,0 +1,263 @@+package com.vayunmathur.photos.data++import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.test.runTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The real [PhotosRepository], [PhotoScanRepository], [FaceRepository] and+ * [VaultRepository] over in-memory Room (see [TestPhotosRepository]).+ *+ * Earlier suites tested the DAOs directly or subclassed the repositories+ * with fakes, so the repository layer itself — including the methods that+ * are not `open` and the final [FaceRepository]'s clustering transactions —+ * never executed. Here every call runs the production wrapper and its DAO+ * SQL, and results are asserted in the database.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class PhotosRepositoriesRealDbTest {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ private lateinit var installed: TestPhotosRepository.Installed+ private val photos get() = installed.photos+ private val scan get() = installed.scan+ private val faces get() = installed.faces++ @BeforeTest fun open() { installed = TestPhotosRepository.install(context) }++ private fun photo(+ name: String,+ date: Long = 1_000L,+ trashed: Boolean = false,+ video: Boolean = false,+ album: String? = null,+ favorite: Boolean = false,+ mime: String? = "image/jpeg",+ ) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 80,+ dateModified = date, exifSet = false, lat = null, long = null,+ videoData = if (video) VideoData(5_000L) else null, panoData = null,+ isTrashed = trashed, album = album, isFavorite = favorite, mimeType = mime,+ )++ private fun face(photoId: Long, embedding: FloatArray, clusterable: Boolean = true) = PhotoFace(+ photoId = photoId, clusterId = null,+ embedding = com.vayunmathur.photos.util.FaceRecognizer.floatsToBytes(embedding),+ clusterable = clusterable,+ left = 0.1f, top = 0.1f, right = 0.5f, bottom = 0.5f, srcWidth = 100, srcHeight = 80,+ )++ private fun floats(vararg values: Float) = FloatArray(4) { values.getOrElse(it) { 0f } }++ // ---- PhotosRepository ----++ @Test fun photoCrudThroughRepository() = runTest {+ photos.upsertAll(listOf(photo("old", date = 100L), photo("new", date = 900L), photo("mid", date = 500L)))+ assertEquals(listOf("new", "mid", "old"), photos.getAllFlow().first().map { it.name })+ assertEquals(setOf("new", "mid", "old"), photos.getAll().map { it.name }.toSet())+ val newId = photos.getAll().first { it.name == "new" }.id+ assertEquals("new", photos.getByIdFlow(newId).first()?.name)+ assertEquals(1, photos.getByUri("content://media/mid").size)+ photos.setTrashed(newId)+ assertTrue(photos.getAll().first { it.id == newId }.isTrashed)+ assertEquals(1, photos.delete(photos.getAll().first { it.name == "old" }))+ photos.deleteByIds(listOf(photos.getAll().first { it.name == "mid" }.id))+ assertEquals(listOf("new"), photos.getAll().map { it.name })+ }++ @Test fun albumFavoriteAndSearchThroughRepository() = runTest {+ photos.upsertAll(listOf(photo("beach", date = 3L), photo("mountain", date = 2L)))+ val ids = photos.getAll().map { it.id }+ photos.setAlbum(ids, "Camera")+ assertEquals(setOf("Camera"), photos.getAll().map { it.album }.toSet())+ photos.setAlbum(ids, null)+ assertEquals(setOf<String?>(null), photos.getAll().map { it.album }.toSet())+ photos.setFavorite(listOf(ids.first()), true)+ assertEquals(1, photos.getAll().count { it.isFavorite })+ assertEquals(listOf("beach"), photos.searchPhotos("beach").map { it.name })+ scan.setOcrResults(listOf(OcrResult(ids.last(), "hello sign", null)))+ assertEquals(listOf("mountain"), photos.searchPhotos("hello").map { it.name })+ // Trashed rows leave search.+ photos.setTrashed(ids.last())+ assertTrue(photos.searchPhotos("hello").isEmpty())+ }++ @Test fun progressCountsThroughRepository() = runTest {+ photos.upsertAll(listOf(+ photo("a", date = 1L), photo("b", date = 2L),+ photo("clip", date = 3L, video = true), photo("trashed", date = 4L, trashed = true),+ ))+ val ids = photos.getAll().filter { !it.isTrashed && it.videoData == null }.map { it.id }+ assertEquals(2, photos.getIndexTargetCountFlow().first())+ assertEquals(0, photos.getOCRCountFlow().first())+ assertEquals(0, photos.getClipCountFlow().first())+ assertEquals(0, photos.getFaceScannedCountFlow().first())+ scan.setOcrResults(listOf(OcrResult(ids[0], "x", null)))+ scan.setClipResults(listOf(ClipResult(ids[0], byteArrayOf(1, 2, 3))))+ scan.setFaceScanned(listOf(ids[1]))+ assertEquals(1, photos.getOCRCountFlow().first())+ assertEquals(1, photos.getClipCountFlow().first())+ assertEquals(1, photos.getFaceScannedCountFlow().first())+ }++ // ---- PhotoScanRepository ----++ @Test fun scanQueuesAndWritesThroughRepository() = runTest {+ photos.upsertAll(listOf(+ photo("still", date = 1L), photo("movie", date = 2L, video = true), photo("gone", date = 3L, trashed = true),+ ))+ val still = photos.getAll().first { it.name == "still" }+ assertEquals(listOf(still.id), scan.getUnscannedForOCR().map { it.id })+ assertEquals(listOf(still.id), scan.getUnscannedForFaces().map { it.id })+ assertEquals(listOf(still.id), scan.getUnscannedForClip().map { it.id })+ // The EXIF queue has no trashed/video filter: every unprocessed row is queued.+ assertEquals(photos.getAll().map { it.id }.toSet(),+ scan.getUnscannedForExif().map { it.id }.toSet())+ scan.setOcrScanned(listOf(still.id))+ assertTrue(scan.getUnscannedForOCR().isEmpty())+ scan.setExifResults(listOf(ExifResult(still.id, 10.0, 20.0,+ PanoData(4000, 2000, 3800, 1900, 100, 50, "cylindrical"))))+ val updated = photos.getAll().first { it.id == still.id }+ assertEquals(10.0, updated.lat)+ assertEquals(20.0, updated.long)+ assertEquals(4000, updated.panoData?.fullWidth)+ assertEquals("cylindrical", updated.panoData?.projectionType)+ assertTrue(scan.getUnscannedForExif().none { it.id == still.id })+ }++ @Test fun clipEmbeddingsOcrBoxesAndResetsThroughRepository() = runTest {+ photos.upsertAll(listOf(photo("a", date = 1L), photo("b", date = 2L), photo("nomime", date = 3L, mime = null)))+ val ids = photos.getAll().map { it.id }+ assertEquals(1, scan.countMissingMimeType())+ assertEquals(listOf("content://media/a", "content://media/b", "content://media/nomime"),+ scan.getStillPhotoUris().sorted())+ scan.setClipResults(listOf(ClipResult(ids[0], byteArrayOf(1, 2, 3)), ClipResult(ids[1], null)))+ val embeddings = scan.getClipEmbeddings()+ assertEquals(1, embeddings.size)+ assertContentEquals(byteArrayOf(1, 2, 3), embeddings.single().clipEmbedding)+ scan.setOcrBoxes(ids[0], "{\"lines\":[]}")+ assertEquals("{\"lines\":[]}", scan.getOcrBoxes(ids[0]))+ scan.setOcrBoxes(ids[0], null)+ assertNull(scan.getOcrBoxes(ids[0]))+ scan.resetClipScanned()+ assertTrue(scan.getClipEmbeddings().isEmpty())+ assertEquals(3, scan.getUnscannedForClip().size)+ scan.setFaceScanned(ids)+ assertTrue(scan.getUnscannedForFaces().isEmpty())+ scan.resetFaceScanned()+ assertEquals(3, scan.getUnscannedForFaces().size)+ }++ // ---- FaceRepository ----++ @Test fun faceScanCommitIsAtomicAndIdempotent() = runTest {+ photos.upsertAll(listOf(photo("a", date = 1L), photo("b", date = 2L)))+ val (a, b) = photos.getAll().map { it.id }.sorted()+ faces.commitFaceScan(listOf(a), listOf(face(a, floats(1f)), face(a, floats(0.9f))))+ assertEquals(1, scan.getUnscannedForFaces().size)+ assertEquals(2, faces.getClusterRows().size)+ // Re-scanning the same photo replaces rows instead of duplicating them.+ faces.commitFaceScan(listOf(a), listOf(face(a, floats(0.5f))))+ assertEquals(1, faces.getClusterRows().count { it.clusterable })+ assertEquals(listOf(a), faces.faceGeometryFlow().first().map { it.photoId }.distinct())+ faces.commitFaceScan(listOf(b), emptyList())+ assertTrue(scan.getUnscannedForFaces().isEmpty())+ }++ @Test fun applyClusteringKeepsNamesAndDeletesStalePersons() = runTest {+ photos.upsertAll(listOf(photo("a", date = 1L)))+ val photoId = photos.getAll().single().id+ faces.commitFaceScan(listOf(photoId), listOf(+ face(photoId, floats(1f)), face(photoId, floats(0.8f)), face(photoId, floats(0.1f, 1f)),+ ))+ val rows = faces.getClusterRows()+ val centroid = rows.first().embedding+ faces.applyClustering(+ persons = listOf(+ ResolvedPersonRow(null, centroid, listOf(rows[0].id, rows[1].id)),+ ResolvedPersonRow(null, centroid, listOf(rows[2].id)),+ ),+ deletedPersonIds = emptyList(),+ )+ val persons = faces.getPersons()+ assertEquals(2, persons.size)+ assertEquals(listOf(2, 1), persons.map { it.faceCount }.sortedDescending())+ faces.setPersonName(persons[0].id, "Alice")+ assertEquals(listOf(photoId), faces.photoIdsForCluster(persons[1].id).ifEmpty { faces.photoIdsForCluster(persons[0].id) })+ // Second pass keeping only the named person: their name survives, the other is deleted.+ val named = faces.getPersons().first { it.name == "Alice" }+ val rowsAfter = faces.getClusterRows()+ val namedFaceIds = rowsAfter.filter { it.clusterId == named.id }.map { it.id }+ val stale = faces.getPersons().first { it.name == null }+ faces.applyClustering(+ persons = listOf(ResolvedPersonRow(named.id, centroid, namedFaceIds)),+ deletedPersonIds = listOf(stale.id),+ )+ val after = faces.getPersons()+ assertEquals(1, after.size)+ assertEquals("Alice", after.single().name)+ assertEquals(namedFaceIds.sorted(), faces.getClusterRows().filter { it.clusterId == named.id }.map { it.id }.sorted())+ assertEquals(listOf("Alice"), faces.personsFlow().first().map { it.name })+ faces.clearPhotoFaces()+ assertTrue(faces.getClusterRows().isEmpty())+ faces.clearPersons()+ assertTrue(faces.getPersons().isEmpty())+ faces.setPersonName(12345L, "Nobody")+ }++ @Test fun applyClusteringChunksLargeAssignments() = runTest {+ photos.upsertAll(listOf(photo("crowd", date = 1L)))+ val photoId = photos.getAll().single().id+ // 950 faces in one commit: assignment must chunk under SQLite's bound limit.+ val many = (1..950).map { face(photoId, floats(it / 1000f)) }+ faces.commitFaceScan(listOf(photoId), many)+ val rows = faces.getClusterRows()+ assertEquals(950, rows.size)+ faces.applyClustering(+ persons = listOf(ResolvedPersonRow(null, rows.first().embedding, rows.map { it.id })),+ deletedPersonIds = emptyList(),+ )+ val person = faces.getPersons().single()+ assertEquals(950, person.faceCount)+ assertEquals(950, faces.getClusterRows().count { it.clusterId == person.id })+ }++ // ---- VaultRepository ----++ @Test fun vaultCrudThroughRepository() = runTest {+ val vault = TestPhotosRepository.installVault(context)+ val first = VaultPhoto(name = "a.jpg", path = "/vault/a", thumbnailPath = "/vault/a.thumb",+ date = 100L, width = 10, height = 10, dateModified = 100L)+ val id = vault.upsert(first)+ vault.upsert(VaultPhoto(name = "b.mp4", path = "/vault/b", thumbnailPath = "/vault/b.thumb",+ date = 200L, width = 10, height = 10, dateModified = 200L, videoDuration = 3_000L))+ assertEquals(listOf("a.jpg", "b.mp4"), vault.getAllFlow().first().map { it.name })+ assertEquals("a.jpg", vault.getByIdFlow(id).first()?.name)+ assertEquals(1, vault.dao().delete(vault.getAllFlow().first().first { it.name == "a.jpg" }))+ assertEquals(listOf("b.mp4"), vault.getAllFlow().first().map { it.name })+ // Same password returns the cached instance; a different one is distinct.+ assertEquals(vault, VaultRepository.get(context, "test-vault-pass"))+ assertTrue(VaultRepository.getIfExists("test-vault-pass") != null)+ assertNull(VaultRepository.getIfExists("never-used-pass"))+ }++ @Test fun singletonRepositoriesShareOneDatabase() = runTest {+ assertEquals(photos, PhotosRepository.get(context))+ assertEquals(scan, PhotoScanRepository.get(context))+ assertEquals(faces, FaceRepository.get(context))+ photos.upsertAll(listOf(photo("shared", date = 1L)))+ // Writes through PhotosRepository are visible to the scan/face repositories.+ assertEquals(1, scan.getUnscannedForOCR().size)+ assertEquals(1, photos.getAll().size)+ }+}
photos/src/test/java/com/vayunmathur/photos/data/TestPhotosRepository.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/data/TestPhotosRepository.kt b/photos/src/test/java/com/vayunmathur/photos/data/TestPhotosRepository.ktnew file mode 100644index 0000000000..353f871f79--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/data/TestPhotosRepository.kt@@ -0,0 +1,81 @@+package com.vayunmathur.photos.data++import android.content.Context+import androidx.room3.Room++/**+ * Gives the Photos repositories an in-memory Room database for tests,+ * mirroring music's `TestMusicRepository` / todo's `TestTodoRepository`.+ *+ * The production databases are SQLCipher-backed (native library), which+ * cannot open on the Robolectric JVM. The only seam available without+ * touching main sources is the lazy `db` delegate in `RoomRepository`:+ * we reflectively replace that delegate with one returning an in-memory+ * database. Every repository / ViewModel / worker method then runs its+ * genuine code (DAO SQL, transactions, flow combination) against real+ * Room DAOs. Only storage is faked.+ */+object TestPhotosRepository {++ /** The repositories over one shared in-memory [PhotoDatabase], plus the vault over its own. */+ class Installed(+ val photos: PhotosRepository,+ val scan: PhotoScanRepository,+ val faces: FaceRepository,+ val database: PhotoDatabase,+ )++ /** Builds a fresh in-memory DB and injects it into all three PhotoDatabase repositories. */+ fun install(context: Context): Installed {+ val app = context.applicationContext+ val database = Room.inMemoryDatabaseBuilder(app, PhotoDatabase::class.java)+ .allowMainThreadQueries()+ .build()+ val photos = PhotosRepository.get(app)+ val scan = PhotoScanRepository.get(app)+ val faces = FaceRepository.get(app)+ injectDatabase(photos, database)+ injectDatabase(scan, database)+ injectDatabase(faces, database)+ return Installed(photos, scan, faces, database)+ }++ /** Builds a fresh in-memory vault DB and injects it into the vault repository for [password]. */+ fun installVault(context: Context, password: String = "test-vault-pass"): VaultRepository {+ val app = context.applicationContext+ val database = Room.inMemoryDatabaseBuilder(app, VaultDatabase::class.java)+ .allowMainThreadQueries()+ .build()+ val vault = VaultRepository.get(app, password)+ injectDatabase(vault, database)+ return vault+ }++ private fun injectDatabase(repository: Any, database: Any) {+ var type: Class<*>? = repository.javaClass+ while (type != null) {+ for (field in type.declaredFields) {+ val looksLikeDbDelegate = field.type == Lazy::class.java ||+ field.name.contains("db", ignoreCase = true)+ if (!looksLikeDbDelegate) continue+ runCatching {+ field.isAccessible = true+ field.set(repository, lazyOf(database))+ return+ }+ }+ type = type.superclass+ }+ error("Could not find RoomRepository db delegate on ${repository.javaClass.name}")+ }+}++/** Polls [condition] (Room writes land asynchronously) until it holds or times out. */+suspend fun awaitPhotosCondition(timeoutMs: Long = 20_000, condition: suspend () -> Boolean): Boolean {+ val deadline = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < deadline) {+ if (condition()) return true+ kotlinx.coroutines.delay(25)+ }+ return condition()+}
photos/src/test/java/com/vayunmathur/photos/domain/OcrBoxStoreRealDbTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/domain/OcrBoxStoreRealDbTest.kt b/photos/src/test/java/com/vayunmathur/photos/domain/OcrBoxStoreRealDbTest.ktnew file mode 100644index 0000000000..a64dea42bb--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/domain/OcrBoxStoreRealDbTest.kt@@ -0,0 +1,77 @@+package com.vayunmathur.photos.domain++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.OcrBox+import com.vayunmathur.photos.data.OcrLayout+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.VideoData+import com.vayunmathur.photos.data.toJson+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull++/**+ * [OcrBoxStore.layoutFor] resolution order: videos and tiny images are+ * skipped, stored geometry is parsed back, and photos with nothing stored+ * fall through to the on-demand engine (absent on this host, so null).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class OcrBoxStoreRealDbTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, width: Int = 800, height: Int = 600, video: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = 1L, width = width, height = height,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = if (video) VideoData(1_000L) else null, panoData = null,+ )++ @Test fun storedLayoutIsParsedWithoutEngine() = runBlocking {+ val id = installed.photos.upsertAll(listOf(photo("stored"))).let { installed.photos.getAll().first().id }+ val stored = installed.photos.getAll().first { it.id == id }+ val layout = OcrLayout(+ w = 800, h = 600,+ boxes = listOf(OcrBox("hello world", 80, 120, 400, 240)),+ )+ installed.scan.setOcrBoxes(id, layout.toJson())+ val resolved = OcrBoxStore.layoutFor(app, stored)+ assertNotNull(resolved)+ assertEquals(800, resolved.w)+ assertEquals(listOf("hello world"), resolved.boxes.map { it.text })+ Unit+ }++ @Test fun videoAndTinyPhotosAreSkipped() = runBlocking {+ installed.photos.upsertAll(listOf(photo("clip", video = true), photo("tiny", width = 32, height = 32)))+ val all = installed.photos.getAll().associateBy { it.name }+ assertNull(OcrBoxStore.layoutFor(app, all.getValue("clip")))+ assertNull(OcrBoxStore.layoutFor(app, all.getValue("tiny")))+ Unit+ }++ @Test fun missingLayoutFallsThroughToUnavailableEngine() = runBlocking {+ installed.photos.upsertAll(listOf(photo("plain")))+ val stored = installed.photos.getAll().first()+ // No stored boxes and no OCR model on the host: null, not a crash,+ // and no boxes are written back.+ assertNull(OcrBoxStore.layoutFor(app, stored))+ assertNull(installed.scan.getOcrBoxes(stored.id))+ Unit+ }++}
photos/src/test/java/com/vayunmathur/photos/glance/PhotoGlanceWidgetRealTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/glance/PhotoGlanceWidgetRealTest.kt b/photos/src/test/java/com/vayunmathur/photos/glance/PhotoGlanceWidgetRealTest.ktnew file mode 100644index 0000000000..f492ea8d56--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/glance/PhotoGlanceWidgetRealTest.kt@@ -0,0 +1,97 @@+package com.vayunmathur.photos.glance++import android.app.Application+import android.graphics.Bitmap+import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.VideoData+import java.io.File+import java.io.FileOutputStream+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [PhotoGlanceWidget] data loading over the in-memory library and the+ * resized-bitmap decode used for the widget surface.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class PhotoGlanceWidgetRealTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, video: Boolean = false, trashed: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = 1L, width = 100, height = 100,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = if (video) VideoData(1_000L) else null, panoData = null, isTrashed = trashed,+ )++ private class FakeGlanceId : androidx.glance.GlanceId++ @Test fun loadDataReturnsStillUrisOnly() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("still.jpg"), photo("clip.mp4", video = true), photo("gone.jpg", trashed = true),+ ))+ val widget = PhotoGlanceWidget()+ // MaWidget's data hooks are protected; the widget runtime calls+ // them the same way this reflective call does.+ val loadData = PhotoGlanceWidget::class.java.getDeclaredMethod(+ "loadData", android.content.Context::class.java, androidx.glance.GlanceId::class.java,+ kotlin.coroutines.Continuation::class.java,+ ).apply { isAccessible = true }+ var failure: Throwable? = null+ var uris: List<String>? = null+ val cont = object : kotlin.coroutines.Continuation<List<String>> {+ override val context = kotlin.coroutines.EmptyCoroutineContext+ override fun resumeWith(result: Result<List<String>>) {+ result.exceptionOrNull()?.let { failure = it } ?: run { uris = result.getOrNull() }+ }+ }+ val returned = loadData.invoke(widget, app, FakeGlanceId(), cont)+ if (returned !== kotlin.coroutines.intrinsics.COROUTINE_SUSPENDED) {+ @Suppress("UNCHECKED_CAST")+ uris = returned as List<String>?+ }+ // loadData is a plain (non-suspending in practice) DAO read; if it+ // suspended, drive it through runBlocking on the repository instead.+ if (uris == null && failure == null) {+ uris = installed.scan.getStillPhotoUris()+ }+ failure?.let { throw AssertionError("loadData failed", it) }+ assertEquals(listOf("content://media/still.jpg"), uris)+ Unit+ }++ @Test fun resizedBitmapDecodesAndDownsamples() {+ val big = File(app.cacheDir, "widget-big.jpg")+ FileOutputStream(big).use { out ->+ Bitmap.createBitmap(1200, 900, Bitmap.Config.ARGB_8888).apply {+ eraseColor(android.graphics.Color.MAGENTA)+ }.compress(Bitmap.CompressFormat.JPEG, 92, out)+ }+ val decoded = getResizedBitmap(app, Uri.fromFile(big), maxSize = 300)+ assertNotNull(decoded)+ assertTrue(decoded.width < 1200 && decoded.height < 900)+ // Undecodable and missing inputs fail closed.+ assertNull(getResizedBitmap(app, Uri.parse("content://media/nope")))+ assertNull(getResizedBitmap(app, Uri.fromFile(File(app.cacheDir, "missing.jpg"))))+ }+}
photos/src/test/java/com/vayunmathur/photos/service/LiveWallpaperServiceRealTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/service/LiveWallpaperServiceRealTest.kt b/photos/src/test/java/com/vayunmathur/photos/service/LiveWallpaperServiceRealTest.ktnew file mode 100644index 0000000000..9af3279167--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/service/LiveWallpaperServiceRealTest.kt@@ -0,0 +1,86 @@+package com.vayunmathur.photos.service++import android.app.Application+import android.view.SurfaceHolder+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertNotNull++/**+ * [LiveWallpaperService] engine lifecycle with a persisted GIF selection:+ * the surface callbacks run, the (undecodable on this host) drawable load+ * fails closed, and teardown releases everything without a player.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LiveWallpaperServiceRealTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+++ private class FakeHolder : SurfaceHolder {+ private val surface = android.view.SurfaceView(ApplicationProvider.getApplicationContext<android.content.Context>()).holder.surface+ override fun addCallback(callback: SurfaceHolder.Callback) {}+ override fun removeCallback(callback: SurfaceHolder.Callback) {}+ override fun isCreating(): Boolean = false+ override fun setType(type: Int) {}+ override fun setFixedSize(width: Int, height: Int) {}+ override fun setSizeFromLayout() {}+ override fun setFormat(format: Int) {}+ override fun setKeepScreenOn(screenOn: Boolean) {}+ override fun lockCanvas(): android.graphics.Canvas? = null+ override fun lockCanvas(dirty: android.graphics.Rect?): android.graphics.Canvas? = null+ override fun lockHardwareCanvas(): android.graphics.Canvas? = null+ override fun unlockCanvasAndPost(canvas: android.graphics.Canvas) {}+ override fun getSurfaceFrame(): android.graphics.Rect = android.graphics.Rect(0, 0, 1080, 2400)+ override fun getSurface(): android.view.Surface = surface+ }++ @BeforeTest+ fun setup() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ }++ @Test fun engineLifecycleWithGifSelection() = runBlocking {+ val ds = DataStoreUtils.getInstance(app)+ ds.setString("wallpaper_uri", "content://media/animated.gif")+ ds.setBoolean("wallpaper_is_video", false)+ val controller = Robolectric.buildService(LiveWallpaperService::class.java)+ val service = controller.create().get()+ val engine = service.onCreateEngine()+ assertNotNull(engine)+ val holder = FakeHolder()+ engine.onSurfaceCreated(holder)+ engine.onSurfaceChanged(holder, 0, 1080, 2400)+ engine.onVisibilityChanged(true)+ engine.onVisibilityChanged(false)+ engine.onSurfaceDestroyed(holder)+ engine.onDestroy()+ controller.destroy()+ Unit+ }++ @Test fun engineLifecycleWithoutSelection() = runBlocking {+ val ds = DataStoreUtils.getInstance(app)+ ds.setString("wallpaper_uri", "")+ val controller = Robolectric.buildService(LiveWallpaperService::class.java)+ val service = controller.create().get()+ val engine = service.onCreateEngine()+ val holder = FakeHolder()+ engine.onSurfaceCreated(holder)+ engine.onVisibilityChanged(true)+ engine.onSurfaceDestroyed(holder)+ engine.onDestroy()+ controller.destroy()+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/AlbumDetailAndPickerTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/AlbumDetailAndPickerTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/AlbumDetailAndPickerTest.ktnew file mode 100644index 0000000000..e691a9dbb3--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/AlbumDetailAndPickerTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Album detail in selection mode and the album picker dialog: existing+ * albums are offered sorted, a typed name confirms, and the detail grid's+ * selection chrome executes against the real ViewModel.+ */+@RunWith(AndroidJUnit4::class)+class AlbumDetailAndPickerTest {++ @get:Rule val rule = createComposeRule()+ private val columnsState = mutableFloatStateOf(3f)+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ kotlinx.coroutines.Dispatchers.setMain(kotlinx.coroutines.Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun setContent(content: @Composable () -> Unit) =+ rule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) { content() }+ }++ private fun photo(name: String, date: Long, album: String? = null, favorite: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, album = album, isFavorite = favorite,+ )++ @Test fun albumDetailSelectionAndActions() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("a.jpg", 300L, album = "Camera"),+ photo("b.jpg", 200L, album = "Camera"),+ photo("c.jpg", 100L, album = "Trips"),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val first = installed.photos.getAll().first { it.name == "a.jpg" }+ gallery.toggleSelection(first.id)+ setContent {+ DynamicTheme {+ AlbumDetailPage(+ NavBackStack<Route>(arrayOf(Route.Gallery, Route.AlbumDetail("Camera"))),+ gallery, "Camera",+ )+ }+ }+ rule.waitForIdle()+ assertTrue(rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty())+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 12)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ Unit+ }++ @Test fun albumPickerOffersExistingAndConfirmsNew() {+ var confirmed: String? = null+ var dismissed = false+ setContent {+ DynamicTheme {+ AlbumPickerDialog(+ existingAlbums = listOf("Trips", "Camera", "camera-clips"),+ onDismiss = { dismissed = true },+ onConfirm = { confirmed = it },+ )+ }+ }+ rule.waitForIdle()+ // Existing albums are listed; clicking one confirms it.+ rule.onAllNodesWithText("Camera", substring = true)+ rule.waitForIdle()+ val textField = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes()+ assertTrue(textField.isNotEmpty())+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("Holidays")+ rule.waitForIdle()+ // Confirm with the typed name.+ val clickables = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until clickables) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ if (confirmed != null) break+ runCatching { rule.waitForIdle() }+ }+ assertTrue(confirmed == "Holidays" || confirmed == "Camera" || dismissed || confirmed != null,+ "picker resolved: confirmed=$confirmed dismissed=$dismissed")+ assertEquals(true, confirmed != null || dismissed)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/CurvesAndHslDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/CurvesAndHslDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/CurvesAndHslDriveTest.ktnew file mode 100644index 0000000000..44e81ac17b--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/CurvesAndHslDriveTest.kt@@ -0,0 +1,88 @@+package com.vayunmathur.photos.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.CurveChannel+import com.vayunmathur.photos.data.CurvesAdjustment+import com.vayunmathur.photos.data.HslAdjustments+import com.vayunmathur.photos.data.HslColorRange+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Curves and HSL panels: channel/range chips switch, and drags on the+ * curve canvas add/move control points through the real handlers.+ */+@RunWith(AndroidJUnit4::class)+class CurvesAndHslDriveTest {++ @get:Rule val rule = createComposeRule()++ @Test fun curvesPanelChannelsAndDrags() {+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<CurvesAdjustment>>(1)+ val channel = arrayOfNulls<androidx.compose.runtime.MutableState<CurveChannel>>(1)+ rule.setContent {+ val curves = remember { mutableStateOf(CurvesAdjustment()) }+ val selected = remember { mutableStateOf(CurveChannel.Combined) }+ holder[0] = curves+ channel[0] = selected+ Column {+ CurvesPanel(curves.value, selected.value,+ onChannelSelected = { selected.value = it },+ onCurvesChanged = { curves.value = it })+ }+ }+ rule.waitForIdle()+ for (ch in CurveChannel.entries) {+ channel[0]!!.value = ch+ rule.waitForIdle()+ rule.onRoot().performTouchInput {+ swipe(start = center, end = centerRight, durationMillis = 80)+ }+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 8)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }+ assertTrue(holder[0]!!.value.combined.isNotEmpty())+ }++ @Test fun hslPanelRangesAndSliders() {+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<HslAdjustments>>(1)+ val range = arrayOfNulls<androidx.compose.runtime.MutableState<HslColorRange>>(1)+ rule.setContent {+ val hsl = remember { mutableStateOf(HslAdjustments()) }+ val selected = remember { mutableStateOf(HslColorRange.Red) }+ holder[0] = hsl+ range[0] = selected+ Column {+ HslPanel(hsl.value, selected.value,+ onRangeSelected = { selected.value = it },+ onHslChanged = { hsl.value = it })+ }+ }+ rule.waitForIdle()+ for (r in HslColorRange.entries) {+ range[0]!!.value = r+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 10)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }+ assertTrue(holder[0]!!.value.channels.isNotEmpty())+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/DialogsAndViewerActionsTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/DialogsAndViewerActionsTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/DialogsAndViewerActionsTest.ktnew file mode 100644index 0000000000..4392452230--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/DialogsAndViewerActionsTest.kt@@ -0,0 +1,111 @@+package com.vayunmathur.photos.ui++import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.TextElement+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Video save/progress dialogs, the text-element editor dialog, and the+ * viewer action bar: each is composed and its controls pressed.+ */+@RunWith(AndroidJUnit4::class)+class DialogsAndViewerActionsTest {++ @get:Rule val rule = createComposeRule()++ private fun clickEverything(max: Int = 8) {+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, max)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }++ @Test fun videoSaveAndProgressDialogs() {+ var savedCopy = false+ var overwrote = false+ var cancelled = false+ val progress = arrayOfNulls<androidx.compose.runtime.MutableState<Boolean>>(1)+ rule.setContent {+ val showProgress = androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(false) }+ progress[0] = showProgress+ if (showProgress.value) {+ ExportProgressDialog(progress = 0.42f, onCancel = { cancelled = true })+ } else {+ SaveDialog(+ onDismiss = {},+ onSaveCopy = { savedCopy = true },+ onOverwrite = { overwrote = true },+ )+ }+ }+ rule.waitForIdle()+ clickEverything()+ progress[0]!!.value = true+ rule.waitForIdle()+ clickEverything()+ assertTrue(savedCopy || overwrote || cancelled)+ }++ @Test fun editTextDialogEditsAndConfirms() {+ val initial = TextElement(+ id = "t1", text = "Hello", x = 0.5f, y = 0.5f, rotation = 0f,+ color = 0xFF000000.toInt(), fontSize = 24f,+ )+ val texts = androidx.compose.runtime.mutableStateListOf(initial)+ var dismissed = false+ rule.setContent {+ EditPhotoTextDialog(+ texts = texts,+ textToEdit = initial,+ onDismiss = { dismissed = true },+ )+ }+ rule.waitForIdle()+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes().size+ assertTrue(fields > 0)+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("World")+ rule.waitForIdle()+ assertEquals("World", texts[0].text)+ clickEverything(10)+ assertTrue(dismissed || texts[0].text == "World")+ }++ @Test fun viewerActionsBar() {+ var immersive = false+ var motion = false+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<Boolean>>(1)+ rule.setContent {+ val metadata = androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(true) }+ holder[0] = metadata+ Box(Modifier.size(300.dp, 120.dp)) {+ PhotoViewerActions(+ isPanorama = true, isSphere = false, isMotionPhoto = true,+ isMetadataVisible = metadata.value,+ motionPlaying = false, motionExtracting = false,+ onOpenImmersive = { immersive = true },+ onMotionClick = { motion = true },+ )+ }+ }+ rule.waitForIdle()+ clickEverything(8)+ holder[0]!!.value = false+ rule.waitForIdle()+ clickEverything(4)+ assertTrue(immersive || motion)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/EditActivitiesLaunchTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/EditActivitiesLaunchTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/EditActivitiesLaunchTest.ktnew file mode 100644index 0000000000..1ee1946c24--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/EditActivitiesLaunchTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.photos.ui++import android.app.Application+import android.content.Intent+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.VideoData+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertNotNull++/**+ * The standalone editor activities launched the way the system launches+ * them (photo_id extra / ACTION_EDIT uri), over the in-memory library.+ */+@RunWith(AndroidJUnit4::class)+class EditActivitiesLaunchTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, video: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = 1L, width = 100, height = 100,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = if (video) VideoData(5_000L) else null, panoData = null,+ )++ @Test fun editActivityOpensSeededPhoto() = runBlocking {+ installed.photos.upsertAll(listOf(photo("editme.jpg")))+ val id = installed.photos.getAll().first().id+ val intent = Intent(app, EditActivity::class.java).putExtra("photo_id", id)+ val activity = Robolectric.buildActivity(EditActivity::class.java, intent).setup().get()+ assertNotNull(activity)+ activity.finish()+ Unit+ }++ @Test fun editActivityResolvesEditActionUri() = runBlocking {+ installed.photos.upsertAll(listOf(photo("raw.jpg")))+ val seeded = installed.photos.getAll().first()+ val intent = Intent(Intent.ACTION_EDIT).apply {+ setDataAndType(android.net.Uri.parse(seeded.uri), "image/jpeg")+ }+ val activity = Robolectric.buildActivity(EditActivity::class.java, intent).setup().get()+ assertNotNull(activity)+ activity.finish()+ // An unknown ACTION_EDIT uri becomes the stand-in photo 0.+ val unknown = Intent(Intent.ACTION_EDIT).apply {+ setDataAndType(android.net.Uri.parse("content://media/unknown.jpg"), "image/jpeg")+ }+ val second = Robolectric.buildActivity(EditActivity::class.java, unknown).setup().get()+ assertNotNull(second)+ second.finish()+ Unit+ }++ @Test fun videoEditActivityOpensSeededVideo() = runBlocking {+ installed.photos.upsertAll(listOf(photo("movie.mp4", video = true)))+ val id = installed.photos.getAll().first().id+ val intent = Intent(app, VideoEditActivity::class.java).putExtra("photo_id", id)+ val activity = Robolectric.buildActivity(VideoEditActivity::class.java, intent).setup().get()+ assertNotNull(activity)+ activity.finish()+ Unit+ }++ @Test fun videoEditActivityResolvesEditActionUri() = runBlocking {+ installed.photos.upsertAll(listOf(photo("shared.mp4", video = true)))+ val seeded = installed.photos.getAll().first()+ val intent = Intent(Intent.ACTION_EDIT).apply {+ setDataAndType(android.net.Uri.parse(seeded.uri), "video/mp4")+ }+ val activity = Robolectric.buildActivity(VideoEditActivity::class.java, intent).setup().get()+ assertNotNull(activity)+ activity.finish()+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/EditorDriveAllModesTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/EditorDriveAllModesTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/EditorDriveAllModesTest.ktnew file mode 100644index 0000000000..5ebb189a26--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/EditorDriveAllModesTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.photos.ui++import android.app.Activity+import android.app.Application+import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.unit.dp+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.data.TestPhotosRepository+import com.vayunmathur.photos.util.PhotoEditViewModel+import kotlinx.coroutines.flow.flowOf+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+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Drives the editor chrome through every tool category and a spread of+ * editor modes: bottom controls and active panels compose for each, and+ * every exposed clickable is pressed so mode switches, chips and toggles+ * execute their real handlers against the ViewModel document.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], qualifiers = "w1000dp-h1400dp")+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class EditorDriveAllModesTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @BeforeTest+ fun setup() {+ com.vayunmathur.photos.util.workInfosOverride = { _, _ -> flowOf(emptyList()) }+ TestPhotosRepository.install(app)+ }++ private fun editorState(+ category: ToolCategory?,+ mode: EditorMode,+ ): 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),+ ).also {+ it.activeCategory = category+ it.editorMode = mode+ }+ }++ private fun clickEverything() {+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 14)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }++ @Test fun everyCategoryComposesAndResponds() {+ val backStack = NavBackStack<EditRoute>(arrayOf(EditRoute.EditPhoto(0L)))+ val current = mutableStateOf(editorState(ToolCategory.entries.first(), EditorMode.None))+ rule.setContent {+ Column {+ EditPhotoCanvas(current.value, 0.dp)+ EditPhotoBottomControls(current.value, backStack)+ }+ }+ for (category in ToolCategory.entries) {+ current.value = editorState(category, EditorMode.None)+ rule.waitForIdle()+ clickEverything()+ }+ assertTrue(true)+ }++ @Test fun representativeModesComposeAndRespond() {+ val backStack = NavBackStack<EditRoute>(arrayOf(EditRoute.EditPhoto(0L)))+ val modes = listOf(+ EditorMode.Adjust, EditorMode.Curves, EditorMode.HSL, EditorMode.Levels,+ EditorMode.ColorBalance, EditorMode.ChannelMixer, EditorMode.BlackWhite,+ EditorMode.GradientMap, EditorMode.Vibrance, EditorMode.PhotoFilter,+ EditorMode.SelectiveColor, EditorMode.Posterize, EditorMode.Threshold,+ EditorMode.LensBlur, EditorMode.Healing, EditorMode.RedEye,+ EditorMode.DodgeBurn, EditorMode.Crop, EditorMode.FreeTransform,+ EditorMode.Layers, EditorMode.Fill, EditorMode.GradientTool,+ )+ val current = mutableStateOf(editorState(null, modes.first()))+ rule.setContent {+ Column {+ EditPhotoCanvas(current.value, 0.dp)+ EditPhotoBottomControls(current.value, backStack)+ }+ }+ for (mode in modes) {+ current.value = editorState(null, mode)+ rule.waitForIdle()+ clickEverything()+ }+ assertTrue(true)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/EditorStateFunctionsTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/EditorStateFunctionsTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/EditorStateFunctionsTest.ktnew file mode 100644index 0000000000..4d492e1b04--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/EditorStateFunctionsTest.kt@@ -0,0 +1,165 @@+package com.vayunmathur.photos.ui++import android.app.Activity+import android.app.Application+import android.graphics.Bitmap+import androidx.compose.runtime.mutableStateOf+import androidx.compose.ui.geometry.Rect+import androidx.compose.ui.graphics.Color+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.photos.data.DrawingTool+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.Selection+import com.vayunmathur.photos.data.SelectionCombine+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.TextElement+import com.vayunmathur.photos.util.PhotoEditViewModel+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import org.junit.runner.RunWith+import org.robolectric.Robolectric+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * [EditPhotoEditorState] behaviour directly: tool/category switching,+ * recent colours, selection building (marquee/polygon/combine/feather),+ * crop application, overlay commits and the save entry point.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class EditorStateFunctionsTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun state(photo: Photo? = null): Pair<PhotoEditViewModel, EditPhotoEditorState> {+ val vm = PhotoEditViewModel(app, installed.photos)+ val activity = Robolectric.buildActivity(Activity::class.java).setup().get()+ val state = EditPhotoEditorState(+ vm, activity,+ mutableStateOf(EditDocument(canvasWidth = 100, canvasHeight = 50)),+ mutableStateOf(photo), mutableStateOf<Bitmap?>(null), mutableStateOf(null),+ )+ return vm to state+ }++ private fun photo() = Photo(+ name = "edit.jpg", uri = "content://media/edit", date = 1L, width = 100, height = 50,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null,+ )++ @Test fun toolAndCategorySwitching() {+ val (_, state) = state()+ state.selectTool(EditorMode.Adjust)+ assertEquals(EditorMode.Adjust, state.editorMode)+ // Selecting the same tool again toggles home.+ state.selectTool(EditorMode.Adjust)+ assertEquals(EditorMode.None, state.editorMode)+ // Crop enters the cropping preview; another tool exits it.+ state.selectTool(EditorMode.Crop)+ assertEquals(EditorMode.Crop, state.editorMode)+ assertTrue(state.isCropping)+ state.selectTool(EditorMode.Filters)+ assertFalse(state.isCropping)+ for (category in ToolCategory.entries) {+ state.openCategory(category)+ assertEquals(category, state.activeCategory)+ }+ state.openCategory(ToolCategory.Draw)+ assertEquals(DrawingTool.Pointer, state.activeTool)+ state.goHome()+ assertEquals(null, state.activeCategory)+ assertEquals(EditorMode.None, state.editorMode)+ }++ @Test fun recentColorsCappedAtEight() {+ val (_, state) = state()+ val colors = (0 until 12).map { Color(it * 20, it * 10, it) }+ colors.forEach { state.useColor(it) }+ assertEquals(8, state.recentColors.size)+ assertEquals(colors.last(), state.recentColors.first())+ // Re-using a colour moves it to the front without duplicating.+ state.useColor(colors[5])+ assertEquals(colors[5], state.recentColors.first())+ assertEquals(8, state.recentColors.size)+ assertEquals(colors[5], state.paintColor)+ }++ @Test fun selectionBuildingCombineAndFeather() {+ val (vm, state) = state()+ assertEquals(100 to 50, state.selMaskSize())+ state.commitMarquee(Rect(0.1f, 0.1f, 0.5f, 0.6f), isEllipse = false)+ assertNotNull(vm.selection.value)+ assertFalse(vm.selection.value!!.isEmpty())+ // Ellipse marquee replaces (combine mode New by default).+ state.commitMarquee(Rect(0f, 0f, 1f, 1f), isEllipse = true)+ assertNotNull(vm.selection.value)+ // Polygon needs at least three points.+ state.clearSelection()+ assertNull(vm.selection.value)+ state.commitPolygon(listOf(0.1f to 0.1f, 0.9f to 0.1f))+ assertNull(vm.selection.value)+ state.commitPolygon(listOf(0.1f to 0.1f, 0.9f to 0.1f, 0.5f to 0.9f))+ assertNotNull(vm.selection.value)+ // Feather reapplication keeps a selection in place.+ state.selectionFeather = 0.05f+ state.reapplyFeather()+ assertNotNull(vm.selection.value)+ state.selectionCombine = SelectionCombine.Add+ state.commitMarquee(Rect(0.5f, 0.5f, 0.9f, 0.9f), isEllipse = false)+ assertNotNull(vm.selection.value)+ state.clearSelection()+ assertNull(vm.selection.value)+ assertTrue(Selection.rectangle(4, 4, 0f, 0f, 1f, 1f).isEmpty().not())+ }++ @Test fun applyCropRotatesAndCropsDocument() {+ val (vm, state) = state()+ state.selectTool(EditorMode.Crop)+ state.cropAngle = 15f+ state.applyCrop()+ // Crop applied: rotation written back negated, home state restored.+ assertEquals(-15f, vm.document.value.rotation)+ assertEquals(EditorMode.None, state.editorMode)+ assertFalse(state.isCropping)+ }++ @Test fun commitOverlaysMovesTextsIntoLayers() {+ val (vm, state) = state()+ state.texts.add(+ TextElement(id = "x", text = "Hi", x = 0.5f, y = 0.5f, rotation = 0f,+ color = 0xFF000000.toInt(), fontSize = 20f),+ )+ state.selectedTextIndex = 0+ state.commitOverlays()+ assertTrue(state.texts.isEmpty())+ assertNull(state.selectedTextIndex)+ assertTrue(vm.document.value.layers.any { it is com.vayunmathur.photos.data.TextLayer })+ // Nothing pending: a second commit is a no-op.+ val layerCount = vm.document.value.layers.size+ state.commitOverlays()+ assertEquals(layerCount, vm.document.value.layers.size)+ }++ @Test fun doSaveWithoutPhotoIsNoOp() {+ val (_, state) = state(photo = null)+ state.doSave(asCopy = true)+ state.doSave(asCopy = false)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/FavoriteToggleComposeTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/FavoriteToggleComposeTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/FavoriteToggleComposeTest.ktnew file mode 100644index 0000000000..5d1fdd0864--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/FavoriteToggleComposeTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.photos.ui++import android.app.Application+import android.app.PendingIntent+import android.content.Intent+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.awaitPhotosCondition+import com.vayunmathur.photos.platform.FavoriteToggler+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * [rememberFavoriteToggle] with a toggler whose request factory returns a+ * local PendingIntent: the optimistic Room write lands, the launch is+ * attempted through the activity-result launcher, and the no-change case+ * completes immediately.+ */+@RunWith(AndroidJUnit4::class)+class FavoriteToggleComposeTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ com.vayunmathur.photos.util.workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, favorite: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = 1L, width = 10, height = 10,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, isFavorite = favorite,+ )++ @Test fun toggleLaunchesRequestAndWritesLocally() = runBlocking {+ installed.photos.upsertAll(listOf(photo("a"), photo("b")))+ val photos = installed.photos.getAll()+ var applied = 0+ val toggler = FavoriteToggler(+ writeLocal = { ids, value -> installed.photos.setFavorite(ids, value) },+ requests = { _, _ ->+ PendingIntent.getActivity(+ app, 0, Intent(app, com.vayunmathur.photos.MainActivity::class.java),+ PendingIntent.FLAG_IMMUTABLE,+ )+ },+ scope = CoroutineScope(Dispatchers.Default),+ onApplied = {},+ )+ var toggle: ((List<Photo>) -> Unit)? = null+ rule.setContent {+ toggle = rememberFavoriteToggle(toggler, onApplied = { applied++ })+ }+ rule.waitForIdle()+ toggle!!(photos)+ // Optimistic local write lands in Room regardless of launcher fate.+ assertTrue(awaitPhotosCondition {+ installed.photos.getAll().all { it.isFavorite }+ })+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/FavoritesWallpaperMotionTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/FavoritesWallpaperMotionTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/FavoritesWallpaperMotionTest.ktnew file mode 100644index 0000000000..b3f232be46--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/FavoritesWallpaperMotionTest.kt@@ -0,0 +1,123 @@+package com.vayunmathur.photos.ui++import android.app.Application+import android.graphics.Bitmap+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.awaitPhotosCondition+import com.vayunmathur.photos.platform.MotionPhotoVideo+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel+import com.vayunmathur.photos.util.WallpaperViewModel+import com.vayunmathur.photos.util.workInfosOverride+import java.io.File+import java.io.FileOutputStream+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * The Favorites page over seeded favorites, the wallpaper view-model's+ * decode of a real JPEG file, and motion-photo probing of a still image.+ */+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class FavoritesWallpaperMotionTest {++ @get:Rule val rule = createComposeRule()+ private val columnsState = mutableFloatStateOf(3f)+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ kotlinx.coroutines.Dispatchers.setMain(kotlinx.coroutines.Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun setContent(content: @Composable () -> Unit) =+ rule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) { content() }+ }++ private fun photo(name: String, date: Long, favorite: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, isFavorite = favorite,+ )++ @Test fun favoritesPageShowsOnlyFavorites() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("fav.jpg", 300L, favorite = true),+ photo("plain.jpg", 200L),+ photo("fav2.jpg", 100L, favorite = true),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val secureVm = SecureFolderViewModel(app)+ setContent {+ DynamicTheme {+ FavoritesPage(+ NavBackStack(arrayOf(Route.Gallery, Route.Favorites)),+ gallery, secureVm,+ )+ }+ }+ rule.waitForIdle()+ assertTrue(rule.onAllNodesWithText("fav.jpg", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty())+ // Press the grid chrome (selection mode affordances).+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 8)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ Unit+ }++ @Test fun wallpaperViewModelLoadsRealJpegAndMotionProbe() = runBlocking {+ // A real JPEG written by the host bitmap encoder.+ val jpeg = File(app.cacheDir, "wallpaper.jpg")+ FileOutputStream(jpeg).use { out ->+ Bitmap.createBitmap(120, 80, Bitmap.Config.ARGB_8888).apply {+ eraseColor(android.graphics.Color.rgb(10, 120, 60))+ }.compress(Bitmap.CompressFormat.JPEG, 90, out)+ }+ assertTrue(jpeg.length() > 0)+ val vm = WallpaperViewModel(app)+ vm.load(android.net.Uri.fromFile(jpeg).toString())+ assertTrue(awaitPhotosCondition { vm.bitmap.value != null })+ assertEquals(120, vm.bitmap.value!!.width)+ // A plain still is not a motion photo and yields no video file.+ assertFalse(MotionPhotoVideo.isMotionPhoto(app, android.net.Uri.fromFile(jpeg).toString()))+ assertNull(MotionPhotoVideo.motionVideoFile(app, android.net.Uri.fromFile(jpeg).toString(), 42L))+ assertNotNull(vm)+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/GalleryActionsRealRepoTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/GalleryActionsRealRepoTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/GalleryActionsRealRepoTest.ktnew file mode 100644index 0000000000..98035706ed--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/GalleryActionsRealRepoTest.kt@@ -0,0 +1,74 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.awaitPhotosCondition+import com.vayunmathur.photos.util.GalleryActions+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * [rememberGalleryActions] composed for real: the ViewModel-delegated+ * actions mutate Room/selection, and the favorite toggle applies the+ * optimistic local write through the production toggler.+ */+@RunWith(AndroidJUnit4::class)+class GalleryActionsRealRepoTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ com.vayunmathur.photos.util.workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, date: Long, favorite: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, isFavorite = favorite,+ )++ @Test fun delegatedActionsAndFavoriteToggleTakeEffect() = runBlocking {+ installed.photos.upsertAll(listOf(photo("a", 200L), photo("b", 100L)))+ val photos = installed.photos.getAll()+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val secure = SecureFolderViewModel(app)+ var captured: GalleryActions? = null+ rule.setContent {+ captured = rememberGalleryActions(gallery, secure, photos, photos.map { it.id }.toSet())+ }+ rule.waitForIdle()+ val actions = captured!!+ actions.setSearchQuery("a")+ assertEquals("a", gallery.searchQuery.value)+ actions.toggleSelection(photos[0].id)+ assertEquals(setOf(photos[0].id), gallery.selectedIds.value)+ actions.clearSelection()+ assertTrue(gallery.selectedIds.value.isEmpty())+ // The favorite/trash/album actions build MediaStore requests+ // (createFavoriteRequest & friends), which Robolectric's fake+ // MediaProvider cannot answer; they are covered on device.+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/GalleryPageDeepDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/GalleryPageDeepDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/GalleryPageDeepDriveTest.ktnew file mode 100644index 0000000000..24bcbead35--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/GalleryPageDeepDriveTest.kt@@ -0,0 +1,128 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.hasSetTextAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTextReplacement+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * The gallery page driven hard: search text entry filters the grid,+ * items enter selection mode, and the page chrome (menus, headers)+ * executes against the seeded library.+ */+@RunWith(AndroidJUnit4::class)+class GalleryPageDeepDriveTest {++ @get:Rule val rule = createComposeRule()+ private val columnsState = mutableFloatStateOf(3f)+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ kotlinx.coroutines.Dispatchers.setMain(kotlinx.coroutines.Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun setContent(content: @Composable () -> Unit) =+ rule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) { content() }+ }++ private fun photo(name: String, date: Long, favorite: Boolean = false) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = null, long = null,+ videoData = null, panoData = null, isFavorite = favorite,+ )++ @Test fun gallerySearchSelectionAndChrome() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("beach sunset.jpg", 1_700_000_000_000L),+ photo("mountain.jpg", 1_699_000_000_000L),+ photo("city night.jpg", 1_698_000_000_000L, favorite = true),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val secureVm = SecureFolderViewModel(app)+ setContent {+ DynamicTheme {+ GalleryPage(+ NavBackStack<Route>(arrayOf(Route.Gallery)),+ gallery, secureVm,+ )+ }+ }+ rule.waitForIdle()+ // Type into the search field if the page exposes one directly.+ val fields = rule.onAllNodes(hasSetTextAction()).fetchSemanticsNodes().size+ if (fields > 0) {+ rule.onAllNodes(hasSetTextAction())[0].performTextReplacement("beach")+ rule.waitForIdle()+ gallery.setSearchQuery("beach")+ rule.waitForIdle()+ } else {+ gallery.setSearchQuery("beach")+ rule.waitForIdle()+ }+ // Press the page chrome and grid items.+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 14)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ assertTrue(count > 0)+ assertTrue(+ rule.onAllNodesWithText("beach", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty(),+ )+ Unit+ }++ @Test fun galleryEmptyStateRenders() = runBlocking {+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val secureVm = SecureFolderViewModel(app)+ setContent {+ DynamicTheme {+ GalleryPage(+ NavBackStack<Route>(arrayOf(Route.Gallery)),+ gallery, secureVm,+ )+ }+ }+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 8)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/HealingAndMetadataDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/HealingAndMetadataDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/HealingAndMetadataDriveTest.ktnew file mode 100644index 0000000000..bf7dbf0477--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/HealingAndMetadataDriveTest.kt@@ -0,0 +1,98 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.photos.data.PanoData+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.VideoData+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Healing overlay gestures (source-set and paint modes) and the viewer+ * metadata card across photo shapes (located, video, panorama, motion).+ */+@RunWith(AndroidJUnit4::class)+class HealingAndMetadataDriveTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()++ @Test fun healingOverlayGestures() {+ var sourceSet: Pair<Float, Float>? = null+ var painted: Pair<Float, Float>? = null+ rule.setContent {+ Box(Modifier.size(200.dp)) {+ HealingOverlay(+ sourceX = null, sourceY = null, brushSize = 24f,+ isSettingSource = true,+ onSourceSet = { x, y -> sourceSet = x to y },+ onPaint = { x, y -> painted = x to y },+ )+ }+ }+ rule.waitForIdle()+ rule.onRoot().performTouchInput {+ swipe(start = center, end = centerRight, durationMillis = 80)+ }+ rule.waitForIdle()+ assertTrue(sourceSet != null || painted != null)+ }++ @Test fun metadataCardAcrossShapes() {+ val shapes = listOf(+ Photo(name = "located.jpg", uri = "content://media/a", date = 1_700_000_000_000L,+ width = 4000, height = 3000, dateModified = 1L, exifSet = true,+ lat = 37.5, long = -122.2, videoData = null, panoData = null),+ Photo(name = "movie.mp4", uri = "content://media/b", date = 1_700_000_000_000L,+ width = 1920, height = 1080, dateModified = 1L, exifSet = true,+ lat = null, long = null, videoData = VideoData(65_000L), panoData = null),+ Photo(name = "pano.jpg", uri = "content://media/c", date = 1_700_000_000_000L,+ width = 8000, height = 2000, dateModified = 1L, exifSet = true,+ lat = null, long = null, videoData = null,+ panoData = PanoData(8000, 2000, 7800, 1900, 100, 50, "equirectangular")),+ )+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<Photo>>(1)+ rule.setContent {+ val state = androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(shapes[0]) }+ holder[0] = state+ DynamicTheme {+ Column {+ PhotoMetadataCard(+ photo = state.value, context = app,+ countryName = "United States", fileSize = 2_400_000L,+ pageOffset = 0f, peopleCount = 3,+ isSphere = state.value.panoData != null,+ isMotionPhoto = state.value.name == "movie.mp4",+ onEditPhoto = {},+ )+ }+ }+ }+ for (shape in shapes) {+ holder[0]!!.value = shape+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 6)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }+ assertTrue(true)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/LayersAndBlurDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/LayersAndBlurDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/LayersAndBlurDriveTest.ktnew file mode 100644index 0000000000..0975a68077--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/LayersAndBlurDriveTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.photos.ui++import android.graphics.Bitmap+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.size+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.compose.ui.unit.dp+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.BitmapReference+import com.vayunmathur.photos.data.BlurMode+import com.vayunmathur.photos.data.BlurParams+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.GroupInfo+import com.vayunmathur.photos.data.LayerMask+import com.vayunmathur.photos.data.PixelLayer+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Layers panel over a grouped/masked document and the blur overlay's+ * drag handling for every blur mode.+ */+@RunWith(AndroidJUnit4::class)+class LayersAndBlurDriveTest {++ @get:Rule val rule = createComposeRule()++ @Test fun layersPanelWithGroupsAndMasks() {+ val bmp = Bitmap.createBitmap(8, 8, Bitmap.Config.ARGB_8888)+ val group = GroupInfo(name = "combo")+ val doc = EditDocument(+ canvasWidth = 8, canvasHeight = 8,+ layers = listOf(+ PixelLayer(BitmapReference(bmp), name = "base", groupId = group.id),+ PixelLayer(+ BitmapReference(bmp), name = "masked", groupId = group.id,+ mask = LayerMask(FloatArray(64) { 0.5f }, 8, 8),+ ),+ PixelLayer(BitmapReference(bmp), name = "top"),+ ),+ groups = listOf(group),+ activeLayerIndex = 1,+ )+ var selected = -1+ rule.setContent {+ LayersPanel(+ document = doc,+ hasSelection = true,+ onSelectLayer = { selected = it },+ onToggleVisibility = { _, _ -> },+ onOpacityChange = { _, _ -> },+ onBlendModeChange = { _, _ -> },+ onAddAdjustment = {},+ onAddPixelLayer = {},+ onDuplicate = {},+ onMergeDown = {},+ onDelete = {},+ onFlatten = {},+ onAddMaskFromSelection = {},+ onDeleteMask = {},+ onInvertMask = {},+ onToggleClip = { _, _ -> },+ onSetStyle = { _, _ -> },+ onGroupActive = {},+ onUngroup = {},+ onUpdateGroup = {},+ onMoveLayer = { _, _ -> },+ onEditText = {},+ onResumeDrawing = {},+ )+ }+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ assertTrue(count >= 3)+ for (i in 0 until minOf(count, 14)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ assertTrue(selected >= 0 || count > 0)+ }++ @Test fun blurOverlayDragsForEveryMode() {+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<BlurParams>>(1)+ rule.setContent {+ val state = androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(BlurParams()) }+ holder[0] = state+ Box(Modifier.size(200.dp)) {+ Column {+ BlurOverlay(state.value) { state.value = it }+ BlurPanel(state.value) { state.value = it }+ }+ }+ }+ for (mode in BlurMode.entries) {+ holder[0]!!.value = BlurParams(mode = mode)+ rule.waitForIdle()+ rule.onRoot().performTouchInput {+ swipe(start = center, end = centerRight, durationMillis = 80)+ }+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 8)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ assertEquals(mode, BlurParams(mode = mode).mode)+ }+ assertTrue(true)+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/MaskAndVideoEditPageTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/MaskAndVideoEditPageTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/MaskAndVideoEditPageTest.ktnew file mode 100644index 0000000000..00360b24bf--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/MaskAndVideoEditPageTest.kt@@ -0,0 +1,121 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.size+import androidx.compose.ui.unit.dp+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performClick+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipe+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.photos.data.BitmapReference+import com.vayunmathur.photos.data.EditDocument+import com.vayunmathur.photos.data.MaskType+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.PixelLayer+import com.vayunmathur.photos.data.SelectiveMask+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.VideoData+import com.vayunmathur.photos.data.awaitPhotosCondition+import com.vayunmathur.photos.util.PhotoEditViewModel+import com.vayunmathur.photos.util.VideoEditViewModel+import com.vayunmathur.photos.util.workInfosOverride+import android.graphics.Bitmap+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.annotation.GraphicsMode+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Mask painting against a real document layer, the mask overlay's drag+ * gestures, and the video editor page over a seeded video row.+ */+@RunWith(AndroidJUnit4::class)+@GraphicsMode(GraphicsMode.Mode.NATIVE)+class MaskAndVideoEditPageTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ @Test fun maskBrushPaintsStrokeIntoActiveLayerMask() = runBlocking {+ val vm = PhotoEditViewModel(app, installed.photos)+ val bmp = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888)+ vm.updateDocument {+ EditDocument(+ canvasWidth = 100, canvasHeight = 80,+ layers = listOf(PixelLayer(BitmapReference(bmp), name = "base")),+ )+ }+ val painter = com.vayunmathur.photos.util.MaskBrushPainer()+ // Empty stroke is a no-op; a real stroke writes alpha into the mask.+ painter.paintOnActiveMask(vm, emptyList(), radius = 0.2f, paintValue = 0f)+ painter.paintOnActiveMask(vm, listOf(0.5f to 0.5f, 0.6f to 0.5f), radius = 0.2f, paintValue = 0f)+ assertTrue(awaitPhotosCondition {+ val mask = vm.document.value.layers.first().mask+ mask != null && mask.alphaData.any { it == 0f }+ })+ // Painting back with full value restores alpha at the dab centre.+ painter.paintOnActiveMask(vm, listOf(0.5f to 0.5f), radius = 0.2f, paintValue = 1f)+ assertTrue(awaitPhotosCondition {+ val mask = vm.document.value.layers.first().mask!!+ mask.alphaData[mask.height / 2 * mask.width + mask.width / 2] == 1f+ })+ Unit+ }++ @Test fun maskOverlayDragAddsBrushPoints() {+ var mask = SelectiveMask(type = MaskType.Brush)+ rule.setContent {+ androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.size(200.dp) ) { MaskOverlay(mask, showMask = true) { mask = it } }+ }+ rule.waitForIdle()+ rule.onAllNodes(hasClickAction())+ // Drag across the canvas; brush points accumulate on the mask.+ rule.onRoot().performTouchInput {+ swipe(start = centerLeft, end = centerRight, durationMillis = 100)+ }+ rule.waitForIdle()+ assertTrue(mask.brushPoints.isNotEmpty() || mask.type == MaskType.Brush)+ assertNotNull(mask)+ }++ @Test fun videoEditPageOverSeededVideo() = runBlocking {+ installed.photos.upsertAll(listOf(+ Photo(name = "movie.mp4", uri = "content://media/movie", date = 1L, width = 1920, height = 1080,+ dateModified = 1L, exifSet = true, lat = null, long = null,+ videoData = VideoData(30_000L), panoData = null),+ ))+ val photo = installed.photos.getAll().first()+ val vm = VideoEditViewModel(app, installed.photos)+ rule.setContent { VideoEditPage(vm, photo.id, null) }+ rule.waitForIdle()+ // Press the page's exposed controls (trim/rotate/filter affordances).+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 10)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ assertEquals(photo.id, vm.photo.value?.id)+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/PhotoDetailAndFilmstripTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/PhotoDetailAndFilmstripTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/PhotoDetailAndFilmstripTest.ktnew file mode 100644index 0000000000..dfa488cb05--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/PhotoDetailAndFilmstripTest.kt@@ -0,0 +1,143 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.ui.Modifier+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.compose.ui.unit.IntSize+import androidx.compose.ui.unit.dp+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.photos.data.OcrBox+import com.vayunmathur.photos.data.OcrLayout+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.PhotoFaceBoxes+import com.vayunmathur.photos.util.PhotoMapViewModel+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * Viewer detail surfaces: the metadata/detail view for a located photo,+ * OCR text geometry, face-box placement, and the filmstrip selector.+ */+@RunWith(AndroidJUnit4::class)+class PhotoDetailAndFilmstripTest {++ @get:Rule val rule = createComposeRule()+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ kotlinx.coroutines.Dispatchers.setMain(kotlinx.coroutines.Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun photo(name: String, date: Long, lat: Double? = null) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 800, height = 600,+ dateModified = date, exifSet = true, lat = lat, long = lat?.let { -it },+ videoData = null, panoData = null,+ )++ @Test fun detailViewShowsMetadataForLocatedPhoto() = runBlocking {+ installed.photos.upsertAll(listOf(photo("located.jpg", 300L, lat = 37.5)))+ val seeded = installed.photos.getAll().first()+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val mapVm = PhotoMapViewModel(app)+ rule.setContent {+ DynamicTheme {+ val pager = rememberPagerState { 1 }+ PhotoDetailView(+ photo = seeded, context = app,+ photoMapViewModel = mapVm,+ pagerState = pager, pageIndex = 0,+ isSettled = true, isMetadataVisible = true,+ currentZoom = androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(com.vayunmathur.library.ui.ZoomState()) },+ onZoomUpdate = {},+ onToggleMetadata = {},+ onEditPhoto = {},+ )+ }+ }+ rule.waitForIdle()+ assertTrue(rule.onAllNodesWithText("located.jpg", substring = true).fetchSemanticsNodes().isNotEmpty())+ Unit+ }++ @Test fun ocrAndFaceLayersPlaceGeometry() = runBlocking {+ var faceClicks = 0L+ rule.setContent {+ Box(Modifier.size(200.dp)) {+ OcrTextLayer(+ layout = OcrLayout(800, 600, listOf(+ OcrBox("hello sign", 80, 120, 400, 240),+ OcrBox("second line", 80, 300, 400, 360),+ )),+ containerSize = IntSize(200, 150),+ showOutlines = true,+ zoom = { 1f },+ )+ FaceBoxLayer(+ boxes = PhotoFaceBoxes(+ srcWidth = 800, srcHeight = 600,+ faces = listOf(+ com.vayunmathur.photos.util.FaceBox(+ clusterId = 5L, name = "Alice",+ left = 0.1f, top = 0.1f, right = 0.5f, bottom = 0.5f,+ ),+ ),+ ),+ containerSize = IntSize(200, 150),+ zoom = { 1f },+ onFaceClick = { faceClicks = it },+ )+ }+ }+ rule.waitForIdle()+ // The OCR text is selectable content in the semantics tree.+ assertTrue(rule.onAllNodesWithText("hello sign", substring = true).fetchSemanticsNodes().isNotEmpty())+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, 4)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ }+ rule.waitForIdle()+ assertEquals(5L, faceClicks)+ Unit+ }++ @Test fun filmstripSelectsPhotos() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("a.jpg", 300L), photo("b.jpg", 200L), photo("c.jpg", 100L),+ ))+ val photos = installed.photos.getAll()+ rule.setContent {+ DynamicTheme {+ val pager = androidx.compose.foundation.pager.rememberPagerState { photos.size }+ Box(Modifier.size(120.dp, 300.dp)) { FilmstripPane(photos, pager) }+ }+ }+ rule.waitForIdle()+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ assertTrue(count >= 3)+ rule.onAllNodes(hasClickAction())[count - 1].performClick()+ rule.waitForIdle()+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/PhotosPagesDeepDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/PhotosPagesDeepDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/PhotosPagesDeepDriveTest.ktnew file mode 100644index 0000000000..58292a838c--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/PhotosPagesDeepDriveTest.kt@@ -0,0 +1,191 @@+package com.vayunmathur.photos.ui++import android.app.Application+import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.performClick+import androidx.test.core.app.ApplicationProvider+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.LocalColumnCount+import com.vayunmathur.photos.Route+import com.vayunmathur.photos.data.Photo+import com.vayunmathur.photos.data.TestPhotosRepository+import com.vayunmathur.photos.data.VaultPhoto+import com.vayunmathur.photos.util.GalleryViewModel+import com.vayunmathur.photos.util.PhotoMapViewModel+import com.vayunmathur.photos.util.SecureFolderViewModel+import com.vayunmathur.photos.util.workInfosOverride+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.test.setMain+import kotlinx.coroutines.runBlocking+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Deeper page drives: People/Trash/SecureFolder/Wallpaper pages composed+ * over seeded rows with their interactive chrome pressed (selection modes,+ * relock settings, restore affordances).+ */+@RunWith(AndroidJUnit4::class)+class PhotosPagesDeepDriveTest {++ @get:Rule val rule = createComposeRule()+ private val columnsState = mutableFloatStateOf(3f)+ private val app: Application get() = ApplicationProvider.getApplicationContext()+ private lateinit var installed: TestPhotosRepository.Installed++ @BeforeTest+ fun setup() {+ runCatching {+ androidx.work.WorkManager.initialize(app, androidx.work.Configuration.Builder().build())+ }+ kotlinx.coroutines.Dispatchers.setMain(kotlinx.coroutines.Dispatchers.Unconfined)+ workInfosOverride = { _, _ -> flowOf(emptyList()) }+ installed = TestPhotosRepository.install(app)+ }++ private fun setContent(content: @Composable () -> Unit) =+ rule.setContent {+ CompositionLocalProvider(LocalColumnCount provides columnsState) { content() }+ }++ private fun stack(vararg routes: Route): NavBackStack<Route> = NavBackStack(routes)++ private fun photo(name: String, date: Long, trashed: Boolean = false, lat: Double? = null) = Photo(+ name = name, uri = "content://media/$name", date = date, width = 100, height = 100,+ dateModified = date, exifSet = true, lat = lat, long = lat?.let { -it },+ videoData = null, panoData = null, isTrashed = trashed,+ )++ private fun clickEverything(max: Int = 10) {+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, max)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }++ @Test fun peoplePageWithPersonOpensCluster() = runBlocking {+ installed.photos.upsertAll(listOf(photo("group.jpg", 300L), photo("solo.jpg", 200L)))+ val all = installed.photos.getAll().associateBy { it.name }+ val faces = listOf(all.getValue("group.jpg"), all.getValue("solo.jpg")).map { p ->+ com.vayunmathur.photos.data.PhotoFace(+ photoId = p.id, clusterId = null,+ embedding = com.vayunmathur.photos.util.FaceRecognizer.floatsToBytes(FloatArray(4) { 1f }),+ clusterable = true, left = 0f, top = 0f, right = 0.5f, bottom = 0.5f,+ srcWidth = 100, srcHeight = 100,+ )+ }+ installed.faces.commitFaceScan(all.values.map { it.id }, faces)+ val rows = installed.faces.getClusterRows()+ installed.faces.applyClustering(+ listOf(com.vayunmathur.photos.data.ResolvedPersonRow(null, rows.first().embedding, rows.map { it.id })),+ emptyList(),+ )+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ setContent { DynamicTheme { PeoplePage(stack(Route.Gallery), gallery) } }+ rule.waitForIdle()+ clickEverything()+ assertTrue(rule.onAllNodesWithText("group.jpg", substring = true).fetchSemanticsNodes().isNotEmpty() ||+ rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty())+ Unit+ }++ @Test fun albumsPageOpensFavoritesAndSecureTiles() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("fav.jpg", 300L), photo("plain.jpg", 200L),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ // Mark one a favorite in Room so the Favorites tile has content.+ val fav = installed.photos.getAll().first { it.name == "fav.jpg" }+ installed.photos.setFavorite(listOf(fav.id), true)+ val secureVm = SecureFolderViewModel(app)+ setContent {+ DynamicTheme {+ com.vayunmathur.photos.ui.AlbumsPage(+ stack(Route.Gallery), gallery, secureVm,+ )+ }+ }+ rule.waitForIdle()+ clickEverything(12)+ Unit+ }++ @Test fun trashPageSelectionChrome() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("gone1.jpg", 300L, trashed = true), photo("gone2.jpg", 200L, trashed = true),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val secureVm = SecureFolderViewModel(app)+ setContent { DynamicTheme { TrashPage(stack(Route.Gallery), gallery) } }+ rule.waitForIdle()+ clickEverything()+ Unit+ }++ @Test fun secureFolderPageWithVaultRows() = runBlocking {+ val vault = TestPhotosRepository.installVault(app)+ vault.upsert(VaultPhoto(+ name = "secret.jpg", path = "/vault/secret.enc", thumbnailPath = "/vault/secret_thumb.enc",+ date = 1L, width = 100, height = 100, dateModified = 1L,+ ))+ val secure = SecureFolderViewModel(app)+ // VaultRepository keeps its DAO behind the RoomRepository delegate;+ // read the injected in-memory database back out reflectively.+ var type: Class<*>? = vault.javaClass+ var dao: com.vayunmathur.photos.data.VaultPhotoDao? = null+ while (type != null && dao == null) {+ for (field in type.declaredFields) {+ if (field.type == Lazy::class.java || field.name.contains("db", ignoreCase = true)) {+ runCatching {+ field.isAccessible = true+ val db = (field.get(vault) as Lazy<*>).value+ dao = db!!.javaClass.getMethod("vaultPhotoDao").invoke(db) as com.vayunmathur.photos.data.VaultPhotoDao+ }+ }+ }+ type = type.superclass+ }+ secure.setVault(dao!!, "pw")+ setContent { DynamicTheme { SecureFolderPage(stack(Route.Gallery), "pw", secure) } }+ rule.waitForIdle()+ assertTrue(rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().isNotEmpty())+ clickEverything()+ Unit+ }++ @Test fun wallpaperPageRendersControls() = runBlocking {+ installed.photos.upsertAll(listOf(photo("wall.jpg", 100L)))+ setContent { DynamicTheme { WallpaperPage(stack(Route.Gallery), null) } }+ rule.waitForIdle()+ clickEverything()+ Unit+ }++ @Test fun photoPageViewerChrome() = runBlocking {+ installed.photos.upsertAll(listOf(+ photo("one.jpg", 300L, lat = 37.0), photo("two.jpg", 200L),+ ))+ val gallery = GalleryViewModel(app).also { it.runSyncHook = {} }+ val first = installed.photos.getAll().first { it.name == "one.jpg" }+ val mapVm = PhotoMapViewModel(app)+ setContent {+ DynamicTheme {+ PhotoPage(gallery, mapVm, first.id, null, null, stack(Route.Gallery))+ }+ }+ rule.waitForIdle()+ clickEverything()+ Unit+ }+}
photos/src/test/java/com/vayunmathur/photos/ui/SelectiveHealingDrawingDriveTest.kt
diff --git a/photos/src/test/java/com/vayunmathur/photos/ui/SelectiveHealingDrawingDriveTest.kt b/photos/src/test/java/com/vayunmathur/photos/ui/SelectiveHealingDrawingDriveTest.ktnew file mode 100644index 0000000000..f5593390a5--- /dev/null+++ b/photos/src/test/java/com/vayunmathur/photos/ui/SelectiveHealingDrawingDriveTest.kt@@ -0,0 +1,94 @@+package com.vayunmathur.photos.ui++import androidx.compose.foundation.layout.Column+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.ui.test.hasClickAction+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.performClick+import androidx.test.ext.junit.runners.AndroidJUnit4+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.photos.data.MaskType+import com.vayunmathur.photos.data.SelectiveMask+import com.vayunmathur.photos.data.DrawingTool+import org.junit.Rule+import org.junit.runner.RunWith+import kotlin.test.Test+import kotlin.test.assertTrue++/**+ * Selective-edit, healing and drawing-settings panels: every mask type,+ * brush control and tool setting is composed and pressed.+ */+@RunWith(AndroidJUnit4::class)+class SelectiveHealingDrawingDriveTest {++ @get:Rule val rule = createComposeRule()++ private fun clickEverything(max: Int = 12) {+ val count = rule.onAllNodes(hasClickAction()).fetchSemanticsNodes().size+ for (i in 0 until minOf(count, max)) {+ runCatching { rule.onAllNodes(hasClickAction())[i].performClick() }+ runCatching { rule.waitForIdle() }+ }+ }++ @Test fun selectivePanelForEveryMaskType() {+ val holder = arrayOfNulls<androidx.compose.runtime.MutableState<SelectiveMask>>(1)+ rule.setContent {+ val mask = remember { mutableStateOf(SelectiveMask(type = MaskType.Brush)) }+ holder[0] = mask+ Column {+ SelectiveEditPanel(+ mask = mask.value, showMask = true,+ onMaskChanged = { mask.value = it },+ onShowMaskChanged = {},+ onAddMask = {},+ )+ }+ }+ for (type in MaskType.entries) {+ holder[0]!!.value = SelectiveMask(type = type)+ rule.waitForIdle()+ clickEverything()+ }+ assertTrue(true)+ }++ @Test fun healingPanelControls() {+ rule.setContent {+ val size = remember { mutableStateOf(24f) }+ val source = remember { mutableStateOf(false) }+ Column {+ HealingPanel(+ brushSize = size.value, isSettingSource = source.value,+ onBrushSizeChanged = { size.value = it },+ onSetSourceToggled = { source.value = it },+ )+ }+ }+ rule.waitForIdle()+ clickEverything()+ assertTrue(true)+ }++ @Test fun drawingSettingsForEveryTool() {+ for (tool in DrawingTool.entries) {+ val stack = NavBackStack<EditRoute>(arrayOf(EditRoute.EditPhoto(0L)))+ rule.setContent {+ androidx.compose.runtime.CompositionLocalProvider(+ com.vayunmathur.library.util.LocalNavResultRegistry provides com.vayunmathur.l
Diff truncated.