Cotton code
246 lines · 13.9 KB · KotlinRaw
package com.cottondb.android.ui.photosimport android.graphics.Bitmapimport android.graphics.Colorimport androidx.compose.runtime.keyimport androidx.compose.runtime.mutableLongStateOfimport androidx.compose.runtime.mutableStateOfimport androidx.compose.ui.test.assertIsEnabledimport androidx.compose.ui.test.assertIsNotEnabledimport androidx.compose.ui.test.junit4.createComposeRuleimport androidx.compose.ui.test.onAllNodesWithContentDescriptionimport androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.performClickimport androidx.compose.ui.test.performTextClearanceimport androidx.compose.ui.test.performTextInputimport androidx.compose.ui.test.performScrollToimport androidx.compose.ui.test.onRootimport androidx.compose.ui.test.captureToImageimport androidx.compose.ui.graphics.asAndroidBitmapimport androidx.test.ext.junit.runners.AndroidJUnit4import com.cottondb.android.PhotosModelsimport com.cottondb.android.FeatureModelsimport com.cottondb.android.PasswordModelsimport com.cottondb.android.ScreenEvidenceimport com.cottondb.android.core.CoreExceptionimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.home.HomeStateimport com.cottondb.android.boot.BootReadimport com.cottondb.android.media.LocalMediaimport com.cottondb.android.media.LocalMediaFileimport com.cottondb.android.media.LocalMediaSourceimport com.cottondb.android.media.MediaSourceimport com.cottondb.android.media.MediaPathTierimport com.cottondb.android.media.EnsuredMediaimport com.cottondb.android.navigation.Routeimport java.io.Fileimport java.io.FileOutputStreamimport java.time.Clockimport java.time.Instantimport java.time.ZoneOffsetimport java.util.concurrent.atomic.AtomicIntegerimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNullimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWith/** Route-level regressions: retained writes must never be replayed by recomposition or revision reads. */@RunWith(AndroidJUnit4::class)class AlbumsRouteTest {    @get:Rule val compose = createComposeRule()    private var fixture: Fixture? = null    @After fun closeFixture() {        val current = fixture ?: return        compose.runOnIdle { current.visible.value = false }        compose.waitForIdle()        compose.runOnIdle { current.close() }        fixture = null    }    @Test fun confirmedTitleWithFailedRereadSurvivesRemountWithoutReplay() {        val f = show(Route.PhotosAlbum(ALBUM))        await("Album title")        compose.onNodeWithContentDescription("Album title").performScrollTo()        compose.onNodeWithContentDescription("Album title").performTextClearance()        compose.onNodeWithContentDescription("Album title").performTextInput("After")        f.core.failAlbumReads = true        compose.runOnIdle { assertEquals("After", f.models.album(Route.PhotosAlbum(ALBUM)).state.value.titleDraft) }        compose.onNodeWithContentDescription("Save album title").assertIsEnabled().performScrollTo().performClick()        compose.waitUntil(5_000) { f.core.writes.get() == 1 && f.core.albumReads.get() >= 2 }        compose.onNodeWithText("Synthetic reread failed").assertExists()        f.remount()        compose.waitUntil(5_000) { f.core.albumReads.get() >= 3 }        assertEquals(1, f.core.writes.get())        assertEquals("update_album", f.core.tools.single())    }    @Test fun unknownTitleReceiptStaysFrozenAcrossRevisionReads() {        val f = show(Route.PhotosAlbum(ALBUM))        await("Album title")        compose.onNodeWithContentDescription("Album title").performScrollTo()        compose.onNodeWithContentDescription("Album title").performTextClearance()        compose.onNodeWithContentDescription("Album title").performTextInput("After")        f.core.malformedWrite = true        compose.runOnIdle { assertEquals("After", f.models.album(Route.PhotosAlbum(ALBUM)).state.value.titleDraft) }        compose.onNodeWithContentDescription("Save album title").assertIsEnabled().performScrollTo().performClick()        compose.waitUntil(5_000) { f.core.writes.get() == 1 }        compose.runOnIdle { f.revision.longValue += 1 }        compose.waitForIdle()        compose.onNodeWithContentDescription("Save album title").assertIsNotEnabled()        compose.runOnIdle { assertFalse(f.models.album(Route.PhotosAlbum(ALBUM)).state.value.canAct) }        assertEquals(1, f.core.writes.get())    }    @Test fun selectedAddConfirmsBackOnceAndDoesNotReplayOnRemount() {        val f = show(Route.PhotosAlbumAdd(ALBUM))        await("Photo tile photo:add: Picture")        compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick()        compose.onNodeWithContentDescription("Add the selected pictures").performClick()        compose.waitUntil(5_000) { f.back.get() == 1 && f.core.writes.get() == 1 }        f.remount()        compose.waitForIdle()        assertEquals(1, f.back.get())        assertEquals(1, f.core.writes.get())    }    @Test fun appNavigationDeepLinkOpensAlbumAddsAndRetiresTheCompletedAddVisit() {        val f = Fixture(); fixture = f        val features = f.features()        compose.setContent {            CottonTheme {                if (f.visible.value) com.cottondb.android.ui.navigation.AppNavigation(                    home = HomeState.Error("Synthetic home"),                    boot = BootRead(true, "joined", null, "synthetic-workspace", null, "Cotton", null),                    features = features,                    onJoin = {}, onLeave = {}, onRefreshHome = {}, onSaveArrangement = {},                    notificationRoute = Route.PhotosAlbums,                )            }        }        await("Album Before")        ScreenEvidence.capture("albums-list-route") { compose.onRoot().captureToImage().asAndroidBitmap() }        compose.onNodeWithContentDescription("Album Before").performClick()        await("Album title")        ScreenEvidence.capture("album-detail-route") { compose.onRoot().captureToImage().asAndroidBitmap() }        compose.onNodeWithContentDescription("Add photos").performClick()        await("Photo tile photo:add: Picture")        lateinit var retired: com.cottondb.android.traffic.photos.albums.AlbumAddModel        compose.runOnIdle { retired = features.photos.albumAdd(Route.PhotosAlbumAdd(ALBUM)) }        compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick()        compose.onNodeWithContentDescription("Add the selected pictures").performClick()        compose.waitUntil(5_000) { f.core.writes.get() == 1 }        await("Album title")        compose.runOnIdle { assertNull(retired.refresh()) }    }    @Test fun knownAddRefusalKeepsSelectionOnTheAddRoute() {        val f = show(Route.PhotosAlbumAdd(ALBUM))        await("Photo tile photo:add: Picture")        compose.onNodeWithContentDescription("Photo tile photo:add: Picture").performClick()        f.core.refuseWrite = true        compose.onNodeWithContentDescription("Add the selected pictures").performClick()        compose.waitUntil(5_000) { f.core.writes.get() == 1 }        compose.onNodeWithText("Album is locked").assertExists()        assertEquals(0, f.back.get())        compose.onNodeWithText("1 selected").assertExists()    }    private fun show(route: Route): Fixture {        val fresh = Fixture(); fixture = fresh        compose.setContent { CottonTheme { if (fresh.visible.value) key(fresh.remount.value) {            AlbumsRoute(route, fresh.models, fresh.media, CLOCK, fresh.revision.longValue, { fresh.back.incrementAndGet() }, {})        } } }        return fresh    }    private fun await(description: String) = compose.waitUntil(5_000) {        compose.onAllNodesWithContentDescription(description).fetchSemanticsNodes().isNotEmpty()    }    private class Fixture {        val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        val core = Core(); val models = PhotosModels(core, scope); val media = LocalOnlyMedia()        val visible = mutableStateOf(true); val remount = mutableLongStateOf(0); val revision = mutableLongStateOf(0)        val back = AtomicInteger()        fun remount() { composeMain { remount.longValue++ } }        fun features(): FeatureModels {            val context = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext            val access = com.cottondb.android.passwords.VaultAccess(core)            val session = com.cottondb.android.passwords.VaultSession(                access, com.cottondb.android.passwords.VaultOperations(access, com.cottondb.android.passwords.VaultKeyRepublisher {}), scope, {},            )            return FeatureModels(                core, CLOCK, scope, media, com.cottondb.android.ui.traffic.messages.AndroidWhatsAppExportStager(context),                PasswordModels(core, scope, CLOCK, session) {},                object : com.cottondb.android.search.SearchRecentsStore { override fun load() = emptyList<String>(); override fun save(recents: List<String>) = Unit },                com.cottondb.android.ui.imports.AndroidSafFileStager(context, "album-route-test", "document"),            )        }        fun close() { models.retain(emptyList()); scope.cancel(); media.close() }    }    private class Core : CottonCalling {        override val events: SharedFlow<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        val albumReads = AtomicInteger(); val writes = AtomicInteger(); val tools = mutableListOf<String>()        var failAlbumReads = false; var malformedWrite = false; var refuseWrite = false        private var title = "Before"        override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) {            "read.album" -> { albumReads.incrementAndGet(); if (failAlbumReads) throw IllegalStateException("Synthetic reread failed") else album(title) }            "read.addablePhotos" -> addable()            "read.albums" -> buildJsonObject { put("albums", buildJsonArray { add(card(title)) }) }            "write" -> { writes.incrementAndGet(); tools += request["tool"]!!.jsonPrimitive.content                if (refuseWrite) throw CoreException("locked", "Album is locked", null)                if (malformedWrite) buildJsonObject { put("answer", buildJsonObject {}) }                else {                    request["args"]!!.jsonObject["title"]?.jsonPrimitive?.content?.let { title = it }                    buildJsonObject { put("answer", receipt(title)) }                }            }            else -> error(method)        }        override suspend fun close() = Unit    }    private class LocalOnlyMedia : MediaSource {        private val file = File(androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().targetContext.cacheDir, "album-cover.png").also { target ->            val bitmap = Bitmap.createBitmap(12, 12, Bitmap.Config.ARGB_8888)            try { bitmap.eraseColor(Color.rgb(26, 61, 85)); FileOutputStream(target).use { check(bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)) } } finally { bitmap.recycle() }        }        override suspend fun local(key: String, tier: MediaPathTier): LocalMedia = if (key == "cover") LocalMedia.Present(LocalMediaFile(file), com.cottondb.android.media.ResolvedMediaTier.Thumb) else LocalMedia.Absent        override suspend fun ensure(key: String): EnsuredMedia = error("album renderer must not fetch")        override suspend fun viewed(key: String): Boolean = false        fun close() { file.delete() }    }}private const val ALBUM = "album:synthetic"private val CLOCK: Clock = Clock.fixed(Instant.parse("2026-01-01T00:00:00Z"), ZoneOffset.UTC)private fun composeMain(block: () -> Unit) = androidx.test.platform.app.InstrumentationRegistry.getInstrumentation().runOnMainSync(block)private fun card(title: String) = buildJsonObject { put("id", ALBUM); listOf("kind","state","decidedAt","title","titleBy","startsAt","endsAt","homeLabel","coverId","createdAt","updatedAt").forEach { put(it, if (it == "state") JsonPrimitive("open") else if (it == "title") JsonPrimitive(title) else JsonNull) }; put("members", 1); put("people", buildJsonArray {}); put("cover", buildJsonObject { put("key", "cover"); put("preview", JsonNull) }) }private fun album(title: String) = card(title).toMutableMap().apply { put("items", buildJsonArray { add(buildJsonObject { put("id", "photo:member"); put("kind", "photo"); put("addedBy", JsonNull); put("sortAt", JsonNull) }) }); put("projects", buildJsonArray {}) }.let(::JsonObject)private fun addable() = buildJsonObject { put("photos", buildJsonArray { add(buildJsonObject { put("id", "photo:add"); listOf("key","preview","description","takenAt","contentType").forEach { put(it, JsonNull) }; put("caption", "Picture"); put("sizeBytes", 0); put("favourite", false); put("people", buildJsonArray {}); put("projects", buildJsonArray {}) }) }) }private fun receipt(title: String) = buildJsonObject { card(title).forEach { (key, value) -> put(key, value) }; put("items", buildJsonArray {}); put("projects", buildJsonArray {}) }