Cotton code
226 lines · 10.5 KB · KotlinRaw
package com.cottondb.android.ui.day.peopleimport androidx.compose.ui.test.assertIsEnabledimport androidx.compose.ui.test.assertIsNotEnabledimport androidx.compose.material3.Textimport androidx.compose.ui.test.hasContentDescriptionimport androidx.compose.ui.test.hasTextimport androidx.compose.ui.test.performScrollToNodeimport androidx.compose.ui.test.performTextReplacementimport androidx.compose.ui.test.captureToImageimport androidx.compose.ui.test.onRootimport androidx.compose.ui.graphics.asAndroidBitmapimport com.cottondb.android.ScreenEvidenceimport com.cottondb.android.design.CottonThemeimport com.cottondb.android.ui.media.CottonAvatarimport com.cottondb.android.media.*import androidx.compose.ui.test.junit4.createComposeRuleimport androidx.compose.ui.test.onNodeWithContentDescriptionimport androidx.compose.ui.test.onNodeWithTagimport androidx.compose.ui.test.onNodeWithTextimport androidx.compose.ui.test.performClickimport androidx.compose.ui.test.performTextClearanceimport androidx.compose.ui.test.performTextInputimport com.cottondb.android.core.CottonCallingimport com.cottondb.android.core.CottonEventimport com.cottondb.android.core.MalformedCoreEventExceptionimport com.cottondb.android.day.people.PeopleReadimport com.cottondb.android.day.people.PeopleRepositoryimport com.cottondb.android.day.people.PeopleStateimport com.cottondb.android.day.people.PersonDetailModelimport com.cottondb.android.day.people.PersonListingimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.flow.MutableSharedFlowimport kotlinx.coroutines.flow.SharedFlowimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.JsonPrimitiveimport kotlinx.serialization.json.buildJsonArrayimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.putimport org.junit.Assert.assertEqualsimport org.junit.Afterimport kotlinx.coroutines.cancelimport org.junit.Ruleimport org.junit.runner.RunWithimport androidx.test.ext.junit.runners.AndroidJUnit4import org.junit.Test@RunWith(AndroidJUnit4::class)class PeopleScreensTest {    @get:Rule val compose = createComposeRule()    private val fixtures = mutableListOf<DetailFixture>()    @After fun closeScopes() { fixtures.forEach { it.writerScope.cancel() } }    @Test    fun directorySearchesTheCompleteReadAndNavigatesToTheSelectedPerson() {        var route: String? = null        compose.setContent {            PeopleDirectoryScreen(                state = PeopleState.Data(PeopleRead(2, 0, false, listOf(person("a", "Asha", "Studio"), person("b", "Bela", "Elsewhere")))),                query = "studio",                layout = PeopleLayout.List,                onQueryChange = {},                onLayoutChange = {},                onRefresh = {},                onOpenPerson = { route = "/people/person/$it" },            )        }        ScreenEvidence.capture("people-directory") { compose.onRoot().captureToImage().asAndroidBitmap() }        compose.onNodeWithText("Bela").assertDoesNotExist()        compose.onNodeWithText("Asha").performClick()        assertEquals("/people/person/a", route)    }    @Test    fun emptyDirectoryOffersTheContactImportFlow() {        var imports = 0        compose.setContent {            PeopleDirectoryScreen(                state = PeopleState.Data(PeopleRead(0, 0, false, emptyList())),                query = "",                layout = PeopleLayout.Grid,                onQueryChange = {},                onLayoutChange = {},                onRefresh = {},                onOpenPerson = {},                onImport = { imports += 1 },            )        }        compose.onNodeWithText("Import contacts").assertExists().performClick()        assertEquals(1, imports)    }    @Test    fun invalidBirthdayPreventsSaveAndAChosenTimezoneEnablesIt() {        val fixture = DetailFixture().also(fixtures::add)        compose.setContent { fixture.screen() }        compose.waitUntil(5_000) { fixture.model.editor.value != null }        ScreenEvidence.capture("person-detail") { compose.onRoot().captureToImage().asAndroidBitmap() }        compose.onNodeWithContentDescription("Edit person").performClick()        input("Month", "2")        input("Day", "30")        compose.onNodeWithText("That day is not in this birthday month.").assertExists()        compose.onNodeWithText("Save").assertIsNotEnabled()        input("Day", "29")        input("Timezone", "Berlin")        compose.onNodeWithText("Europe/Berlin").performClick()        compose.onNodeWithText("Save").assertIsEnabled()    }    @Test    fun partialSaveFailureStaysInTheEditorAndArchiveNeedsConfirmation() {        val fixture = DetailFixture(summaryFails = true).also(fixtures::add)        compose.setContent { fixture.screen() }        compose.waitUntil(5_000) { fixture.model.editor.value != null }        ScreenEvidence.capture("person-detail") { compose.onRoot().captureToImage().asAndroidBitmap() }        compose.onNodeWithContentDescription("Edit person").performClick()        input("City", "Berlin")        input("Summary", "A new summary")        compose.onNodeWithText("Save").performClick()        compose.waitUntil(5_000) { fixture.core.summaryWrites == 1 }        compose.onNodeWithTag("person-edit-fields").performScrollToNode(hasText("Summary could not be saved"))        compose.onNodeWithText("Summary could not be saved").assertExists()        compose.onNodeWithText("Edit person").assertExists()        compose.onNodeWithText("Cancel").performClick()        compose.onNodeWithContentDescription("Archive person").performClick()        compose.onNodeWithText("Archive Asha?").assertExists()        assertEquals(0, fixture.core.archives)        compose.onNodeWithTag("person-archive-confirm").performClick()        compose.waitUntil(5_000) { fixture.core.archives == 1 }    }    private fun input(label: String, value: String) {        compose.onNodeWithTag("person-edit-fields").performScrollToNode(hasContentDescription(label))        compose.onNodeWithContentDescription(label).performTextReplacement(value)    }    private fun person(id: String, name: String, org: String) = PersonListing(        id = id, name = name, phones = emptyList(), emails = emptyList(), org = org,        roleTitle = null, city = null, timezone = null, avatarKey = null, avatarUrl = null,    )    private class DetailFixture(summaryFails: Boolean = false) {        val core = PersonCore(summaryFails)        val model = PersonDetailModel(PeopleRepository(core), "person-a")        val writerScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)        @androidx.compose.runtime.Composable        fun screen() = CottonTheme { PersonDetailScreen(            model = model,            writerScope = writerScope,            dataRevision = 0,            avatar = { id, name, key, size -> CottonAvatar(id, name, key, media, 0, size) },            onBack = {},            onNavigate = {},            onOpenUri = {},            clock = java.time.Clock.fixed(java.time.Instant.parse("2026-01-01T12:00:00Z"), java.time.ZoneOffset.UTC),            zoneId = java.time.ZoneOffset.UTC,        ) }        private val media = object : LocalMediaSource {            override suspend fun local(key: String, tier: MediaPathTier) = LocalMedia.Absent        }    }    private class PersonCore(private val summaryFails: Boolean) : CottonCalling {        override val events: SharedFlow<CottonEvent> = MutableSharedFlow()        override val eventErrors: SharedFlow<MalformedCoreEventException> = MutableSharedFlow()        var summaryWrites = 0        var archives = 0        override suspend fun call(method: String, request: JsonObject): JsonElement = when (method) {            "read.person" -> detailJson()            "write" -> when ((request["tool"] as JsonPrimitive).content) {                "update_person" -> buildJsonObject { }                "update_summary" -> {                    summaryWrites += 1                    if (summaryFails) error("Summary could not be saved") else buildJsonObject { }                }                "archive_person" -> {                    archives += 1                    buildJsonObject { }                }                else -> error("unexpected person write")            }            else -> error("unexpected method $method")        }        override suspend fun close() = Unit    }    private companion object {        fun detailJson() = buildJsonObject {            put("person", buildJsonObject {                put("id", "person-a"); put("workspaceId", "workspace"); put("fullName", "Asha")                put("phones", buildJsonArray { add(JsonPrimitive("+49 123 4567890")) })                put("emails", buildJsonArray { add(JsonPrimitive("asha@example.test")) })                put("org", "Studio"); put("roleTitle", "Designer"); put("city", "Hamburg")                put("summary", kotlinx.serialization.json.JsonNull); put("summaryBy", kotlinx.serialization.json.JsonNull); put("summaryUpdatedAt", kotlinx.serialization.json.JsonNull)                put("contactSource", kotlinx.serialization.json.JsonNull); put("deviceContactId", kotlinx.serialization.json.JsonNull); put("birthday", kotlinx.serialization.json.JsonNull)                put("timezone", "Europe/Berlin"); put("avatarKey", kotlinx.serialization.json.JsonNull); put("avatarUrl", kotlinx.serialization.json.JsonNull)                put("archivedAt", kotlinx.serialization.json.JsonNull); put("createdAt", kotlinx.serialization.json.JsonNull); put("updatedAt", kotlinx.serialization.json.JsonNull)            })            put("thread", kotlinx.serialization.json.JsonNull)            put("projects", buildJsonArray { })            put("projectLinks", buildJsonArray { })            // Strict `parsePersonSections` consumes these families from the same read.            put("personNotes", buildJsonArray { })            put("links", buildJsonArray { })            put("linkedRecordFacts", buildJsonObject { })            put("todos", buildJsonArray { })            put("calls", buildJsonArray { })            put("faceSuggestions", buildJsonArray { })            put("faceSuggestionPhotos", buildJsonArray { })            put("money", buildJsonArray { })            put("summary", buildJsonObject { put("summary", buildJsonObject {                put("text", kotlinx.serialization.json.JsonNull); put("by", kotlinx.serialization.json.JsonNull); put("updatedAt", kotlinx.serialization.json.JsonNull)            }) })        }    }}