Cotton code
143 lines · 6.7 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.money.MoneyFormStateimport com.cottondb.android.work.money.MoneyRecordVerbimport com.cottondb.android.work.money.MoneyWriteResultimport java.time.Clockimport java.time.Instantimport java.time.ZoneOffsetimport java.util.concurrent.CopyOnWriteArrayListimport java.util.concurrent.CountDownLatchimport java.util.concurrent.TimeUnitimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.NonCancellableimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.cancelimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport 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/** Android-main lifetime checks for retained record and deletion visits. */@RunWith(AndroidJUnit4::class)class MoneyWriteVisitsTest {    private val fixtures = CopyOnWriteArrayList<Fixture>()    @After fun closeFixtures() {        onMain {            fixtures.forEach(Fixture::close)            fixtures.clear()        }    }    @Test fun deletionConsumesItsReceiptOnceAndRetirementRefusesFurtherActions() {        val fixture = onMain { fixture() }        val deletion = onMain { fixture.models.deletion("transaction-1") }        val job = onMain { requireNotNull(deletion.deleteConfirmed()) }        runBlocking { job.join() }        InstrumentationRegistry.getInstrumentation().waitForIdleSync()        assertTrue(onMain { deletion.consumeDeleted() })        assertFalse(onMain { deletion.consumeDeleted() })        assertNull(onMain { deletion.deleteConfirmed() })        assertEquals(1, fixture.core.deleteCalls)        onMain { fixture.models.retain(emptyList()) }        assertNull(onMain { deletion.deleteConfirmed() })        assertEquals(1, fixture.core.deleteCalls)    }    private fun fixture(blockRecord: Boolean = false, malformedRecord: Boolean = false) =        Fixture(blockRecord, malformedRecord).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(blockRecord: Boolean, malformedRecord: Boolean) {        private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        val core = WriteCore(blockRecord, malformedRecord)        val models = MoneyModels(            core = core,            clock = Clock.fixed(Instant.parse("2026-09-22T23:30:00Z"), ZoneOffset.UTC),            zone = java.time.ZoneId.of("Asia/Kolkata"),            scope = scope,        )        fun close() = scope.cancel()    }    private class WriteCore(        private val blockRecord: Boolean,        private val malformedRecord: Boolean,    ) : CottonCalling {        override val events: SharedFlow<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        val writeArgs = CopyOnWriteArrayList<JsonObject>()        val recordEntered = CountDownLatch(1)        private val recordReply = CompletableDeferred<JsonElement>()        var deleteCalls = 0            private set        override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) {            "read.moneyForm" -> json(FORM)            "write" -> write(request)            else -> error("Unexpected core method: $method")        }        override suspend fun close() = Unit        fun releaseRecord() { recordReply.complete(json(RECORD)) }        private suspend fun write(request: JsonObject): JsonElement {            val tool = request["tool"]!!.jsonPrimitive.content            val args = request["args"]!!.jsonObject            return when (tool) {                "record_transaction" -> {                    writeArgs += args                    if (malformedRecord) json("""{"answer":{"id":"transaction-1"}}""") else if (blockRecord) {                        recordEntered.countDown()                        withContext(NonCancellable) { recordReply.await() }                    } else json(RECORD)                }                "delete_transaction" -> {                    deleteCalls += 1                    json("""{"answer":{"deleted":true,"id":"transaction-1","description":"Lunch","occurredOn":"2026-09-23"}}""")                }                else -> error("Unexpected money tool: $tool")            }        }    }    private companion object {        fun json(raw: String): JsonElement = Json.parseToJsonElement(raw)        const val FORM = """{"currency":"INR","accounts":[            {"id":"bank","name":"Bank","kind":"asset","subtype":"bank","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null},            {"id":"food","name":"Food","kind":"expense","subtype":"category","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null},            {"id":"other-food","name":"Other food","kind":"expense","subtype":"category","personId":null,"currency":"INR","institution":null,"numberMask":null,"archived":false,"balanceMinor":0,"postedBalanceMinor":null,"counts":null,"coverage":null,"gaps":[],"lastStatement":null}],"people":[{"id":"person-1","fullName":"Synthetic person"}]}"""        const val RECORD = """{"answer":{"id":"transaction-1","verb":"spent","occurredOn":"2026-09-23","description":"Lunch","amountMinor":1250,"personId":null,"lines":[{"accountId":"bank","account":"Bank","amountMinor":-1250},{"accountId":"food","account":"Food","amountMinor":1250}]}}"""    }}