package com.cottondb.android.keyboard import androidx.datastore.core.CorruptionException import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import java.io.File import java.io.IOException import java.util.UUID import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import 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) }) }