196 lines · 9.9 KB · KotlinRaw
package com.cottondb.messages.chatimport android.app.Applicationimport android.net.ConnectivityManagerimport com.cottondb.messages.ChatFilesimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.toListimport kotlinx.coroutines.launchimport kotlinx.coroutines.test.advanceTimeByimport kotlinx.coroutines.test.runCurrentimport kotlinx.coroutines.test.runTestimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.booleanimport kotlinx.serialization.json.jsonArrayimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.jsonPrimitiveimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.annotation.Configimport java.io.File/** * PICTURES BEFORE THEY ARE ASKED FOR, as Android tells the core when (CONTRACT.md "Pictures at once", owner 23 Nov * 2026: pictures took 1 to 2 s to appear on opening a chat and on scrolling into older ones). Invented messages; the * core is a fake that answers as `phone::chat_ahead` does. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], application = Application::class)class ChatAheadTest { private class Core(val answers: MutableMap<String, ArrayDeque<JsonObject>> = mutableMapOf()) { val asked = mutableListOf<Pair<String, JsonObject>>() fun answer(method: String, vararg o: JsonObject) { answers.getOrPut(method) { ArrayDeque() }.addAll(o) } val ask: suspend (String, JsonObject) -> JsonObject = { m, r -> asked += m to r; answers[m]?.removeFirstOrNull() ?: JsonObject(emptyMap()) } fun calls(m: String) = asked.filter { it.first == m }.map { it.second } } private fun o(vararg p: Pair<String, Any?>) = ChatData.o(*p) @Test fun the_shown_messages_go_to_the_core_as_the_scroll_settles_never_while_it_moves() = runTest { val keys = MutableStateFlow<List<Any>?>(null) val messages = setOf("m1", "m2", "m3", "m9") val told = mutableListOf<List<String>>() val job = launch { ChatAhead.settled(keys) { ChatAhead.shown(it, messages) }.collect { told += it } } // Opened: the newest messages show, a day line among them. keys.value = listOf("m1", "day-1", "m2") advanceTimeBy(ChatAhead.SETTLE_MS + 1); runCurrent() assertEquals(listOf(listOf("m1", "m2")), told) // Scrolled up: nothing while it moves, then the older messages once it rests. keys.value = null advanceTimeBy(500); runCurrent() keys.value = listOf("m3", "m9") advanceTimeBy(50); runCurrent() assertEquals(1, told.size) advanceTimeBy(ChatAhead.SETTLE_MS); runCurrent() assertEquals(listOf("m3", "m9"), told.last()) // Scrolled back down: told again, the other way. keys.value = null; runCurrent() keys.value = listOf("m1", "m2") advanceTimeBy(ChatAhead.SETTLE_MS + 1); runCurrent() assertEquals(listOf("m1", "m2"), told.last()) job.cancel() } @Test fun the_fetch_ahead_names_the_chat_and_its_shown_messages() = runTest { val core = Core() ChatAhead(core.ask).ahead("t-noor", listOf("m1", "m2")) ChatAhead(core.ask).ahead("t-noor", emptyList()) val call = core.calls("chat.ahead").single() assertEquals("t-noor", call["thread"]!!.jsonPrimitive.content) assertEquals(listOf("m1", "m2"), call["messages"]!!.jsonArray.map { it.jsonPrimitive.content }) } @Test fun the_warm_goes_on_while_it_brings_something_at_most_five_times_then_makes_missing_previews() = runTest { val core = Core() core.answer("chat.warm", o("fetched" to 200), o("fetched" to 120), o("fetched" to 0)) core.answer("chat.previews", o("items" to kotlinx.serialization.json.JsonArray(listOf(o("message" to "m-old", "index" to 0, "path" to "/invented/old.jpg"))))) core.answer("chat.preview", o("set" to 1)) val ahead = ChatAhead(core.ask, make = { "PREVIEW-${it.name}" }) assertEquals(320, ahead.warm()) assertEquals(3, core.calls("chat.warm").size) assertFalse(core.calls("chat.warm").first()["constrained"]!!.jsonPrimitive.boolean) val written = core.calls("chat.preview").single()["items"]!!.jsonArray.single().jsonObject assertEquals("m-old", written["message"]!!.jsonPrimitive.content) assertEquals("PREVIEW-old.jpg", written["preview"]!!.jsonPrimitive.content) // A warm that keeps bringing stops after five calls. repeat(9) { core.answer("chat.warm", o("fetched" to 200)) } ahead.warm() assertEquals(3 + ChatAhead.WARM_CALLS, core.calls("chat.warm").size) } @Test fun asked_while_one_runs_the_warm_runs_once_more_after_it_never_twice_at_once() = runTest { val gate = kotlinx.coroutines.CompletableDeferred<Unit>() var running = 0 var most = 0 var calls = 0 val ahead = ChatAhead({ m, _ -> if (m == "chat.warm") { calls++; running++; most = maxOf(most, running) if (calls == 1) gate.await() running-- } JsonObject(emptyMap()) }) val first = launch { ahead.warm() } runCurrent() // Something arrived while the list's warm runs: asked twice more, it runs once more, after. assertEquals(0, ahead.warm()) assertEquals(0, ahead.warm()) gate.complete(Unit) first.join() assertEquals(2, calls) assertEquals(1, most) } @Test fun with_data_saver_on_a_metered_network_the_warm_says_constrained() = runTest { val core = Core() ChatAhead(core.ask, constrained = { true }).warm() assertTrue(core.calls("chat.warm").single()["constrained"]!!.jsonPrimitive.boolean) // Data Saver limits a metered network only; mobile data alone, or the app let through, is not limited. assertTrue(ChatFiles.limited(ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED, metered = true)) assertFalse(ChatFiles.limited(ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED, metered = true)) assertFalse(ChatFiles.limited(ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED, metered = true)) assertFalse(ChatFiles.limited(ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED, metered = false)) } @Test fun an_old_picture_without_a_preview_gets_one_made_from_its_file_once() = runTest { val core = Core() core.answer("chat.preview", o("set" to 1)) val made = mutableListOf<String>() val ahead = ChatAhead(core.ask, make = { made += it.path; "PREVIEW" }) assertTrue(ahead.wanted("m-old", 1, File("/invented/kept.jpg"))) assertFalse("asked again this sitting, not made twice", ahead.wanted("m-old", 1, File("/invented/kept.jpg"))) assertEquals(listOf("/invented/kept.jpg"), made) val item = core.calls("chat.preview").single()["items"]!!.jsonArray.single().jsonObject assertEquals(1, item["index"]!!.jsonPrimitive.content.toInt()) assertEquals("PREVIEW", item["preview"]!!.jsonPrimitive.content) } @Test fun a_picture_no_preview_can_be_made_of_is_not_written_nor_asked_forever() = runTest { val core = Core() val page = o("items" to kotlinx.serialization.json.JsonArray(listOf(o("message" to "m-bad", "index" to 0, "path" to "/invented/broken.bin")))) repeat(5) { core.answer("chat.previews", page) } assertEquals(0, ChatAhead(core.ask, make = { null }).previews()) assertEquals(1, core.calls("chat.previews").size) assertTrue(core.calls("chat.preview").isEmpty()) } /** * CONTRACT "Voice player" (owner, 23 Nov 2026, item 2): a voice note from an older phone or an import has no * waveform, so its bubble drew the thin track. After the warm, the held ones are read here, each file's 64 peaks * handed to `chat.waveform`; one no waveform can be read from is not asked again this sitting. */ @Test fun after_the_warm_old_voice_notes_get_their_waveform_read_from_the_file_once() = runTest { val core = Core() val page = o("items" to kotlinx.serialization.json.JsonArray(listOf( o("message" to "m-voice", "index" to 0, "path" to "/invented/note.m4a"), o("message" to "m-broken", "index" to 0, "path" to "/invented/broken.m4a"), ))) core.answer("chat.waveforms", page, page) core.answer("chat.waveform", o("set" to 1)) val read = mutableListOf<String>() val ahead = ChatAhead(core.ask, make = { null }, wave = { read += it.name; if (it.name == "note.m4a") List(64) { i -> i / 63f } else null }) ahead.warm() val written = core.calls("chat.waveform").first()["items"]!!.jsonArray.single().jsonObject assertEquals("m-voice", written["message"]!!.jsonPrimitive.content) val peaks = written["waveform"]!!.jsonArray.map { it.jsonPrimitive.content.toFloat() } assertEquals(64, peaks.size) assertEquals(1f, peaks.last(), 0.0001f) // The next page answers the same two: neither is read again this sitting, nothing more is written. assertEquals(listOf("note.m4a", "broken.m4a"), read) assertEquals(1, core.calls("chat.waveform").size) } @Test fun a_notes_peaks_are_sixty_four_stretches_each_its_loudest() { assertEquals(null, VoiceWaveform.peaks(emptyList())) val one = VoiceWaveform.peaks(listOf(0.4f))!! assertEquals("a short note's one block fills every slice", List(64) { 0.4f }, one) val long = List(640) { if (it % 10 == 9) 0.9f else 0.1f } assertEquals("a loud block never falls between two slices", List(64) { 0.9f }, VoiceWaveform.peaks(long)) assertEquals(64, VoiceWaveform.peaks(List(100) { it / 100f })!!.size) }}