Cotton code
244 lines · 7.7 KB · KotlinRaw
package com.cottondb.android.keyboardimport androidx.datastore.core.CorruptionExceptionimport androidx.test.ext.junit.runners.AndroidJUnit4import androidx.test.platform.app.InstrumentationRegistryimport java.io.Fileimport java.io.IOExceptionimport java.util.UUIDimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJobimport kotlinx.coroutines.asyncimport kotlinx.coroutines.awaitAllimport kotlinx.coroutines.cancelAndJoinimport kotlinx.coroutines.runBlockingimport kotlinx.coroutines.withContextimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonElementimport kotlinx.serialization.json.JsonObjectimport org.junit.Afterimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrueimport org.junit.Testimport org.junit.runner.RunWith@RunWith(AndroidJUnit4::class)class KeyboardChannelStoreTest {    private val root = File(        InstrumentationRegistry.getInstrumentation().targetContext.noBackupFilesDir,        "keyboard-channel-test-${UUID.randomUUID()}",    )    @After    fun cleanUp() {        root.deleteRecursively()    }    @Test    fun persistedRoundTripSurvivesAStoreRecreation() = runBlocking {        val file = channelFile("round-trip")        val expected = objectValue(            """            {              "cotton.keyboard.snapshot.v1": {                "take": "acorn-take",                "unknownFromNewerApp": [1, {"cedar": true}]              },              "cotton.keyboard.outbox.v1": [{"event": "finished"}]            }            """,        )        val firstScope = storeScope()        AndroidKeyboardChannelStore.openForTest(file, firstScope).update { expected }        close(firstScope)        val secondScope = storeScope()        try {            assertEquals(expected, AndroidKeyboardChannelStore.openForTest(file, secondScope).read())        } finally {            close(secondScope)        }    }    @Test    fun concurrentUpdatesAreSerializedAndRetainBothEdits() = runBlocking {        val scope = storeScope()        try {            val store = AndroidKeyboardChannelStore.openForTest(channelFile("serialized"), scope)            withContext(Dispatchers.Default) {                awaitAll(                    async {                        store.update { current ->                            current.with("cotton.keyboard.snapshot.v1", objectValue("""{"take":"acorn"}"""))                        }                    },                    async {                        store.update {                            it.with(                                "cotton.keyboard.outbox.v1",                                Json.parseToJsonElement("""[{"event":"cedar"}]"""),                            )                        }                    },                )            }            assertEquals(                objectValue(                    """                    {                      "cotton.keyboard.snapshot.v1": {"take":"acorn"},                      "cotton.keyboard.outbox.v1": [{"event":"cedar"}]                    }                    """,                ),                store.read(),            )        } finally {            close(scope)        }    }    @Test    fun malformedExistingFileIsRefusedWithoutReplacingIt() = runBlocking {        val file = channelFile("corrupt")        file.parentFile!!.mkdirs()        val malformed = "{not-json"        file.writeText(malformed, Charsets.UTF_8)        val scope = storeScope()        try {            val failure = try {                AndroidKeyboardChannelStore.openForTest(file, scope).read()                null            } catch (error: CorruptionException) {                error            }            assertTrue(failure != null)            assertEquals(malformed, file.readText(Charsets.UTF_8))        } finally {            close(scope)        }    }    @Test    fun ioFailureIsExposedInsteadOfReturningAnEmptyChannel() = runBlocking {        val directoryAtChannelPath = channelFile("io-failure")        assertTrue(directoryAtChannelPath.mkdirs())        val scope = storeScope()        try {            val failure = try {                AndroidKeyboardChannelStore.openForTest(directoryAtChannelPath, scope).read()                null            } catch (error: IOException) {                error            }            assertTrue(failure != null)            assertTrue(directoryAtChannelPath.isDirectory)        } finally {            close(scope)        }    }    @Test    fun canceledScopeIsRefusedBeforeCreatingAStore() = runBlocking {        val scope = storeScope()        close(scope)        val failure = try {            AndroidKeyboardChannelStore.openForTest(channelFile("canceled"), scope)            null        } catch (error: IllegalArgumentException) {            error        }        assertTrue(failure?.message?.contains("active") == true)    }    @Test    fun deviceProtectedContextIsRefusedBeforeChoosingAChannelFile() {        val credentialContext = InstrumentationRegistry.getInstrumentation().targetContext        val deviceProtectedContext = credentialContext.createDeviceProtectedStorageContext()        val scope = storeScope()        try {            val failure = try {                AndroidKeyboardChannelStore.open(deviceProtectedContext, scope)                null            } catch (error: IllegalArgumentException) {                error            }            assertTrue(failure?.message?.contains("credential-encrypted") == true)        } finally {            scope.coroutineContext[Job]!!.cancel()        }    }    @Test    fun unknownRootAndNestedValuesSurviveAnUpdate() = runBlocking {        val scope = storeScope()        try {            val store = AndroidKeyboardChannelStore.openForTest(channelFile("unknown"), scope)            store.update {                objectValue(                    """                    {                      "future.root.v9": {"array": [null, {"cedar": 4}]},                      "cotton.keyboard.snapshot.v1": {                        "known": "old",                        "futureSnapshotField": {"acorn": false}                      }                    }                    """,                )            }            val result = store.update { current ->                val snapshot = current["cotton.keyboard.snapshot.v1"] as JsonObject                current.with(                    "cotton.keyboard.snapshot.v1",                    snapshot.with("known", Json.parseToJsonElement("\"new\"")),                )            }            assertEquals(                objectValue(                    """                    {                      "future.root.v9": {"array": [null, {"cedar": 4}]},                      "cotton.keyboard.snapshot.v1": {                        "known": "new",                        "futureSnapshotField": {"acorn": false}                      }                    }                    """,                ),                result,            )        } finally {            close(scope)        }    }    private fun channelFile(name: String): File = File(root, "$name.json")    private fun storeScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)    private suspend fun close(scope: CoroutineScope) {        scope.coroutineContext[Job]!!.cancelAndJoin()    }    private fun objectValue(source: String): JsonObject =        Json.parseToJsonElement(source) as JsonObject    private fun JsonObject.with(key: String, value: JsonElement): JsonObject =        JsonObject(toMutableMap().apply { put(key, value) })}