package com.cottondb.android import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.cottondb.android.core.CottonCalling import com.cottondb.android.core.CottonEvent import com.cottondb.android.core.MalformedCoreEventException import com.cottondb.android.navigation.Route import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.SharedFlow import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonPrimitive import kotlinx.serialization.json.put import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertNotSame import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class BriefingModelsTest { private val fixtures = mutableListOf() @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 onMain(block: () -> T): T { var result: Result? = 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 = MutableSharedFlow() override val eventErrors: SharedFlow = MutableSharedFlow() val entered = CountDownLatch(1) private val reply = CompletableDeferred() 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") }))) }