BackupSelectiveRestoreTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/backup/BackupSelectiveRestoreTest.kt
1package eu.friedcutlet.yokan.services.backup23import eu.friedcutlet.yokan.database.DbActionType4import eu.friedcutlet.yokan.services.notifications.NoNotifications5import eu.friedcutlet.yokan.database.DbCategory6import eu.friedcutlet.yokan.database.DbChangedPart7import eu.friedcutlet.yokan.database.DbChapter8import eu.friedcutlet.yokan.database.DbHistory9import eu.friedcutlet.yokan.database.DbItemType10import eu.friedcutlet.yokan.database.DbManga11import eu.friedcutlet.yokan.database.DbSource12import eu.friedcutlet.yokan.database.DbSyncPreference13import eu.friedcutlet.yokan.database.DbTrack14import eu.friedcutlet.yokan.database.DbTrackStatus15import eu.friedcutlet.yokan.database.DbUpdate16import eu.friedcutlet.yokan.database.InMemoryYokanDatabase17import eu.friedcutlet.yokan.database.seedDatabaseSnapshot18import eu.friedcutlet.yokan.domain.Manga19import eu.friedcutlet.yokan.database.sync.SyncPaths20import kotlin.test.Test21import kotlin.test.assertEquals22import kotlin.test.assertFailsWith23import kotlin.test.assertFalse24import kotlin.test.assertTrue25import kotlinx.coroutines.test.runTest26import kotlinx.serialization.json.Json2728private val LenientBackupJson = Json { ignoreUnknownKeys = true }2930class BackupSelectiveRestoreTest {31 @Test32 fun restoreReplacesInsteadOfMerging() = runTest {33 val database = InMemoryYokanDatabase(34 seedDatabaseSnapshot().copy(35 mangas = listOf(36 DbManga(id = 1, name = "Stale title"),37 DbManga(id = 2, name = "Another stale"),38 ),39 chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Stale ch", url = "u")),40 ),41 )42 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)43 val backup = BackupSnapshot(44 createdAtMillis = 1,45 mangas = listOf(DbManga(id = 7, name = "Restored title")),46 chapters = listOf(DbChapter(id = 70, mangaId = 7, name = "Restored ch", url = "u7")),47 )48 val bytes = native(backup)4950 service.restore(bytes)5152 assertEquals(listOf("Restored title"), database.mangas().map { it.name })53 assertEquals(listOf("Restored ch"), database.chapters().map { it.name })54 }5556 @Test57 fun restoredDifferencesAreQueuedForTheHub() = runTest {58 val database = InMemoryYokanDatabase(59 seedDatabaseSnapshot().copy(60 mangas = listOf(DbManga(id = 1, name = "Hub name"), DbManga(id = 2, name = "Gone"), DbManga(id = 3, name = "Same")),61 syncPreferences = listOf(DbSyncPreference(syncId = 1, server = "https://hub.test", authToken = "tok", syncOn = true, hubEpoch = 4, hubHead = 50)),62 ),63 )64 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)6566 service.restore(native(BackupSnapshot(createdAtMillis = 1, mangas = listOf(DbManga(id = 1, name = "Backup name"), DbManga(id = 3, name = "Same")))))6768 val ops = database.outbox().filter { it.kind == SyncPaths.KIND_MANGA }69 assertEquals("\"Backup name\"", ops.single { it.id == 1L && it.path == "name" }.value)70 assertEquals(SyncPaths.DELETED, ops.single { it.id == 2L }.path)71 assertTrue(ops.none { it.id == 3L }, "unchanged titles are not re-sent")72 assertTrue(ops.all { it.epoch == 4 }, "ops belong to the logged-in hub generation")73 assertEquals(0L, database.syncPreferences().single().hubHead)74 }7576 @Test77 fun restoreKeepsOnlyDownloadMarksWhoseFilesExistOnThisDevice() = runTest {78 val database = InMemoryYokanDatabase(seedDatabaseSnapshot())79 val files = MemoryFileService().apply { files["/here/ch1.cbz"] = byteArrayOf(1) }80 val service = DefaultBackupService(database, files, PassthroughCompression(), NoNotifications)8182 service.restore(native(BackupSnapshot(83 createdAtMillis = 1,84 mangas = listOf(DbManga(id = 1, name = "Source title"), DbManga(id = 2, name = "Local title", isLocalArchive = true)),85 chapters = listOf(86 DbChapter(id = 10, mangaId = 1, name = "Here", url = "/c/1", archivePath = "/here/ch1.cbz", downloadSize = "1.0 MB"),87 DbChapter(id = 11, mangaId = 1, name = "Other device", url = "/c/2", archivePath = "/other/ch2", downloadSize = "2.0 MB"),88 DbChapter(id = 20, mangaId = 2, name = "Local", url = "local/Title/ch.cbz", archivePath = "local/Title/ch.cbz"),89 ),90 )))9192 val chapters = database.chapters().associateBy { it.id }93 assertEquals("/here/ch1.cbz" to "1.0 MB", chapters.getValue(10).let { it.archivePath to it.downloadSize })94 assertEquals("" to null, chapters.getValue(11).let { it.archivePath to it.downloadSize }, "another device's download is not restored")95 assertEquals("local/Title/ch.cbz", chapters.getValue(20).archivePath, "local-library paths are not download marks")96 }9798 @Test99 fun openAndPreviewDoNotMutateDatabase() = runTest {100 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(101 mangas = listOf(DbManga(id = 1, name = "Local")),102 chapters = listOf(DbChapter(id = 2, mangaId = 1, name = "Local ch", url = "local")),103 ))104 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)105 val before = database.snapshot()106 val bytes = native(BackupSnapshot(107 createdAtMillis = 1,108 includedSections = listOf("manga", "chapters"),109 mangas = listOf(DbManga(id = 7, name = "Incoming")),110 chapters = listOf(DbChapter(id = 8, mangaId = 7, name = "Incoming ch", url = "incoming")),111 ))112113 val opened = service.openBackup(bytes)114 assertTrue(opened is BackupOpenResult.Ready)115 service.previewBackup(opened.plan)116117 assertEquals(before, database.snapshot())118 }119120 @Test121 fun applyReplacesOnlySelectedCollectionsAndEmptySelectedClears() = runTest {122 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(123 mangas = listOf(124 DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),125 DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),126 ),127 chapters = listOf(128 DbChapter(id = 3, mangaId = 1, name = "Clear", url = "clear"),129 DbChapter(id = 5, mangaId = 2, name = "Keep excluded", url = "keep-excluded"),130 ),131 categories = listOf(DbCategory(id = 4, name = "Keep category", forItemType = DbItemType.Manga)),132 ))133 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)134 val bytes = native(BackupSnapshot(135 createdAtMillis = 1,136 includedSections = listOf("manga", "categories"),137 mangas = emptyList(),138 categories = emptyList(),139 chapters = listOf(DbChapter(id = 99, mangaId = 99, name = "Ignored", url = "ignored")),140 ))141142 val opened = service.openBackup(bytes) as BackupOpenResult.Ready143 service.applyBackup(opened.plan)144145 assertEquals(listOf("Anime local"), database.mangas().map { it.name })146 assertTrue(database.categories().isEmpty(), "present-empty selected collection was not cleared")147 assertEquals(listOf("Keep excluded"), database.chapters().map { it.name })148 }149150 @Test151 fun selectingOneTitleTypePreservesTheOtherTypes() = runTest {152 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(153 mangas = listOf(154 DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),155 DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),156 DbManga(id = 3, name = "Novel local", itemType = DbItemType.Novel),157 ),158 ))159 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)160 val bytes = native(BackupSnapshot(161 createdAtMillis = 1,162 includedSections = listOf("anime"),163 mangas = listOf(164 DbManga(id = 20, name = "Anime incoming", itemType = DbItemType.Anime),165 DbManga(id = 21, name = "Should stay excluded", itemType = DbItemType.Manga),166 ),167 ))168169 val opened = service.openBackup(bytes) as BackupOpenResult.Ready170 service.applyBackup(opened.plan)171172 assertEquals(setOf("Manga local", "Anime incoming", "Novel local"), database.mangas().map { it.name }.toSet())173 }174175 @Test176 fun incomingDependentRowsCannotCrossManifestTitleBoundary() = runTest {177 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(178 mangas = listOf(179 DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),180 DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),181 ),182 chapters = listOf(DbChapter(id = 20, mangaId = 2, name = "Anime episode")),183 histories = listOf(DbHistory(id = 21, mangaId = 2, chapterId = 20, itemType = DbItemType.Anime)),184 updates = listOf(DbUpdate(id = 22, mangaId = 2, chapterId = 20)),185 tracks = listOf(DbTrack(id = 23, mangaId = 2, status = DbTrackStatus.Watching)),186 ))187 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)188 val bytes = native(BackupSnapshot(189 createdAtMillis = 1,190 includedSections = listOf("manga", "chapters", "history", "updates", "tracks"),191 mangas = listOf(DbManga(id = 10, name = "Imported manga", itemType = DbItemType.Manga)),192 chapters = listOf(193 DbChapter(id = 30, mangaId = 10, name = "Imported chapter"),194 DbChapter(id = 31, mangaId = 2, name = "Excluded incoming episode"),195 ),196 histories = listOf(197 DbHistory(id = 40, mangaId = 10, chapterId = 30, itemType = DbItemType.Manga),198 DbHistory(id = 41, mangaId = 2, chapterId = 20, itemType = DbItemType.Anime),199 ),200 updates = listOf(201 DbUpdate(id = 50, mangaId = 10, chapterId = 30),202 DbUpdate(id = 51, mangaId = 2, chapterId = 20),203 ),204 tracks = listOf(205 DbTrack(id = 60, mangaId = 10, status = DbTrackStatus.Reading),206 DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),207 ),208 ))209210 val opened = service.openBackup(bytes) as BackupOpenResult.Ready211 service.applyBackup(opened.plan)212213 assertEquals(setOf(10L, 2L), database.mangas().map { it.id }.toSet())214 assertEquals(setOf(30L, 20L), database.chapters().map { it.id }.toSet())215 assertEquals(setOf(40L, 21L), database.histories().map { it.id }.toSet())216 assertEquals(setOf(50L, 22L), database.updates().map { it.id }.toSet())217 assertEquals(setOf(60L, 23L), database.tracks().map { it.id }.toSet())218 }219220 @Test221 fun identityCollisionRejectsBeforeMutation() = runTest {222 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(223 mangas = listOf(224 DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),225 DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),226 ),227 ))228 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)229 val before = database.snapshot()230 val bytes = native(BackupSnapshot(231 createdAtMillis = 1,232 includedSections = listOf("manga"),233 mangas = listOf(DbManga(id = 2, name = "Colliding manga", itemType = DbItemType.Manga)),234 ))235236 assertFailsWith<IllegalStateException> {237 val opened = service.openBackup(bytes) as BackupOpenResult.Ready238 service.applyBackup(opened.plan)239 }240 assertEquals(before, database.snapshot())241 }242243 @Test244 fun dependentIdentityCollisionRejectsBeforeMutation() = runTest {245 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(246 mangas = listOf(247 DbManga(id = 1, name = "Manga local", itemType = DbItemType.Manga),248 DbManga(id = 2, name = "Anime local", itemType = DbItemType.Anime),249 ),250 chapters = listOf(DbChapter(id = 7, mangaId = 2, name = "Anime episode")),251 ))252 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)253 val before = database.snapshot()254 val bytes = native(BackupSnapshot(255 createdAtMillis = 1,256 includedSections = listOf("manga", "chapters"),257 mangas = listOf(DbManga(id = 3, name = "Incoming manga", itemType = DbItemType.Manga)),258 chapters = listOf(DbChapter(id = 7, mangaId = 3, name = "Colliding chapter")),259 ))260261 assertFailsWith<IllegalStateException> {262 val opened = service.openBackup(bytes) as BackupOpenResult.Ready263 service.applyBackup(opened.plan)264 }265 assertEquals(before, database.snapshot())266 }267268 @Test269 fun changedPartsAreMergedOnlyWhenSelected() = runTest {270 val localChange = DbChangedPart(271 id = 1,272 actionType = DbActionType.RemoveItem,273 isarId = 10,274 data = "local",275 clientDate = 1,276 )277 val incomingChange = localChange.copy(id = 99, data = "incoming")278 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(changedParts = listOf(localChange)))279 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)280281 val selected = native(BackupSnapshot(282 createdAtMillis = 1,283 includedSections = listOf("changedParts"),284 changedParts = listOf(incomingChange),285 ))286 val selectedPlan = service.openBackup(selected) as BackupOpenResult.Ready287 service.applyBackup(selectedPlan.plan)288 assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })289 assertEquals(listOf(1L, 99L), database.changedParts().map { it.id })290291 val absent = native(BackupSnapshot(createdAtMillis = 1, includedSections = emptyList(), changedParts = emptyList()))292 val absentPlan = service.openBackup(absent) as BackupOpenResult.Ready293 service.applyBackup(absentPlan.plan)294 assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })295296 val selectedEmpty = native(BackupSnapshot(createdAtMillis = 1, includedSections = listOf("changedParts")))297 val selectedEmptyPlan = service.openBackup(selectedEmpty) as BackupOpenResult.Ready298 service.applyBackup(selectedEmptyPlan.plan)299 assertEquals(listOf("local", "incoming"), database.changedParts().map { it.data })300 }301302 @Test303 fun applyFiltersInvalidDependentRecordsAgainstTheFinalGraph() = runTest {304 val database = InMemoryYokanDatabase(seedDatabaseSnapshot())305 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)306 val bytes = native(BackupSnapshot(307 createdAtMillis = 1,308 includedSections = listOf("manga", "categories", "chapters", "history", "updates", "tracks"),309 mangas = listOf(DbManga(id = 7, name = "Incoming", categories = listOf(1, 999))),310 categories = listOf(DbCategory(id = 1, name = "Valid", forItemType = DbItemType.Manga)),311 chapters = listOf(312 DbChapter(id = 70, mangaId = 7, name = "Valid chapter"),313 DbChapter(id = 71, mangaId = 999, name = "Orphan chapter"),314 ),315 histories = listOf(316 DbHistory(id = 80, mangaId = 7, chapterId = 70, itemType = DbItemType.Manga),317 DbHistory(id = 81, mangaId = 999, chapterId = 70, itemType = DbItemType.Manga),318 ),319 updates = listOf(320 DbUpdate(id = 90, mangaId = 7, chapterId = 70),321 DbUpdate(id = 91, mangaId = 7, chapterId = 999),322 ),323 tracks = listOf(324 DbTrack(id = 100, mangaId = 7, status = DbTrackStatus.Reading),325 DbTrack(id = 101, mangaId = 999, status = DbTrackStatus.Reading),326 ),327 ))328329 val opened = service.openBackup(bytes) as BackupOpenResult.Ready330 service.applyBackup(opened.plan)331332 assertEquals(listOf(7L), database.mangas().map { it.id })333 assertEquals(listOf(1L), database.mangas().single().categories)334 assertEquals(listOf(70L), database.chapters().map { it.id })335 assertEquals(listOf(80L), database.histories().map { it.id })336 assertEquals(listOf(90L), database.updates().map { it.id })337 assertEquals(listOf(100L), database.tracks().map { it.id })338 }339340 @Test341 fun selectedDependentSectionWithoutTitleTypesReplacesWholeSection() = runTest {342 val database = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(343 mangas = listOf(DbManga(id = 1, name = "Existing")),344 chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Old chapter")),345 ))346 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)347348 val replacement = native(BackupSnapshot(349 createdAtMillis = 1,350 includedSections = listOf("chapters"),351 chapters = listOf(352 DbChapter(id = 20, mangaId = 1, name = "Valid replacement"),353 DbChapter(id = 21, mangaId = 999, name = "Orphan replacement"),354 ),355 ))356 val replacementPlan = service.openBackup(replacement) as BackupOpenResult.Ready357 service.applyBackup(replacementPlan.plan)358 assertEquals(listOf("Valid replacement"), database.chapters().map { it.name })359360 val selectedEmpty = native(BackupSnapshot(361 createdAtMillis = 1,362 includedSections = listOf("chapters"),363 chapters = emptyList(),364 ))365 val selectedEmptyPlan = service.openBackup(selectedEmpty) as BackupOpenResult.Ready366 service.applyBackup(selectedEmptyPlan.plan)367 assertTrue(database.chapters().isEmpty(), "selected-empty dependent section did not clear")368 }369370 @Test371 fun selectiveExportOpenApplyKeepsExcludedTypesAndTheirDependencies() = runTest {372 val manga = DbManga(id = 1, name = "Manga", itemType = DbItemType.Manga, categories = listOf(10), sourceId = 20)373 val anime = DbManga(id = 2, name = "Anime", itemType = DbItemType.Anime, categories = listOf(11), sourceId = 21)374 val sourceManga = DbSource(id = 20, name = "Manga source", itemType = DbItemType.Manga)375 val sourceAnime = DbSource(id = 21, name = "Anime source", itemType = DbItemType.Anime)376 val mangaChapter = DbChapter(id = 30, mangaId = 1, name = "Manga chapter")377 val animeChapter = DbChapter(id = 31, mangaId = 2, name = "Anime episode")378 val sourceDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(379 mangas = listOf(manga, anime),380 categories = listOf(381 DbCategory(id = 10, name = "Manga category", forItemType = DbItemType.Manga),382 DbCategory(id = 11, name = "Anime category", forItemType = DbItemType.Anime),383 ),384 sources = listOf(sourceManga, sourceAnime),385 chapters = listOf(mangaChapter, animeChapter),386 histories = listOf(387 DbHistory(id = 40, mangaId = 1, chapterId = 30, itemType = DbItemType.Manga),388 DbHistory(id = 41, mangaId = 2, chapterId = 31, itemType = DbItemType.Anime),389 ),390 updates = listOf(391 DbUpdate(id = 50, mangaId = 1, chapterId = 30),392 DbUpdate(id = 51, mangaId = 2, chapterId = 31),393 ),394 tracks = listOf(395 DbTrack(id = 60, mangaId = 1, status = DbTrackStatus.Reading),396 DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),397 ),398 ))399 val exporter = DefaultBackupService(sourceDatabase, MemoryFileService(), PassthroughCompression(), NoNotifications)400 val export = exporter.exportBackup(BackupOptions(401 includeAnime = false,402 includeNovel = false,403 includeSettings = false,404 compressionLevel = 0,405 ))406 val exported = LenientBackupJson407 .decodeFromString(BackupSnapshot.serializer(), export.bytes.decodeToString())408 assertEquals(listOf(1L), exported.mangas.map { it.id })409 assertEquals(listOf(30L), exported.chapters.map { it.id })410 assertEquals(listOf(40L), exported.histories.map { it.id })411 assertEquals(listOf(50L), exported.updates.map { it.id })412 assertEquals(listOf(60L), exported.tracks.map { it.id })413 assertEquals(listOf(10L), exported.categories.map { it.id })414 assertEquals(listOf(20L), exported.sources.map { it.id })415416 val targetDatabase = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(417 mangas = listOf(manga.copy(name = "Old manga"), anime),418 categories = listOf(419 DbCategory(id = 10, name = "Old manga category", forItemType = DbItemType.Manga),420 DbCategory(id = 11, name = "Anime category", forItemType = DbItemType.Anime),421 ),422 sources = listOf(sourceManga, sourceAnime),423 chapters = listOf(mangaChapter.copy(name = "Old chapter"), animeChapter),424 histories = listOf(425 DbHistory(id = 40, mangaId = 1, chapterId = 30, itemType = DbItemType.Manga),426 DbHistory(id = 41, mangaId = 2, chapterId = 31, itemType = DbItemType.Anime),427 ),428 updates = listOf(429 DbUpdate(id = 50, mangaId = 1, chapterId = 30),430 DbUpdate(id = 51, mangaId = 2, chapterId = 31),431 ),432 tracks = listOf(433 DbTrack(id = 60, mangaId = 1, status = DbTrackStatus.Reading),434 DbTrack(id = 61, mangaId = 2, status = DbTrackStatus.Watching),435 ),436 ))437 val applier = DefaultBackupService(targetDatabase, MemoryFileService(), PassthroughCompression(), NoNotifications)438 val opened = applier.openBackup(export.bytes) as BackupOpenResult.Ready439 applier.applyBackup(opened.plan)440441 assertEquals(setOf("Manga", "Anime"), targetDatabase.mangas().map { it.name }.toSet())442 assertEquals(setOf(30L, 31L), targetDatabase.chapters().map { it.id }.toSet())443 assertEquals(setOf(40L, 41L), targetDatabase.histories().map { it.id }.toSet())444 assertEquals(setOf(50L, 51L), targetDatabase.updates().map { it.id }.toSet())445 assertEquals(setOf(60L, 61L), targetDatabase.tracks().map { it.id }.toSet())446 assertEquals(setOf(10L, 11L), targetDatabase.categories().map { it.id }.toSet())447 assertEquals(setOf(20L, 21L), targetDatabase.sources().map { it.id }.toSet())448 }449450 @Test451 fun restoreWithMergeModePreservesExistingTitlesAndMergesChaptersAndCategories() = runTest {452 val database = InMemoryYokanDatabase(453 seedDatabaseSnapshot().copy(454 categories = listOf(455 DbCategory(id = 1, name = "Action", forItemType = DbItemType.Manga),456 ),457 mangas = listOf(458 DbManga(id = 10, name = "One Piece", link = "https://example.com/op", favorite = true, categories = listOf(1L)),459 DbManga(id = 20, name = "Naruto", link = "https://example.com/naruto", favorite = true),460 ),461 chapters = listOf(462 DbChapter(id = 100, mangaId = 10, name = "Ch 1", url = "op/1", isRead = false, lastPageRead = "5"),463 ),464 ),465 )466 val fileService = MemoryFileService()467 val service = DefaultBackupService(database, fileService, PassthroughCompression(), NoNotifications)468469 val incomingBackup = BackupSnapshot(470 createdAtMillis = 100,471 categories = listOf(472 DbCategory(id = 99, name = "Action", forItemType = DbItemType.Manga),473 DbCategory(id = 98, name = "Adventure", forItemType = DbItemType.Manga),474 ),475 mangas = listOf(476 DbManga(id = 50, name = "One Piece", link = "https://example.com/op", categories = listOf(99L, 98L)),477 DbManga(id = 60, name = "Bleach", link = "https://example.com/bleach", categories = listOf(98L)),478 ),479 chapters = listOf(480 DbChapter(id = 501, mangaId = 50, name = "Ch 1", url = "op/1", isRead = true, lastPageRead = "15"),481 DbChapter(id = 502, mangaId = 50, name = "Ch 2", url = "op/2", isRead = false, lastPageRead = "1"),482 DbChapter(id = 601, mangaId = 60, name = "Ch 1", url = "bleach/1", isRead = true),483 ),484 )485 val bytes = native(incomingBackup)486 val opened = service.openBackup(bytes) as BackupOpenResult.Ready487488 // Verify preview stats489 assertEquals(1, opened.plan.preview.newSeriesCount) // Bleach490 assertEquals(1, opened.plan.preview.updatedSeriesCount) // One Piece491 assertEquals(2, opened.plan.preview.newChapterCount) // One Piece Ch 2 + Bleach Ch 1492 assertEquals(listOf("Action"), opened.plan.preview.conflictingCategories)493494 // Apply in Merge mode495 service.applyBackup(opened.plan, RestoreMode.Merge)496497 val finalMangas = database.mangas().associateBy { it.name }498 assertTrue("One Piece" in finalMangas)499 assertTrue("Naruto" in finalMangas, "Existing title not in backup must be preserved in merge mode")500 assertTrue("Bleach" in finalMangas, "New title from backup must be added in merge mode")501502 val op = finalMangas.getValue("One Piece")503 assertTrue(op.favorite)504 val opCategoryNames = database.categories().filter { it.id in op.categories.orEmpty() }.map { it.name }.toSet()505 assertEquals(setOf("Action", "Adventure"), opCategoryNames)506507 val opChapters = database.chapters(op.id).associateBy { it.url }508 val ch1 = opChapters.getValue("op/1")509 assertTrue(ch1.isRead, "Chapter progress should be merged (isRead = true)")510 assertEquals("15", ch1.lastPageRead, "Chapter lastPageRead should be maxOf(5, 15)")511512 val ch2 = opChapters.getValue("op/2")513 assertFalse(ch2.isRead)514515 val bleach = finalMangas.getValue("Bleach")516 val bleachChapters = database.chapters(bleach.id)517 assertEquals(1, bleachChapters.size)518 assertEquals("bleach/1", bleachChapters.first().url)519 }520521 @Test522 fun restoreWithReplaceModeWipesNonBackupTitles() = runTest {523 val database = InMemoryYokanDatabase(524 seedDatabaseSnapshot().copy(525 mangas = listOf(526 DbManga(id = 10, name = "One Piece", link = "https://example.com/op", favorite = true),527 DbManga(id = 20, name = "Naruto", link = "https://example.com/naruto", favorite = true),528 ),529 ),530 )531 val service = DefaultBackupService(database, MemoryFileService(), PassthroughCompression(), NoNotifications)532533 val incomingBackup = BackupSnapshot(534 createdAtMillis = 100,535 mangas = listOf(536 DbManga(id = 60, name = "Bleach", link = "https://example.com/bleach"),537 ),538 )539 val bytes = native(incomingBackup)540 val opened = service.openBackup(bytes) as BackupOpenResult.Ready541542 // Apply in Replace mode543 service.applyBackup(opened.plan, RestoreMode.Replace)544545 val mangaNames = database.mangas().map { it.name }546 assertEquals(listOf("Bleach"), mangaNames, "Replace mode must replace titles of included sections")547 }548}549