Yokan / rebuild
Course 1 8624561

ProfileStorageTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/app/profiles/ProfileStorageTest.kt

test / fixture135 lines
1package eu.friedcutlet.yokan.app.profiles23import eu.friedcutlet.yokan.database.*4import eu.friedcutlet.yokan.database.room.RoomYokanDatabase5import eu.friedcutlet.yokan.database.room.createDesktopProfileRoomDatabase6import eu.friedcutlet.yokan.services.files.createDesktopProfileFileService7import java.io.File8import java.nio.file.Files9import kotlinx.coroutines.async10import kotlinx.coroutines.coroutineScope11import kotlinx.coroutines.runBlocking12import kotlin.test.Test13import kotlin.test.assertEquals14import kotlin.test.assertFalse15import kotlin.test.assertFailsWith16import kotlin.test.assertTrue17import eu.friedcutlet.yokan.domain.ProfileId18import eu.friedcutlet.yokan.domain.ProfileStorageNamespace1920class ProfileStorageTest {21    @Test fun fileRegistryCommitsAtomicallyAndIndependentInstancesDoNotLoseUpdates() = runBlocking {22        val root = Files.createTempDirectory("yokan-profile-registry").toFile()23        try {24            val file = File(root, "profiles/registry.json")25            val one = ProfileRegistry(FileProfileRegistryPersistence(file))26            val two = ProfileRegistry(FileProfileRegistryPersistence(file))27            one.refresh()28            coroutineScope { val a = async { one.beginCreate("A", A) }; val b = async { two.beginCreate("B", B) }; a.await(); b.await() }29            val registry = ProfileRegistry(FileProfileRegistryPersistence(file))30            assertEquals(setOf(ProfileId.Default, A, B), registry.refresh().profiles.map { it.id }.toSet())31            assertFalse(file.parentFile.listFiles().orEmpty().any { it.extension == "tmp" })32            registry.markReady(A); registry.recordActive(A)33            assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)34            // An abandoned staging file never replaces a committed registry on restart.35            File(file.parentFile, "registry-abandoned.tmp").writeText("{")36            assertEquals(A, ProfileRegistry(FileProfileRegistryPersistence(file)).refresh().lastActive)37        } finally { root.deleteRecursively() }38    }3940    @Test fun corruptAndOversizedFileRegistryPreserveBytesAndDefaultData() = runBlocking {41        val root = Files.createTempDirectory("yokan-profile-corrupt").toFile()42        try {43            val original = File(root, "yokan-room.db").apply { writeText("existing default sentinel") }44            val file = File(root, "profiles/registry.json").apply { parentFile.mkdirs() }45            for (bytes in listOf("{".encodeToByteArray(), byteArrayOf(0xFF.toByte()), ByteArray(MaxProfileRegistryBytes + 1))) {46                file.writeBytes(bytes)47                assertFailsWith<Exception> { ProfileRegistry(FileProfileRegistryPersistence(file)).refresh() }48                assertTrue(file.readBytes().contentEquals(bytes))49                assertEquals("existing default sentinel", original.readText())50            }51        } finally { root.deleteRecursively() }52    }5354    @Test fun twoNativeDatabasesWithIdenticalIdsRemainIndependentAcrossReopenAndDefaultAdoption() = runBlocking {55        val root = Files.createTempDirectory("yokan-profile-room").toFile()56        try {57            val legacy = seedDatabaseSnapshot().copy(mangas = listOf(DbManga(id = 42, name = "Default", favorite = true, privateNote = "Legacy note")))58            val defaultRoom = createDesktopProfileRoomDatabase(root, ProfileId.Default)59            try {60                val default = RoomYokanDatabase(defaultRoom, legacySnapshotProvider = { legacy })61                default.awaitPersistence()62                assertEquals("Legacy note", default.manga(42)?.privateNote)63            } finally { defaultRoom.close() }64            assertTrue(File(root, "yokan-room.db").isFile)65            val rooms = listOf(A, B).map { createDesktopProfileRoomDatabase(root, it) }66            try {67                val databases = rooms.map { RoomYokanDatabase(it) }68                assertTrue(databases.all { it.mangas().isEmpty() && it.syncPreferences().isEmpty() && it.trackPreferences().isEmpty() })69                databases[0].upsertManga(DbManga(id = 42, name = "A", favorite = true, privateNote = "A note"))70                databases[1].upsertManga(DbManga(id = 42, name = "B", favorite = true, privateNote = "B note"))71                databases[0].updateSettings(databases[0].settings().copy(readerHoldToScroll = true, automaticReaderLayout = true))72                databases[1].updateSettings(databases[1].settings().copy(readerHoldToScroll = false, automaticReaderLayout = false))73                databases.forEach { it.awaitPersistence() }74            } finally { rooms.forEach { it.close() } }75            for ((id, name, note) in listOf(Triple(ProfileId.Default, "Default", "Legacy note"), Triple(A, "A", "A note"), Triple(B, "B", "B note"))) {76                val room = createDesktopProfileRoomDatabase(root, id)77                try {78                    val db = RoomYokanDatabase(room, legacySnapshotProvider = { error("Existing profile must not load legacy data") })79                    assertEquals(name, db.manga(42)?.name); assertEquals(note, db.manga(42)?.privateNote)80                    assertEquals(id == A, db.settings().readerHoldToScroll)81                    db.awaitPersistence()82                } finally { room.close() }83            }84        } finally { root.deleteRecursively() }85    }8687    @Test fun profileOwnedDownloadBackupAndCacheRootsDoNotTouchDefaultOrExports() {88        val root = Files.createTempDirectory("yokan-profile-files").toFile()89        try {90            val default = createDesktopProfileFileService(root, ProfileId.Default)91            val a = createDesktopProfileFileService(root, A)92            val b = createDesktopProfileFileService(root, B)93            assertEquals(File(root, "Yokan/downloads").path, default.downloadRoot)94            assertEquals(File(root, "Yokan/backups").path, default.backupRoot)95            assertEquals(File(root, "cache").path, default.cacheRoot)96            for ((index, files) in listOf(default, a, b).withIndex()) for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {97                files.writeBytes("$path/same-name.txt", "owner $index".encodeToByteArray())98            }99            val exported = File(root, "exported-backup.zip").apply { writeText("user export") }100            assertTrue(File(ProfileStorageNamespace(A).ownedRoot(root.path)).deleteRecursively())101            for ((files, index) in listOf(default to 0, b to 2)) {102                for (path in listOf(files.downloadRoot, files.backupRoot, files.cacheRoot)) {103                    assertEquals("owner $index", files.readBytes("$path/same-name.txt").decodeToString())104                }105            }106            assertEquals("user export", exported.readText())107        } finally { root.deleteRecursively() }108    }109110    @Test fun explicitSnapshotFlushPersistsOnlyItsOwningStoreAndFailureCanBeRetried() = runBlocking {111        val raw = mutableMapOf<String, String>(); var rejected: String? = null112        fun open(id: ProfileId): YokanDatabase {113            val key = ProfileStorageNamespace(id).browserSnapshotKey114            return SnapshotYokanDatabase(object : DatabaseSnapshotStore {115                override fun load() = raw[key]?.let(::decodeDatabaseSnapshot)116                override fun save(snapshot: YokanDatabaseSnapshot) {117                    if (key == rejected) error("Quota exceeded")118                    raw[key] = encodeDatabaseSnapshot(snapshot)119                }120            })121        }122        val default = open(ProfileId.Default); default.upsertManga(DbManga(id = 42, privateNote = "Default")); default.awaitPersistence()123        val defaultRaw = raw.getValue("yokan-database-v1")124        val a = open(A); val b = open(B)125        assertTrue(a.mangas().isEmpty()); assertTrue(b.mangas().isEmpty())126        a.upsertManga(DbManga(id = 42, privateNote = "A")); b.upsertManga(DbManga(id = 42, privateNote = "B"))127        rejected = ProfileStorageNamespace(B).browserSnapshotKey128        a.awaitPersistence(); assertFailsWith<IllegalStateException> { b.awaitPersistence() }129        assertEquals(defaultRaw, raw.getValue("yokan-database-v1"))130        assertEquals("A", open(A).manga(42)?.privateNote)131        rejected = null; b.awaitPersistence(); assertEquals("B", open(B).manga(42)?.privateNote)132        assertEquals("Default", open(ProfileId.Default).manga(42)?.privateNote)133    }134    companion object { val A = ProfileId("p_${"a".repeat(32)}"); val B = ProfileId("p_${"b".repeat(32)}") }135}136

Search chapters, reference and source filenames.