Cotton code
299 lines · 14.5 KB · KotlinRaw
package com.cottondb.messages.warmimport android.app.Applicationimport android.view.Viewimport android.view.ViewGroupimport android.view.accessibility.AccessibilityNodeInfoimport androidx.activity.ComponentActivityimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.foundation.text.BasicTextimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.setValueimport androidx.compose.ui.Modifierimport androidx.compose.foundation.layout.paddingimport androidx.compose.ui.platform.testTagimport androidx.compose.ui.unit.spimport androidx.compose.ui.unit.dpimport androidx.compose.foundation.layout.sizeimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.ViewRootForTestimport androidx.compose.ui.test.assertimport androidx.compose.ui.test.assertCountEqualsimport androidx.compose.ui.test.assertIsDisplayedimport androidx.compose.ui.test.assertIsEnabledimport androidx.compose.ui.test.junit4.createAndroidComposeRuleimport androidx.compose.ui.test.onNodeWithTagimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.performClickimport androidx.compose.ui.test.performScrollToimport androidx.core.view.ViewCompatimport com.cottondb.shell.controlimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Ruleimport org.junit.Testimport org.junit.runner.RunWithimport org.robolectric.RobolectricTestRunnerimport org.robolectric.annotation.Config/** * COMMS' STORE PASS (26 Nov 2026), on invented words: * - A confirmation's Not now (the microphone's reason and refusal, and every other two-way card) can be pressed: it *   stood disabled, faint and said "disabled" by TalkBack, so the card was left only by a tap outside or Back. * - What stands over the page at the root (a viewer, a recording, Sites, the call) leaves the page silent to TalkBack; *   a sheet's veil already does, since it is a control covering the screen. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], qualifiers = "w400dp-h860dp-xhdpi", application = Application::class)class CommsStoreReadyTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    @Test    fun a_confirmations_not_now_can_be_pressed() {        var yes = 0        var no = 0        compose.setContent {            WarmTheme(night = false) {                val look = WarmCardLook(WarmColours.light, WarmType.of(LocalContext.current))                look.ConfirmCard("Comms uses the microphone only while you record.", "Go on", "voice-mic-go-on", { yes++ }, { no++ }, "Not now")            }        }        compose.onNodeWithText("Not now").assertIsDisplayed().assertIsEnabled().performClick()        compose.onNodeWithText("Go on").assertIsEnabled().performClick()        compose.runOnIdle { assertEquals(1, no); assertEquals(1, yes) }    }    @Test    @Config(qualifiers = "w320dp-h570dp-xhdpi", fontScale = 2.0f)    fun at_the_largest_text_on_a_small_phone_both_ways_out_stand_whole() {        compose.setContent {            WarmTheme(night = false) {                val look = WarmCardLook(WarmColours.light, WarmType.of(LocalContext.current))                look.ConfirmCard("Comms needs the microphone to record. Allow it in Settings.", "Open Settings", "voice-mic-settings", {}, {}, "Not now")            }        }        compose.onNodeWithText("Not now").assertIsDisplayed()        compose.onNodeWithText("Open Settings").assertIsDisplayed()        // Neither way out is squeezed into breaking its words: each keeps one line.        listOf("Not now", "Open Settings").forEach { label ->            val layout = mutableListOf<androidx.compose.ui.text.TextLayoutResult>()            compose.onNodeWithText(label).fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsActions.GetTextLayoutResult].action?.invoke(layout)            assertEquals("$label keeps one line", 1, layout.single().lineCount)        }    }    @Test    fun the_page_under_a_full_screen_viewer_is_silent_to_talkback() {        var over by mutableStateOf(false)        compose.setContent {            WarmTheme(night = false) {                Box(Modifier.fillMaxSize()) {                    Box(Modifier.fillMaxSize().hiddenUnder(over)) {                        Column { BasicText("Chats"); Box(Modifier.control("Meena Invented") {}) { BasicText("Meena Invented") } }                    }                    // A full-screen ground with words only at its top, as the file viewer and a recording stand.                    if (over) Column(Modifier.fillMaxSize()) { Box(Modifier.control("Close") {}) { BasicText("Close") } }                }            }        }        compose.onNodeWithText("Chats").assertExists()        assertTrue("Meena Invented" in spoken())        compose.runOnIdle { over = true }        compose.waitForIdle()        compose.onNodeWithText("Chats").assertDoesNotExist()        compose.onNodeWithText("Close").assertExists()        val said = spoken()        assertFalse("the page under the viewer was read: $said", "Meena Invented" in said || "Chats" in said)        assertTrue(said.toString(), "Close" in said)    }    @Test    fun a_sheets_veil_keeps_talkback_off_the_page_under_it() {        var open by mutableStateOf(false)        compose.setContent {            WarmTheme(night = false) {                Box(Modifier.fillMaxSize()) {                    Column { BasicText("Chats"); Box(Modifier.control("Ravi Invented") {}) { BasicText("Ravi Invented") } }                    if (open) Sheet("Close", "test-sheet", { open = false }, title = "Ravi Invented's chat") { SheetRow("Pin", "row-pin") {} }                }            }        }        assertTrue("Ravi Invented" in spoken())        compose.runOnIdle { open = true }        compose.waitForIdle()        val said = spoken()        assertTrue(said.toString(), "Pin" in said)        assertFalse("the page under the sheet was read: $said", "Ravi Invented" in said || "Chats" in said)    }    /** A field is named once, by its hint: the hint drawn in it was read too ("Search, Search, edit box"). */    @Test    fun a_field_says_its_name_once() {        compose.setContent {            WarmTheme(night = false) {                Column {                    SearchPill("", "Search", {})                    val look = WarmCardLook(WarmColours.light, WarmType.of(LocalContext.current))                    look.CodeAskCard(com.cottondb.shell.CodeAskWords("Enter your recovery code", "XXXX-XXXX", "Open", "Not now"), "", {}, null, false, {}, {}, {})                }            }        }        compose.onAllNodes(androidx.compose.ui.test.hasText("Search")).assertCountEquals(0)        compose.onAllNodes(androidx.compose.ui.test.hasContentDescription("Search")).assertCountEquals(1)        // The recovery code's field had no name at all; its pattern is not read as words.        compose.onNodeWithTag("recovery-code-field").assert(androidx.compose.ui.test.hasContentDescription("Enter your recovery code"))        compose.onAllNodes(androidx.compose.ui.test.hasText("XXXX-XXXX")).assertCountEquals(0)    }    @Test    fun the_root_counts_each_full_screen_cover() {        assertFalse(PageCover.over(viewer = false, document = false, recordingPage = false, recordingLive = false, call = false))        listOf(0, 1, 2, 3, 4).forEach { i ->            val on = BooleanArray(5) { it == i }            assertTrue(PageCover.over(on[0], on[1], on[2], on[3], on[4]))        }    }    /**     * What TalkBack is handed: the words of every node in the window's accessibility tree, as the platform builds it     * from Compose (where a node wholly covered by a control drawn over it is left out), not Compose's own tree.     */    private fun spoken(): Set<String> {        compose.waitForIdle()        val root = compose.activity.findViewById<ViewGroup>(android.R.id.content)        val view = generateSequence(listOf<View>(root)) { level -> level.flatMap { v -> (v as? ViewGroup)?.let { g -> (0 until g.childCount).map(g::getChildAt) }.orEmpty() }.takeIf { it.isNotEmpty() } }            .flatten().first { it is ViewRootForTest }        val provider = ViewCompat.getAccessibilityDelegate(view)!!.getAccessibilityNodeProvider(view)!!        val childId = AccessibilityNodeInfo::class.java.getDeclaredMethod("getChildId", Int::class.javaPrimitiveType).apply { isAccessible = true }        val words = mutableSetOf<String>()        val queue = ArrayDeque(listOf(View.NO_ID))        val seen = mutableSetOf<Int>()        while (queue.isNotEmpty()) {            val id = queue.removeFirst()            if (!seen.add(id)) continue            val info = provider.createAccessibilityNodeInfo(id)?.unwrap() ?: continue            info.text?.toString()?.let(words::add)            info.contentDescription?.toString()?.let(words::add)            for (i in 0 until info.childCount) queue.add(((childId.invoke(info, i) as Long) ushr 32).toInt())        }        return words    }}/** Signed out, the one way in stands within reach on a small phone on its side at the largest text. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], qualifiers = "w640dp-h320dp-xhdpi", fontScale = 2.0f, application = Application::class)class CommsWelcomeReachTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    @Test    fun sign_in_can_be_reached() {        compose.setContent {            WarmTheme(night = false) {                Welcome("Comms", "Messages and calls with the people you know. Only you and they can read them.", "Sign in with your number") {}            }        }        compose.onNodeWithTag("chat-sign-in").performScrollTo().assertIsDisplayed()    }}/** At the largest text on a phone: the places keep their whole words, Calls keeps its title, a row keeps its message. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], qualifiers = "w392dp-h850dp-xhdpi", fontScale = 2.0f, application = Application::class)class CommsLargestTextTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    private fun ellipsized(label: String): Boolean {        val layout = mutableListOf<androidx.compose.ui.text.TextLayoutResult>()        compose.onNodeWithText(label, useUnmergedTree = true).fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsActions.GetTextLayoutResult].action?.invoke(layout)        return layout.single().let { it.lineCount > 1 || it.isLineEllipsized(0) }    }    @Test    fun every_place_keeps_its_whole_word() {        compose.setContent { WarmTheme(night = false) { Places(listOf("Chats", "Calls", "You"), 2, Modifier) {} } }        listOf("Chats", "Calls", "You").forEach { assertFalse("$it was cut", ellipsized(it)) }    }    @Test    fun calls_keeps_its_title_and_its_acts_stand_under_it() {        compose.setContent {            WarmTheme(night = false) {                TitleWithActs(                    title = { Title("Calls") },                    acts = { PillButton("Bring in a recording", "calls-import") {}; PillButton("Record", "calls-record", on = true) {} },                    modifier = Modifier.fillMaxSize(),                )            }        }        assertFalse(ellipsized("Calls"))        val title = compose.onNodeWithText("Calls", useUnmergedTree = true).fetchSemanticsNode().boundsInRoot        val record = compose.onNodeWithTag("calls-record").fetchSemanticsNode().boundsInRoot        assertTrue("the acts stand under the title", record.top >= title.bottom)        assertFalse(ellipsized("Bring in a recording"))        assertFalse(ellipsized("Record"))    }    @Test    fun a_rows_message_is_not_squeezed_out_by_its_state() {        compose.setContent {            WarmTheme(night = false) {                Box(Modifier.size(260.dp, 200.dp)) {                    LineAndState(line = { W("You: Video", size = 15.sp, lines = 1) }, beside = " · Waiting to send") { inline ->                        W(if (inline) " · Waiting to send" else "Waiting to send", Modifier.testTag("state"), size = 15.sp, lines = 1)                    }                }            }        }        assertFalse(ellipsized("You: Video"))        assertFalse(ellipsized("Waiting to send"))    }}/** A small phone (360 x 640 dp) at the largest text: a page's name and its value keep whole words. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], qualifiers = "w360dp-h640dp-xhdpi", fontScale = 2.0f, application = Application::class)class CommsSmallPhoneTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    private fun layoutOf(label: String): androidx.compose.ui.text.TextLayoutResult {        val layout = mutableListOf<androidx.compose.ui.text.TextLayoutResult>()        compose.onNodeWithText(label, useUnmergedTree = true).fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsActions.GetTextLayoutResult].action?.invoke(layout)        return layout.single()    }    @Test    fun off_stands_whole_beside_or_under_disappearing_messages() {        compose.setContent { WarmTheme(night = false) { Column(Modifier.padding(horizontal = 18.dp)) { Line("Disappearing messages", "Off", tag = "chat-timer") {} } } }        assertEquals("Off is one line, never O / ff", 1, layoutOf("Off").lineCount)    }}/** On a tablet (800 x 1280 dp) the page stands in a centred 640 dp column; on a phone it keeps the whole width. */@RunWith(RobolectricTestRunner::class)@Config(sdk = [35], qualifiers = "w800dp-h1280dp-xhdpi", application = Application::class)class CommsTabletTest {    @get:Rule val compose = createAndroidComposeRule<ComponentActivity>()    @Test    fun the_page_stands_in_a_centred_column() {        compose.setContent { WarmTheme(night = false) { PageColumn(over = false) { Box(Modifier.fillMaxSize()) } } }        val column = compose.onNodeWithTag("page-column").fetchSemanticsNode().boundsInRoot        val density = compose.activity.resources.displayMetrics.density        assertEquals(640f, column.width / density, 1f)        assertEquals(80f, column.left / density, 1f)    }    @Test    @Config(qualifiers = "w400dp-h860dp-xhdpi")    fun a_phone_keeps_the_whole_width() {        compose.setContent { WarmTheme(night = false) { PageColumn(over = false) { Box(Modifier.fillMaxSize()) } } }        val column = compose.onNodeWithTag("page-column").fetchSemanticsNode().boundsInRoot        assertEquals(400f, column.width / compose.activity.resources.displayMetrics.density, 1f)    }}