package com.cottondb.sync import android.app.Application import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.onAllNodesWithText import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo import com.cottondb.shell.LocalMaterials import com.cottondb.shell.Materials import com.cottondb.shell.SettingsSkin import com.cottondb.shell.SettingsView import com.cottondb.shell.SettingsWords import com.cottondb.shell.SyncSeen import com.cottondb.shell.SyncStuck import com.cottondb.shell.control import com.cottondb.shell.core.Lines import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.io.File /** * UNSENT HEAL ON THE SHARED SYNC PAGE (Words, Days, Story, Sites, Data and Cinemas; assets/design/shared/UNSENT-HEAL.md), * as Comms' and Secrets' pages say it: the row and the line say the stuck title once, one block says why and what to * do, Send again is the one filled button and sends the act's own request, Let go asks first (Keep them sends * nothing), and `sync.kept.seen` is called once the kept count is drawn, the count staying on the open page. The * answers are invented, shaped as `stuck_part` answers; every word is the kit's `sync.json` `unsent` line. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [35], qualifiers = "w400dp-h800dp-mdpi", application = Application::class) class SyncStuckTest { @get:Rule val compose = androidx.compose.ui.test.junit4.createComposeRule() private val repo = generateSequence(File("").absoluteFile) { it.parentFile }.first { File(it, "crates/cotton-core/kits/shell/lines").isDirectory } private val unsent = Json.parseToJsonElement(File(repo, "crates/cotton-core/kits/shell/lines/sync.json").readText()).jsonObject["unsent"]!!.jsonObject private fun w(key: String) = unsent[key]!!.jsonPrimitive.content private fun j(text: String) = Json.parseToJsonElement(text).jsonObject private fun q(text: String) = Json.encodeToString(kotlinx.serialization.json.JsonPrimitive.serializer(), kotlinx.serialization.json.JsonPrimitive(text)) /** Two changes that cannot be sent, as `stuck_part` answers them; [kept] more stay only here. */ private fun stuck(kept: Int = 0, ids: List = listOf("op-invented-a", "op-invented-b")): JsonObject { val keptLine = when (kept) { 0 -> null; 1 -> w("kept_one"); else -> w("kept_many").replace("{n}", "$kept") } val detail = listOfNotNull(w("detail_many"), keptLine).joinToString(" ") val request = """{"ids":[${ids.joinToString(",") { q(it) }}]}""" val seen = if (kept > 0) """{"method":"sync.kept.seen","request":{"count":$kept}}""" else "null" return j( """{"title":${q(w("many").replace("{n}", "2"))},"detail":${q(detail)},"things":2,"kept":$kept,"seen":$seen, "acts":[{"id":"again","label":${q(w("again"))},"method":"sync.stuck.again","request":$request}, {"id":"let_go","label":${q(w("let_go"))},"method":"sync.stuck.letGo","request":$request,"tone":"danger", "confirm":{"title":${q(w("let_go_title"))},"body":${q(w("let_go_body"))},"yes":${q(w("let_go"))},"no":${q(w("keep"))}}}]}""", ) } /** Only changes kept on this phone: the kept line is the title, no acts. */ private fun keptOnly(kept: Int) = j( """{"title":${q(if (kept == 1) w("kept_one") else w("kept_many").replace("{n}", "$kept"))},"detail":null,"things":0,"kept":$kept,"acts":[], "seen":{"method":"sync.kept.seen","request":{"count":$kept}}}""", ) private fun settings(stuck: JsonObject?) = j( """{"rows":[{"id":"sync","label":"Sync","line":"Synced at 9:53","group":"keep"}],"profile":{"signed_in":true,"name":"Invented Person"}, "sync":{"title":"Synced at 9:53","last":null,"trouble":false,"stuck":${stuck ?: "null"}}, "account":{"key":"account","actions":[{"kind":"tool","tool":"account","id":"account_back_up","label":"Sync now"}]}}""", ) /** A skin that draws plainly and notes which feet stand filled. */ private class Skin : SettingsSkin { val filled = mutableMapOf() @Composable override fun Page(title: String?, back: String, tag: String, onBack: () -> Unit, content: @Composable ColumnScope.() -> Unit) = Column(Modifier.verticalScroll(rememberScrollState()).testTag(tag)) { Text(back, Modifier.testTag("$tag-back").control(back, onTap = onBack)); title?.let { Text(it) }; content() } @Composable override fun Card(name: String, line: String?, tag: String, onTap: () -> Unit) = Text(name, Modifier.testTag(tag).control(name, onTap = onTap)) @Composable override fun Row(name: String, line: String?, tag: String, onTap: () -> Unit) = Column(Modifier.testTag(tag).control(name, onTap = onTap)) { Text(name); line?.let { Text(it) } } @Composable override fun Gap() {} @Composable override fun Heading(text: String) = Text(text) @Composable override fun Quiet(text: String, tag: String?) = Text(text, if (tag != null) Modifier.testTag(tag) else Modifier) @Composable override fun Big(text: String, tag: String) = Text(text, Modifier.testTag(tag)) @Composable override fun Fact(label: String, said: String, line: String?, tag: String) = Text("$label $said", Modifier.testTag(tag)) @Composable override fun Block(text: String, tag: String) = Text(text, Modifier.testTag(tag)) @Composable override fun Foot(label: String, tag: String, danger: Boolean, quiet: Boolean, enabled: Boolean, onTap: () -> Unit) { filled[tag] = !quiet && !danger Text(label, Modifier.testTag(tag).control(label, onTap = onTap)) } } private class Ran { val stuck = mutableListOf(); val seen = mutableListOf(); val acts = mutableListOf() } private fun draw(answer: () -> JsonObject, skin: Skin, ran: Ran, page: String? = "sync", seenLine: String? = "Synced just now") { compose.setContent { val context = LocalContext.current CompositionLocalProvider(LocalMaterials provides remember { Materials(context) }) { var at by remember { mutableStateOf(page) } SettingsView( answer(), skin, SettingsWords(Lines.of(buildJsonObject {}, "Words")), "Settings", "Back", "+1 555 0100 0000", at, { at = it }, {}, onAct = { ran.acts += it["id"]!!.jsonPrimitive.content }, seen = seenLine?.let { SyncSeen("up_to_date", it) }, onStuck = { ran.stuck += it }, onSeen = { ran.seen += it }, ) } } } @Test fun the_row_and_the_line_say_what_is_stuck_once_and_the_block_says_why() { val s = stuck() assertEquals(w("many").replace("{n}", "2"), SyncStuck.row(s, "Synced just now", "Synced at 9:53")) assertEquals("Synced just now", SyncStuck.row(null, "Synced just now", "Synced at 9:53")) assertEquals("Synced at 9:53", SyncStuck.row(null, null, "Synced at 9:53")) assertEquals(w("kept_one"), SyncStuck.row(keptOnly(1), "Synced just now", null)) assertEquals(w("many").replace("{n}", "2"), SyncStuck.line(s)) assertNull(SyncStuck.line(keptOnly(1))) assertEquals(w("detail_many"), SyncStuck.block(s)) assertEquals(w("kept_one"), SyncStuck.block(keptOnly(1))) assertFalse(SyncStuck.syncNowFilled(s)) assertTrue(SyncStuck.syncNowFilled(keptOnly(1)) && SyncStuck.syncNowFilled(null)) // The top level's Sync row says it over the live line. val ran = Ran() draw({ settings(s) }, Skin(), ran, page = null) compose.onNodeWithTag("settings-row-sync").performScrollTo() compose.onNodeWithText(w("many").replace("{n}", "2")).assertExists() assertTrue(compose.onAllNodesWithText("Synced just now").fetchSemanticsNodes().isEmpty()) } @Test fun send_again_is_the_one_filled_button_and_let_go_asks_first_with_keep_them() { val s = stuck() val skin = Skin() val ran = Ran() draw({ settings(s) }, skin, ran) // Said once: the title is the line; the block says only why and what to do; the live line steps aside. assertEquals(1, compose.onAllNodesWithText(w("many").replace("{n}", "2"), substring = true).fetchSemanticsNodes().size) compose.onNodeWithTag("settings-sync-state").assertExists() compose.onNodeWithText(w("detail_many")).assertExists() assertTrue(compose.onAllNodesWithText("Synced just now").fetchSemanticsNodes().isEmpty()) compose.runOnIdle { assertEquals(mapOf("settings-sync-stuck-again" to true, "settings-sync-stuck-let_go" to false, "settings-sync-now" to false), skin.filled) } compose.onNodeWithTag("settings-sync-stuck-again").performScrollTo().performClick() compose.runOnIdle { assertEquals(listOf("sync.stuck.again"), ran.stuck.map { it["method"]!!.jsonPrimitive.content }) assertEquals(s["acts"]!!.jsonArray[0].jsonObject["request"], ran.stuck[0]["request"]) } // Let go asks first; Keep them sends nothing. compose.onNodeWithTag("settings-sync-stuck-let_go").performScrollTo().performClick() compose.onNodeWithText(w("let_go_title")).assertIsDisplayed() compose.onNodeWithText(w("let_go_body")).assertIsDisplayed() compose.onNodeWithTag("settings-sync-stuck-confirm-keep").performClick() compose.runOnIdle { assertEquals(1, ran.stuck.size) } assertTrue(compose.onAllNodesWithText(w("let_go_title")).fetchSemanticsNodes().isEmpty()) // Its Let go sends the act's own request, exactly as the core gave it. compose.onNodeWithTag("settings-sync-stuck-let_go").performScrollTo().performClick() compose.onNodeWithTag("settings-sync-stuck-confirm-yes").performClick() compose.runOnIdle { assertEquals(listOf("sync.stuck.again", "sync.stuck.letGo"), ran.stuck.map { it["method"]!!.jsonPrimitive.content }) assertEquals(s["acts"]!!.jsonArray[1].jsonObject["request"], ran.stuck[1]["request"]) assertTrue("seen is called only for a kept count", ran.seen.isEmpty()) } // Sync now still runs, plain. compose.onNodeWithTag("settings-sync-now").performScrollTo().performClick() compose.runOnIdle { assertEquals(listOf("account_back_up"), ran.acts) } } @Test fun the_kept_count_is_seen_once_and_stays_on_the_open_page() { // Changes kept only here: the live line stays, the block says them, nothing to press but Sync now (filled). var answer by mutableStateOf(settings(keptOnly(3))) val skin = Skin() val ran = Ran() draw({ answer }, skin, ran) compose.onNodeWithText("Synced just now").assertExists() compose.onNodeWithText(w("kept_many").replace("{n}", "3")).assertExists() compose.runOnIdle { assertEquals(listOf(j("""{"method":"sync.kept.seen","request":{"count":3}}""")), ran.seen) assertEquals(mapOf("settings-sync-now" to true), skin.filled) } // The core read again after the page called it: nothing kept is said now, but the open page keeps its count, and // seen is not called again. answer = settings(null) compose.waitForIdle() compose.onNodeWithText(w("kept_many").replace("{n}", "3")).assertExists() compose.runOnIdle { assertEquals(1, ran.seen.size) } // Kept beside changes that can be acted on: the count rides in the block's words, seen once; once they are sent // the page says what now stands. val shown = stuck(2) assertSame(shown, SyncStuck.held(shown, stuck(0))) assertEquals(stuck(1, ids = listOf("op-invented-c")), SyncStuck.held(shown, stuck(1, ids = listOf("op-invented-c")))) assertEquals(stuck(0, ids = listOf("op-invented-c")), SyncStuck.held(stuck(2), stuck(0, ids = listOf("op-invented-c")))) assertNull(SyncStuck.held(stuck(2), null)) assertEquals(keptOnly(2), SyncStuck.held(keptOnly(2), null)) // A count kept after the page drew stays counted: the core answers it, and it is drawn. assertEquals(keptOnly(3), SyncStuck.held(keptOnly(2), keptOnly(3))) assertEquals(stuck(1), SyncStuck.held(null, stuck(1))) } }