package eu.friedcutlet.yokan.services.migration import eu.friedcutlet.yokan.data.DefaultYokanRepository import eu.friedcutlet.yokan.data.SettingsStore import eu.friedcutlet.yokan.data.YokanRepository import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.domain.ItemType import eu.friedcutlet.yokan.services.extensions.* import kotlinx.coroutines.* import kotlinx.coroutines.test.* import kotlin.test.* @OptIn(ExperimentalCoroutinesApi::class) class SmarterMigrationTest { private fun database(names: List = listOf("Title")): InMemoryYokanDatabase = InMemoryYokanDatabase( seedDatabaseSnapshot().copy( sources = (1L..6L).map { DbSource(id = it, name = if (it == 1L) "Old" else "Source $it", lang = "en", itemType = DbItemType.Manga, isAdded = true) }, mangas = names.mapIndexed { index, name -> DbManga(id = index + 10L, name = name, link = "/old/$index", sourceId = 1, source = "Old", lang = "en", itemType = DbItemType.Manga, favorite = true, privateNote = "Private $name") }, chapters = listOf(DbChapter(id = 101, mangaId = 10, name = "Chapter 1", url = "/old/ch1", isRead = true, isBookmarked = true)), downloads = emptyList(), ), ) private fun TestScope.service(db: InMemoryYokanDatabase, factory: MigrationTestFactory, limits: MigrationSearchLimits = MigrationSearchLimits()): MigrationService { val repository = DefaultYokanRepository(db) return MigrationService(repository, db, factory, SettingsStore(repository, backgroundScope, {}), backgroundScope, limits, StandardTestDispatcher(testScheduler)) } @Test fun matchingUsesNormalizedTitlesAliasesAndConservativeSimilarity() { val title = checkNotNull(DefaultYokanRepository(database()).manga(10)).copy(name = "A Journey into Light", alternativeTitles = listOf("光の旅", "Light Journey")) assertEquals(MigrationMatchReason.ExactTitle, migrationMatchReason(title, "A JOURNEY—INTO LIGHT!")) assertEquals(MigrationMatchReason.KnownAlias, migrationMatchReason(title, "光の旅")) assertEquals(MigrationMatchReason.SimilarTitle, migrationMatchReason(title, "A Journey into the Light")) listOf("Light", "A Journey into Light 2", "A Journey into Light Side Story", "A Journey into Light Novel", "Unrelated Light").forEach { assertNull(migrationMatchReason(title, it), it) } val source = checkNotNull(DefaultYokanRepository(database()).source(2)) assertTrue(migrationSourceCompatible(title, source)) assertFalse(migrationSourceCompatible(title, source.copy(lang = "fr"))) assertFalse(migrationSourceCompatible(title, source.copy(itemType = ItemType.Anime))) assertTrue(migrationSourceCompatible(title, source.copy(lang = "all"))) } @Test fun coverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntries() { val names = listOf("Chapter 1", "Chapter 1", "Chapter 0", "Chapter 1.5", "Volume 2 Chapter 1", "Chapter 1 Special", "Chapter 1 [fr]", "Bonus", "Bonus", "Chapter 1-2") val detail = RemoteDetail("Title", "/title", chapters = names.mapIndexed { index, name -> RemoteChapter(name, "/$index", scanlator = "$index") }) assertEquals(9, migrationChapterCoverage(detail)) assertEquals(10, detail.chapters.size) } @Test fun laterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetails() = runTest { val db = database() val factory = MigrationTestFactory(detail = { source, url -> val chapters = if (source.id == 2L) listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 1", "$url/alt")) else listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 2", "$url/ch2")) RemoteDetail("Title", url, chapters = chapters) }) val service = service(db, factory) assertTrue(service.start(1, listOf(2, 3), listOf(10, 10))) runCurrent() val run = checkNotNull(service.progress.value) assertEquals(MigrationPhase.Reviewing, run.phase) assertEquals(listOf(3L, 2L), run.items.single().candidates.map { it.source.id }) assertEquals(1, run.items.single().candidates.last().effectiveChapters) assertEquals(2, run.items.single().candidates.last().rawChapters) assertTrue(checkNotNull(db.manga(10)).favorite) assertEquals(1, db.mangas().size) assertTrue(service.start(1, listOf(2, 3), listOf(10))) assertFalse(service.start(1, listOf(4), listOf(10))) service.commitSelected() runCurrent() assertEquals(MigrationPhase.Completed, service.progress.value?.phase) assertEquals(1, service.progress.value?.migrated) assertEquals(2, factory.detailCalls.size) assertFalse(checkNotNull(db.manga(10)).favorite) val migrated = db.mangas().single { it.favorite } assertEquals(3L, migrated.sourceId) assertEquals("Private Title", migrated.privateNote) assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isRead) assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isBookmarked) } @Test fun explicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailures() = runTest { val db = database(listOf("Title", "Missing", "Broken", "Skip")) val factory = MigrationTestFactory(search = { _, query, _ -> when (query) { "Missing" -> SourceListing(listOf(RemoteManga("Unrelated", "/unrelated")), false) "Broken" -> error("Source failed") else -> SourceListing(listOf(RemoteManga(query, "/$query")), false) } }, detail = { _, url -> RemoteDetail(url.removePrefix("/"), url) }) val service = service(db, factory) service.start(1, listOf(2, 3), listOf(10, 11, 12, 13)) runCurrent() val title = checkNotNull(service.progress.value).items.first() service.select(10, title.candidates.first { it.source.id == 3L }.key) service.select(13, null) service.commitSelected() runCurrent() val run = checkNotNull(service.progress.value) assertEquals(4, run.total) assertEquals(1, run.migrated) assertEquals(1, run.unmatched) assertEquals(1, run.failed) assertEquals(1, run.skipped) assertEquals(3L, db.mangas().single { it.favorite && it.id !in 11L..13L }.sourceId) assertTrue((11L..13L).all { db.manga(it)?.favorite == true }) assertTrue(factory.detailCalls.none { it.second == "/unrelated" }) } @Test fun rankingBreaksCoverageTiesByConfidenceSourceOrderAndUrl() { val repository = DefaultYokanRepository(database()) val a = checkNotNull(repository.source(2)) val b = checkNotNull(repository.source(3)) fun candidate(source: eu.friedcutlet.yokan.domain.Source, url: String, reason: MigrationMatchReason) = MigrationCandidate(source, RemoteDetail("Title", url), 2, 10, reason) val results = listOf( MigrationSourceResult(a, listOf(candidate(a, "/weak", MigrationMatchReason.SimilarTitle), candidate(a, "/z", MigrationMatchReason.ExactTitle), candidate(a, "/a", MigrationMatchReason.ExactTitle))), MigrationSourceResult(b, listOf(candidate(b, "/b", MigrationMatchReason.ExactTitle))), ) assertEquals(listOf("/a", "/z", "/b", "/weak"), rankedMigrationCandidates(results).map { it.detail.url }) assertEquals("/b", rankedMigrationCandidates(results.reversed()).first().detail.url) } @Test fun paginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposal() = runTest { val db = database() var broken = true val factory = MigrationTestFactory(search = { _, query, page -> SourceListing(listOf(RemoteManga(query, "/$page")), true) }, detail = { _, url -> if (broken && url == "/1") error("Detail unavailable") RemoteDetail("Title", url, chapters = listOf(RemoteChapter("Chapter $url", "$url/ch"))) }) val service = service(db, factory, MigrationSearchLimits(maxPagesPerQuery = 2)) service.start(1, listOf(2), listOf(10)) runCurrent() val item = checkNotNull(service.progress.value).items.single() assertEquals(listOf(1, 2), factory.searchCalls.map { it.third }) assertEquals(setOf(MigrationSearchIssue.Truncated, MigrationSearchIssue.DetailFailed), item.sources.single().issues) assertEquals(listOf("/2"), item.candidates.map { it.detail.url }) assertTrue(db.manga(10)?.favorite == true) broken = false service.retry(10) runCurrent() val retried = checkNotNull(service.progress.value).items.single() assertEquals(2, retried.candidates.size) assertEquals(setOf(MigrationSearchIssue.Truncated), retried.sources.single().issues) assertEquals(4, factory.detailCalls.size) } @Test fun searchesEveryCompatibleSourceWithBoundedConcurrencyAndIndependentTimeouts() = runTest { val db = database() var active = 0 var peak = 0 val factory = MigrationTestFactory(search = { source, query, _ -> active++ peak = maxOf(peak, active) try { delay(if (source.id == 2L) 100 else 5) SourceListing(listOf(RemoteManga(query, "/title")), false) } finally { active-- } }) val service = service(db, factory, MigrationSearchLimits(parallelSources = 2, sourceTimeoutMillis = 20)) service.start(1, listOf(2, 3, 4, 5, 6), listOf(10)) runCurrent() advanceTimeBy(21) runCurrent() val item = checkNotNull(service.progress.value).items.single() assertEquals(2, peak) assertEquals(5, factory.searchCalls.size) assertEquals(setOf(MigrationSearchIssue.TimedOut), item.sources.first().issues) assertEquals(4, item.candidates.size) assertTrue(db.manga(10)?.favorite == true) } @Test fun cancellationStopsDiscoveryAndNeverStartsTransfer() = runTest { val db = database() val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) }) val service = service(db, factory) service.start(1, listOf(2, 3), listOf(10)) runCurrent() service.cancel() runCurrent() assertEquals(MigrationPhase.Cancelled, service.progress.value?.phase) assertTrue(db.manga(10)?.favorite == true) assertEquals("Private Title", db.manga(10)?.privateNote) assertTrue(factory.detailCalls.isEmpty()) service.commitSelected() runCurrent() assertEquals(1, db.mangas().size) } @Test fun unavailableDestinationAtCommitFailsWithoutUnfavoritingTheOriginal() = runTest { val db = database() val service = service(db, MigrationTestFactory()) service.start(1, listOf(2), listOf(10)) runCurrent() db.upsertSource(checkNotNull(db.source(2)).copy(isAdded = false)) service.commitSelected() runCurrent() assertEquals(1, service.progress.value?.failed) assertEquals(0, service.progress.value?.migrated) assertTrue(db.manga(10)?.favorite == true) assertEquals(1, db.mangas().size) service.retry(10) runCurrent() val retried = checkNotNull(service.progress.value).items.single() assertTrue(retried.candidates.isEmpty()) assertEquals(setOf(MigrationSearchIssue.Failed), retried.sources.single().issues) } @Test fun failedOrCancelledTransferLeavesTheOriginalFavoriteAndItsProgressIntact() = runTest { for (cancel in listOf(false, true)) { val db = database() val delegate = DefaultYokanRepository(db) lateinit var service: MigrationService val repository = object : YokanRepository by delegate { override fun setMangaCategories(mangaId: Long, categories: List, favorite: Boolean) { if (cancel) service.cancel() else error("Cannot transfer categories") } } service = MigrationService(repository, db, MigrationTestFactory(), SettingsStore(repository, backgroundScope, {}), backgroundScope, workDispatcher = StandardTestDispatcher(testScheduler)) service.start(1, listOf(2), listOf(10)) runCurrent() service.commitSelected() runCurrent() assertEquals(if (cancel) MigrationPhase.Cancelled else MigrationPhase.Completed, service.progress.value?.phase) assertEquals(0, service.progress.value?.migrated) assertTrue(db.manga(10)?.favorite == true) assertEquals("Private Title", db.manga(10)?.privateNote) assertTrue(db.chapters(10).single().isRead) assertTrue(db.chapters(10).single().isBookmarked) } } @Test fun parentDeadlinePropagatesInsteadOfBecomingAnOrdinarySourceTimeout() = runTest { val db = database() val repository = DefaultYokanRepository(db) val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) }) val planner = MigrationPlanner(db, factory, MigrationSearchLimits(sourceTimeoutMillis = 500)) assertFailsWith { withTimeout(5) { planner.discover(checkNotNull(repository.manga(10)), listOf(checkNotNull(repository.source(2)))) } } } @Test fun aliasesDeduplicateCandidateFetchesAndCacheDetailsForTheRun() = runTest { val db = database() val repository = DefaultYokanRepository(db) val factory = MigrationTestFactory() val planner = MigrationPlanner(db, factory, MigrationSearchLimits()) val original = checkNotNull(repository.manga(10)).copy(alternativeTitles = listOf("Alias", "TITLE")) val destinations = listOf(checkNotNull(repository.source(2))) planner.discover(original, destinations) planner.discover(original, destinations) assertEquals(4, factory.searchCalls.size) assertEquals(1, factory.detailCalls.size) } } internal class MigrationTestFactory( private val search: suspend (DbSource, String, Int) -> SourceListing = { _, query, _ -> SourceListing(listOf(RemoteManga(query, "/title")), false) }, private val detail: suspend (DbSource, String) -> RemoteDetail = { _, url -> RemoteDetail("Title", url) }, ) : ExtensionRuntimeFactory { val searchCalls = mutableListOf>() val detailCalls = mutableListOf>() override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) { override suspend fun search(query: String, page: Int, filters: List): SourceListing { searchCalls += Triple(source.id, query, page) return this@MigrationTestFactory.search(source, query, page) } override suspend fun detail(url: String): RemoteDetail { detailCalls += source.id to url return this@MigrationTestFactory.detail(source, url) } } }