150 lines · 5.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 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.JsonArrayimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonNullimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport kotlinx.serialization.json.putimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNotSameimport org.junit.Assert.assertNullimport org.junit.Assert.assertSameimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class BriefingModelsTest { private val fixtures = mutableListOf<Fixture>() @After fun closeFixtures() = onMain { fixtures.forEach(Fixture::close) fixtures.clear() } @Test fun retainKeepsOnlyTheKeyedBriefingVisitAndReacquiresRemovedVisits() { val fixture = onMain { Fixture().also(fixtures::add) } val note = Route.Briefing(null) val todo = Route.Briefing("todo-1") val noteModel = onMain { fixture.models.briefing(note) } val todoModel = onMain { fixture.models.briefing(todo) } join(onMain { requireNotNull(noteModel.refresh()) }) join(onMain { requireNotNull(todoModel.refresh()) }) onMain { fixture.models.retain(listOf(todo)) } assertNull(onMain { noteModel.refresh() }) assertSame(todoModel, onMain { fixture.models.briefing(todo) }) assertEquals("todo-1", onMain { requireNotNull(todoModel.state.value.read).briefedProjects.single() }) val replacement = onMain { fixture.models.briefing(note) } assertNotSame(noteModel, replacement) join(onMain { requireNotNull(replacement.refresh()) }) assertEquals("default", onMain { requireNotNull(replacement.state.value.read).briefedProjects.single() }) } @Test fun closingAKeyedRouteBeforeItsNonCooperativeReadReturnsDropsTheLateReply() { val fixture = onMain { Fixture().also(fixtures::add) } val route = Route.Briefing("blocked-note") fixture.core.blockId = route.project val old = onMain { fixture.models.briefing(route) } val pending = onMain { requireNotNull(old.refresh()) } assertTrue(fixture.core.entered.await(3, TimeUnit.SECONDS)) onMain { fixture.models.retain(emptyList()) } fixture.core.release() runBlocking { pending.join() } assertTrue(pending.isCancelled) assertNull(onMain { old.state.value.read }) assertNull(onMain { old.refresh() }) fixture.core.blockId = null val replacement = onMain { fixture.models.briefing(route) } assertNotSame(old, replacement) join(onMain { requireNotNull(replacement.refresh()) }) assertEquals(route.project, onMain { requireNotNull(replacement.state.value.read).briefedProjects.single() }) } private fun join(job: kotlinx.coroutines.Job) = runBlocking { job.join() } 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 = BriefingCore() val models = BriefingModels(core, scope) fun close() { core.release() scope.cancel() } } private class BriefingCore : CottonCalling { override val events: SharedFlow<CottonEvent> = MutableSharedFlow() override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow() val entered = CountDownLatch(1) private val reply = CompletableDeferred<JsonElement>() var blockId: String? = null override suspend fun call(method: String, request: JsonObject): JsonElement { check(method == "read.briefing") { "Unexpected core method: $method" } val id = request["project"]?.jsonPrimitive?.content ?: "default" return if (id == blockId) { entered.countDown() withContext(NonCancellable) { reply.await() } } else briefing(id) } override suspend fun close() = Unit fun release() { reply.complete(briefing("blocked-note")) } }}private fun briefing(id: String) = buildJsonObject { put("briefing", "Synthetic $id") put("tokensEstimate", 12) put("budgetTokens", 100) put("overBudget", false) put("machineScoped", 0) put("generatedAt", JsonNull) put("briefedProjects", JsonArray(listOf(kotlinx.serialization.json.JsonPrimitive(id)))) put("projects", JsonArray(listOf(buildJsonObject { put("id", "project-$id") put("slug", id) put("name", "Synthetic $id") })))}