Cotton code
174 lines · 7.0 KB · KotlinRaw
package com.cottondb.androidimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.navigation.Routeimport com.cottondb.android.work.reader.ReaderMutationResultimport java.util.concurrent.CopyOnWriteArrayListimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.JsonArrayimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotSameimport org.junit.Assert.assertNullimport org.junit.Assert.assertSameimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith/** Exercises retained Reader hosts on Android's serial main dispatcher with real Reader wire shapes. */@RunWith(AndroidJUnit4::class)class ReaderModelsTest {    private val fixtures = CopyOnWriteArrayList<Fixture>()    @After fun closeModels() = onMain {        fixtures.forEach(Fixture::close)        fixtures.clear()    }    @Test fun retainedReaderStackKeepsListAndPageIdentity() = onMain {        val fixture = fixture()        val list = fixture.models.list()        val page = fixture.models.page("page-1")        fixture.models.retain(listOf(Route.Reader, Route.ReaderPage("page-1")))        assertSame(list, fixture.models.list())        assertSame(page, fixture.models.page("page-1"))    }    @Test fun removingPageClosesItsWriterAndNewVisitResetsWebState() = onMain {        val fixture = fixture()        val retired = fixture.models.page("page-1")        runBlocking { retired.model.refresh() }        retired.navigated("https://reader.example.test/old", "Synthetic title")        fixture.models.retain(listOf(Route.Reader))        val refused = runBlocking { retired.model.archive().await() }        assertTrue(refused is ReaderMutationResult.Refused)        assertEquals("This Reader page is no longer open.", (refused as ReaderMutationResult.Refused).message)        assertTrue(fixture.writes.none { it.tool == "archive_page" })        val reopened = fixture.models.page("page-1")        assertNotSame(retired, reopened)        assertNull(reopened.web.value.liveAddress)        assertNull(reopened.web.value.failure)        assertEquals(0L, reopened.web.value.attempt)    }    @Test fun webStateKeepsAddressAcrossFailureAndRetryAndLearnsProviderTitleOnce() {        val fixture = onMain { fixture() }        val visit = onMain {            fixture.models.page("page-1").also { runBlocking { it.model.refresh() } }        }        onMain {            visit.navigated("https://reader.example.test/reader", "  Learned page title  ")            visit.failed("Synthetic network failure")            visit.retryWeb()            visit.navigated("https://reader.example.test/reader", "Learned page title")        }        InstrumentationRegistry.getInstrumentation().waitForIdleSync()        assertEquals("https://reader.example.test/reader", visit.web.value.liveAddress)        assertNull(visit.web.value.failure)        assertEquals(1L, visit.web.value.attempt)        val titleWrites = fixture.writes.filter { it.tool == "update_page" }        assertEquals(1, titleWrites.size)        assertEquals("page-1", titleWrites.single().args["id"]?.jsonObjectOrPrimitiveContent())        assertEquals("Learned page title", titleWrites.single().args["title"]?.jsonObjectOrPrimitiveContent())        assertFalse(visit.model.mutation.value.busy)    }    private fun fixture() = Fixture().also(fixtures::add)    private fun <T> onMain(block: () -> T): T {        var result: Result<T>? = null        InstrumentationRegistry.getInstrumentation().runOnMainSync { result = runCatching(block) }        return requireNotNull(result).getOrThrow()    }    private class Fixture {        private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        val core = ReaderCore()        val models = ReaderModels(core, scope)        val writes get() = core.writes        fun close() = scope.cancel()    }    private class ReaderCore : CottonCalling {        data class Write(val tool: String, val args: JsonObject)        override val events: SharedFlow<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        val writes = CopyOnWriteArrayList<Write>()        override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) {            "read.pages" -> buildJsonObject { put("pages", JsonArray(listOf(page()))) }            "read.page" -> buildJsonObject {                put("page", page())                put("projects", JsonArray(emptyList()))                put("links", JsonArray(emptyList()))            }            "write" -> write(request)            else -> error("Unexpected core method: $method")        }        override suspend fun close() = Unit        private fun write(request: JsonObject): JsonElement {            val tool = request["tool"]!!.jsonObjectOrPrimitiveContent()            val args = request["args"]!!.jsonObject            writes += Write(tool, args)            return buildJsonObject {                put("answer", buildJsonObject {                    when (tool) {                        "update_page" -> {                            put("id", args["id"]!!.jsonObjectOrPrimitiveContent())                            put("changed", true)                        }                        "archive_page" -> {                            put("id", args["id"]!!.jsonObjectOrPrimitiveContent())                            put("archived", true)                        }                        else -> error("Unexpected Reader write: $tool")                    }                })            }        }        private fun page() = buildJsonObject {            put("id", "page-1")            put("url", "https://reader.example.test/reader")            put("host", "reader.example.test")            put("title", JsonNull)            put("readAt", JsonNull)            put("createdAt", "2026-09-22T09:00:00Z")            put("updatedAt", "2026-09-22T09:00:00Z")            put("archivedAt", JsonNull)            put("sourceInboxId", JsonNull)        }    }}private fun JsonElement.jsonObjectOrPrimitiveContent(): String = when (this) {    is JsonPrimitive -> content    else -> error("Expected a string primitive.")}