201 lines · 10.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.money.MoneyReadStateimport java.time.Clockimport java.time.Instantimport java.time.ZoneIdimport 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.jsonPrimitiveimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertNotSameimport org.junit.Assert.assertSameimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith/** Retained Account hosts keep native reads local to the routes that requested them. */@RunWith(AndroidJUnit4::class)class MoneyModelsTest { private val fixtures = CopyOnWriteArrayList<Fixture>() @After fun closeModels() = onMain { fixtures.forEach(Fixture::close) fixtures.clear() } @Test fun typedVisitsUseInjectedLocalDayAndExactReadMethods() { val fixture = onMain { fixture() } val overview = onMain { fixture.models.overview() } val account = onMain { fixture.models.account("account-1") } val statement = onMain { fixture.models.statement("statement-1") } val transaction = onMain { fixture.models.transaction("transaction-1") } runBlocking { overview.refresh().join() account.refresh().join() statement.refresh().join() transaction.refresh().join() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertEquals("2026-09-23", fixture.request("read.money")["today"]!!.jsonPrimitive.content) assertEquals("2026-09-23", fixture.request("read.moneyAccount")["today"]!!.jsonPrimitive.content) assertEquals("account-1", fixture.request("read.moneyAccount")["accountId"]!!.jsonPrimitive.content) assertEquals("statement-1", fixture.request("read.statement")["id"]!!.jsonPrimitive.content) assertEquals("transaction-1", fixture.request("read.transaction")["id"]!!.jsonPrimitive.content) assertTrue(overview.state.value is MoneyReadState.Data) assertTrue(account.state.value is MoneyReadState.Data) assertTrue(statement.state.value is MoneyReadState.Data) assertTrue(transaction.state.value is MoneyReadState.Data) } @Test fun retainedStackKeepsTypedVisitIdentityAndPoppedVisitRefusesFutureRefresh() = onMain { val fixture = fixture() val overview = fixture.models.overview() val account = fixture.models.account("account-1") val statement = fixture.models.statement("statement-1") val transaction = fixture.models.transaction("transaction-1") fixture.models.retain(listOf(Route.Money, Route.MoneyAccount("account-1"), Route.MoneyStatement("statement-1"), Route.MoneyTransaction("transaction-1"))) assertSame(overview, fixture.models.overview()) assertSame(account, fixture.models.account("account-1")) assertSame(statement, fixture.models.statement("statement-1")) assertSame(transaction, fixture.models.transaction("transaction-1")) fixture.models.retain(listOf(Route.Money)) runBlocking { account.refresh().join() } assertFalse(fixture.core.methods.contains("read.moneyAccount")) assertNotSame(account, fixture.models.account("account-1")) assertNotSame(statement, fixture.models.statement("statement-1")) assertNotSame(transaction, fixture.models.transaction("transaction-1")) } @Test fun blankRouteIdsAreVisibleErrorsAndNeverReachNative() = onMain { val fixture = fixture() val account = fixture.models.account(" ") val statement = fixture.models.statement("\t") val transaction = fixture.models.transaction("") runBlocking { account.refresh().join() statement.refresh().join() transaction.refresh().join() } assertEquals("This account could not be opened.", (account.state.value as MoneyReadState.Error).message) assertEquals("This statement could not be opened.", (statement.state.value as MoneyReadState.Error).message) assertEquals("This transaction could not be opened.", (transaction.state.value as MoneyReadState.Error).message) assertTrue(fixture.core.methods.isEmpty()) } @Test fun failureRemainsVisibleWithNoSyntheticData() { val fixture = onMain { fixture(failStatement = true) } val statement = onMain { fixture.models.statement("statement-1") } runBlocking { statement.refresh().join() } InstrumentationRegistry.getInstrumentation().waitForIdleSync() val failure = statement.state.value as MoneyReadState.Error assertEquals("Synthetic statement failure", failure.message) assertEquals(null, failure.last) } @Test fun retirementCancelsOwnedReadAndLateNativeAnswerCannotUpdateRetiredVisit() { val fixture = onMain { fixture(blockAccount = true) } val retired = onMain { fixture.models.account("account-1") } onMain { retired.refresh() } assertTrue(fixture.core.accountEntered.await(3, TimeUnit.SECONDS)) onMain { fixture.models.retain(emptyList()) } fixture.core.releaseAccount() InstrumentationRegistry.getInstrumentation().waitForIdleSync() assertTrue(retired.state.value is MoneyReadState.Loading) assertNotSame(retired, onMain { fixture.models.account("account-1") }) } private fun fixture(failStatement: Boolean = false, blockAccount: Boolean = false) = Fixture(failStatement, blockAccount).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(failStatement: Boolean, blockAccount: Boolean) { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) val core = MoneyCore(failStatement, blockAccount) val models = MoneyModels( core = core, clock = Clock.fixed(Instant.parse("2026-09-22T23:30:00Z"), ZoneOffset.UTC), zone = ZoneId.of("Asia/Kolkata"), scope = scope, ) fun request(method: String): JsonObject = core.requests.single { it.first == method }.second fun close() = scope.cancel() } private class MoneyCore( private val failStatement: Boolean, private val blockAccount: Boolean, ) : CottonCalling { override val events: SharedFlow<CottonEvent> = MutableSharedFlow() override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow() val methods = CopyOnWriteArrayList<String>() val requests = CopyOnWriteArrayList<Pair<String, JsonObject>>() val accountEntered = CountDownLatch(1) private val accountReply = CompletableDeferred<JsonElement>() override suspend fun call(method: String, request: JsonObject): JsonElement { methods += method requests += method to request return when (method) { "read.money" -> json(MONEY) "read.moneyAccount" -> if (blockAccount) { accountEntered.countDown() withContext(NonCancellable) { accountReply.await() } } else json(ACCOUNT) "read.statement" -> if (failStatement) error("Synthetic statement failure") else json(STATEMENT) "read.transaction" -> json(TRANSACTION) else -> error("Unexpected core method: $method") } } override suspend fun close() = Unit fun releaseAccount() { accountReply.complete(json(ACCOUNT)) } } private companion object { fun json(raw: String): JsonElement = Json.parseToJsonElement(raw) const val MONEY = """{"currency":"INR","accounts":[],"month":{"key":"2026-09","spentMinor":0,"receivedMinor":0,"unaccountedMinor":0}}""" const val ACCOUNT = """{"account":{"id":"account-1","name":"Synthetic account","kind":"asset","subtype":"bank","currency":"INR","institution":null,"numberMask":null},"liveBalanceMinor":0,"rows":[],"statements":[],"gaps":[]}""" const val TRANSACTION = """{"transaction":{"id":"transaction-1","occurredOn":"2026-09-22","description":"Synthetic transaction","personId":null,"status":null,"source":null,"notes":null,"dueDate":null,"settlesTransactionId":null,"classifiedBy":null,"classifiedByLabel":null,"confidenceBps":null,"payeeText":null,"period":null},"lines":[],"evidence":[],"categories":[],"people":[]}""" const val STATEMENT = """{"id":"statement-1","documentId":"document-1","accountId":"account-1","kind":"bank","period":{"from":"2026-09-01","to":"2026-09-30"},"openingBalanceMinor":0,"closingBalanceMinor":0,"currency":"INR","readStatus":"read","readError":null,"readBy":null,"readAt":null,"balanceCheck":"ok","lineCount":0,"sumInMinor":0,"sumOutMinor":0,"account":{"id":"account-1","name":"Synthetic account","kind":"asset","subtype":"bank","currency":"INR","institution":null,"numberMask":null},"lines":[]}""" }}