SmarterMigrationTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/migration/SmarterMigrationTest.kt
1package eu.friedcutlet.yokan.services.migration23import eu.friedcutlet.yokan.data.DefaultYokanRepository4import eu.friedcutlet.yokan.data.SettingsStore5import eu.friedcutlet.yokan.data.YokanRepository6import eu.friedcutlet.yokan.database.*7import eu.friedcutlet.yokan.domain.ItemType8import eu.friedcutlet.yokan.services.extensions.*9import kotlinx.coroutines.*10import kotlinx.coroutines.test.*11import kotlin.test.*1213@OptIn(ExperimentalCoroutinesApi::class)14class SmarterMigrationTest {15 private fun database(names: List<String> = listOf("Title")): InMemoryYokanDatabase = InMemoryYokanDatabase(16 seedDatabaseSnapshot().copy(17 sources = (1L..6L).map { DbSource(id = it, name = if (it == 1L) "Old" else "Source $it", lang = "en", itemType = DbItemType.Manga, isAdded = true) },18 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") },19 chapters = listOf(DbChapter(id = 101, mangaId = 10, name = "Chapter 1", url = "/old/ch1", isRead = true, isBookmarked = true)),20 downloads = emptyList(),21 ),22 )2324 private fun TestScope.service(db: InMemoryYokanDatabase, factory: MigrationTestFactory, limits: MigrationSearchLimits = MigrationSearchLimits()): MigrationService {25 val repository = DefaultYokanRepository(db)26 return MigrationService(repository, db, factory, SettingsStore(repository, backgroundScope, {}), backgroundScope,27 limits, StandardTestDispatcher(testScheduler))28 }2930 @Test31 fun matchingUsesNormalizedTitlesAliasesAndConservativeSimilarity() {32 val title = checkNotNull(DefaultYokanRepository(database()).manga(10)).copy(name = "A Journey into Light", alternativeTitles = listOf("光の旅", "Light Journey"))33 assertEquals(MigrationMatchReason.ExactTitle, migrationMatchReason(title, "A JOURNEY—INTO LIGHT!"))34 assertEquals(MigrationMatchReason.KnownAlias, migrationMatchReason(title, "光の旅"))35 assertEquals(MigrationMatchReason.SimilarTitle, migrationMatchReason(title, "A Journey into the Light"))36 listOf("Light", "A Journey into Light 2", "A Journey into Light Side Story", "A Journey into Light Novel", "Unrelated Light").forEach {37 assertNull(migrationMatchReason(title, it), it)38 }39 val source = checkNotNull(DefaultYokanRepository(database()).source(2))40 assertTrue(migrationSourceCompatible(title, source))41 assertFalse(migrationSourceCompatible(title, source.copy(lang = "fr")))42 assertFalse(migrationSourceCompatible(title, source.copy(itemType = ItemType.Anime)))43 assertTrue(migrationSourceCompatible(title, source.copy(lang = "all")))44 }4546 @Test47 fun coverageKeepsVolumesFractionsLanguagesSpecialsAndUncertainEntries() {48 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")49 val detail = RemoteDetail("Title", "/title", chapters = names.mapIndexed { index, name -> RemoteChapter(name, "/$index", scanlator = "$index") })50 assertEquals(9, migrationChapterCoverage(detail))51 assertEquals(10, detail.chapters.size)52 }5354 @Test55 fun laterSourceWithMoreDistinctChaptersWinsAndCommitReusesReviewedDetails() = runTest {56 val db = database()57 val factory = MigrationTestFactory(detail = { source, url ->58 val chapters = if (source.id == 2L) listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 1", "$url/alt"))59 else listOf(RemoteChapter("Chapter 1", "$url/ch1"), RemoteChapter("Chapter 2", "$url/ch2"))60 RemoteDetail("Title", url, chapters = chapters)61 })62 val service = service(db, factory)63 assertTrue(service.start(1, listOf(2, 3), listOf(10, 10)))64 runCurrent()65 val run = checkNotNull(service.progress.value)66 assertEquals(MigrationPhase.Reviewing, run.phase)67 assertEquals(listOf(3L, 2L), run.items.single().candidates.map { it.source.id })68 assertEquals(1, run.items.single().candidates.last().effectiveChapters)69 assertEquals(2, run.items.single().candidates.last().rawChapters)70 assertTrue(checkNotNull(db.manga(10)).favorite)71 assertEquals(1, db.mangas().size)72 assertTrue(service.start(1, listOf(2, 3), listOf(10)))73 assertFalse(service.start(1, listOf(4), listOf(10)))74 service.commitSelected()75 runCurrent()76 assertEquals(MigrationPhase.Completed, service.progress.value?.phase)77 assertEquals(1, service.progress.value?.migrated)78 assertEquals(2, factory.detailCalls.size)79 assertFalse(checkNotNull(db.manga(10)).favorite)80 val migrated = db.mangas().single { it.favorite }81 assertEquals(3L, migrated.sourceId)82 assertEquals("Private Title", migrated.privateNote)83 assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isRead)84 assertTrue(db.chapters(migrated.id).first { it.name == "Chapter 1" }.isBookmarked)85 }8687 @Test88 fun explicitOverrideAndSkipPreserveAccurateTotalsIncludingUnmatchedAndFailures() = runTest {89 val db = database(listOf("Title", "Missing", "Broken", "Skip"))90 val factory = MigrationTestFactory(search = { _, query, _ -> when (query) {91 "Missing" -> SourceListing(listOf(RemoteManga("Unrelated", "/unrelated")), false)92 "Broken" -> error("Source failed")93 else -> SourceListing(listOf(RemoteManga(query, "/$query")), false)94 } }, detail = { _, url -> RemoteDetail(url.removePrefix("/"), url) })95 val service = service(db, factory)96 service.start(1, listOf(2, 3), listOf(10, 11, 12, 13))97 runCurrent()98 val title = checkNotNull(service.progress.value).items.first()99 service.select(10, title.candidates.first { it.source.id == 3L }.key)100 service.select(13, null)101 service.commitSelected()102 runCurrent()103 val run = checkNotNull(service.progress.value)104 assertEquals(4, run.total)105 assertEquals(1, run.migrated)106 assertEquals(1, run.unmatched)107 assertEquals(1, run.failed)108 assertEquals(1, run.skipped)109 assertEquals(3L, db.mangas().single { it.favorite && it.id !in 11L..13L }.sourceId)110 assertTrue((11L..13L).all { db.manga(it)?.favorite == true })111 assertTrue(factory.detailCalls.none { it.second == "/unrelated" })112 }113114 @Test115 fun rankingBreaksCoverageTiesByConfidenceSourceOrderAndUrl() {116 val repository = DefaultYokanRepository(database())117 val a = checkNotNull(repository.source(2))118 val b = checkNotNull(repository.source(3))119 fun candidate(source: eu.friedcutlet.yokan.domain.Source, url: String, reason: MigrationMatchReason) =120 MigrationCandidate(source, RemoteDetail("Title", url), 2, 10, reason)121 val results = listOf(122 MigrationSourceResult(a, listOf(candidate(a, "/weak", MigrationMatchReason.SimilarTitle), candidate(a, "/z", MigrationMatchReason.ExactTitle), candidate(a, "/a", MigrationMatchReason.ExactTitle))),123 MigrationSourceResult(b, listOf(candidate(b, "/b", MigrationMatchReason.ExactTitle))),124 )125 assertEquals(listOf("/a", "/z", "/b", "/weak"), rankedMigrationCandidates(results).map { it.detail.url })126 assertEquals("/b", rankedMigrationCandidates(results.reversed()).first().detail.url)127 }128129 @Test130 fun paginationLimitsAndDetailErrorsAreVisibleAndRetryRefreshesTheProposal() = runTest {131 val db = database()132 var broken = true133 val factory = MigrationTestFactory(search = { _, query, page ->134 SourceListing(listOf(RemoteManga(query, "/$page")), true)135 }, detail = { _, url ->136 if (broken && url == "/1") error("Detail unavailable")137 RemoteDetail("Title", url, chapters = listOf(RemoteChapter("Chapter $url", "$url/ch")))138 })139 val service = service(db, factory, MigrationSearchLimits(maxPagesPerQuery = 2))140 service.start(1, listOf(2), listOf(10))141 runCurrent()142 val item = checkNotNull(service.progress.value).items.single()143 assertEquals(listOf(1, 2), factory.searchCalls.map { it.third })144 assertEquals(setOf(MigrationSearchIssue.Truncated, MigrationSearchIssue.DetailFailed), item.sources.single().issues)145 assertEquals(listOf("/2"), item.candidates.map { it.detail.url })146 assertTrue(db.manga(10)?.favorite == true)147 broken = false148 service.retry(10)149 runCurrent()150 val retried = checkNotNull(service.progress.value).items.single()151 assertEquals(2, retried.candidates.size)152 assertEquals(setOf(MigrationSearchIssue.Truncated), retried.sources.single().issues)153 assertEquals(4, factory.detailCalls.size)154 }155156 @Test157 fun searchesEveryCompatibleSourceWithBoundedConcurrencyAndIndependentTimeouts() = runTest {158 val db = database()159 var active = 0160 var peak = 0161 val factory = MigrationTestFactory(search = { source, query, _ ->162 active++163 peak = maxOf(peak, active)164 try {165 delay(if (source.id == 2L) 100 else 5)166 SourceListing(listOf(RemoteManga(query, "/title")), false)167 } finally { active-- }168 })169 val service = service(db, factory, MigrationSearchLimits(parallelSources = 2, sourceTimeoutMillis = 20))170 service.start(1, listOf(2, 3, 4, 5, 6), listOf(10))171 runCurrent()172 advanceTimeBy(21)173 runCurrent()174 val item = checkNotNull(service.progress.value).items.single()175 assertEquals(2, peak)176 assertEquals(5, factory.searchCalls.size)177 assertEquals(setOf(MigrationSearchIssue.TimedOut), item.sources.first().issues)178 assertEquals(4, item.candidates.size)179 assertTrue(db.manga(10)?.favorite == true)180 }181182 @Test183 fun cancellationStopsDiscoveryAndNeverStartsTransfer() = runTest {184 val db = database()185 val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) })186 val service = service(db, factory)187 service.start(1, listOf(2, 3), listOf(10))188 runCurrent()189 service.cancel()190 runCurrent()191 assertEquals(MigrationPhase.Cancelled, service.progress.value?.phase)192 assertTrue(db.manga(10)?.favorite == true)193 assertEquals("Private Title", db.manga(10)?.privateNote)194 assertTrue(factory.detailCalls.isEmpty())195 service.commitSelected()196 runCurrent()197 assertEquals(1, db.mangas().size)198 }199200 @Test201 fun unavailableDestinationAtCommitFailsWithoutUnfavoritingTheOriginal() = runTest {202 val db = database()203 val service = service(db, MigrationTestFactory())204 service.start(1, listOf(2), listOf(10))205 runCurrent()206 db.upsertSource(checkNotNull(db.source(2)).copy(isAdded = false))207 service.commitSelected()208 runCurrent()209 assertEquals(1, service.progress.value?.failed)210 assertEquals(0, service.progress.value?.migrated)211 assertTrue(db.manga(10)?.favorite == true)212 assertEquals(1, db.mangas().size)213 service.retry(10)214 runCurrent()215 val retried = checkNotNull(service.progress.value).items.single()216 assertTrue(retried.candidates.isEmpty())217 assertEquals(setOf(MigrationSearchIssue.Failed), retried.sources.single().issues)218 }219220 @Test221 fun failedOrCancelledTransferLeavesTheOriginalFavoriteAndItsProgressIntact() = runTest {222 for (cancel in listOf(false, true)) {223 val db = database()224 val delegate = DefaultYokanRepository(db)225 lateinit var service: MigrationService226 val repository = object : YokanRepository by delegate {227 override fun setMangaCategories(mangaId: Long, categories: List<Long>, favorite: Boolean) {228 if (cancel) service.cancel() else error("Cannot transfer categories")229 }230 }231 service = MigrationService(repository, db, MigrationTestFactory(), SettingsStore(repository, backgroundScope, {}), backgroundScope,232 workDispatcher = StandardTestDispatcher(testScheduler))233 service.start(1, listOf(2), listOf(10))234 runCurrent()235 service.commitSelected()236 runCurrent()237 assertEquals(if (cancel) MigrationPhase.Cancelled else MigrationPhase.Completed, service.progress.value?.phase)238 assertEquals(0, service.progress.value?.migrated)239 assertTrue(db.manga(10)?.favorite == true)240 assertEquals("Private Title", db.manga(10)?.privateNote)241 assertTrue(db.chapters(10).single().isRead)242 assertTrue(db.chapters(10).single().isBookmarked)243 }244 }245246 @Test247 fun parentDeadlinePropagatesInsteadOfBecomingAnOrdinarySourceTimeout() = runTest {248 val db = database()249 val repository = DefaultYokanRepository(db)250 val factory = MigrationTestFactory(search = { _, _, _ -> delay(1000); SourceListing(emptyList(), false) })251 val planner = MigrationPlanner(db, factory, MigrationSearchLimits(sourceTimeoutMillis = 500))252 assertFailsWith<TimeoutCancellationException> {253 withTimeout(5) { planner.discover(checkNotNull(repository.manga(10)), listOf(checkNotNull(repository.source(2)))) }254 }255 }256257 @Test258 fun aliasesDeduplicateCandidateFetchesAndCacheDetailsForTheRun() = runTest {259 val db = database()260 val repository = DefaultYokanRepository(db)261 val factory = MigrationTestFactory()262 val planner = MigrationPlanner(db, factory, MigrationSearchLimits())263 val original = checkNotNull(repository.manga(10)).copy(alternativeTitles = listOf("Alias", "TITLE"))264 val destinations = listOf(checkNotNull(repository.source(2)))265 planner.discover(original, destinations)266 planner.discover(original, destinations)267 assertEquals(4, factory.searchCalls.size)268 assertEquals(1, factory.detailCalls.size)269 }270}271272internal class MigrationTestFactory(273 private val search: suspend (DbSource, String, Int) -> SourceListing = { _, query, _ -> SourceListing(listOf(RemoteManga(query, "/title")), false) },274 private val detail: suspend (DbSource, String) -> RemoteDetail = { _, url -> RemoteDetail("Title", url) },275) : ExtensionRuntimeFactory {276 val searchCalls = mutableListOf<Triple<Long, String, Int>>()277 val detailCalls = mutableListOf<Pair<Long, String>>()278 override fun create(source: DbSource): ExtensionRuntimeService = object : ExtensionRuntimeService by DatabaseFallbackRuntimeService(source, InMemoryYokanDatabase()) {279 override suspend fun search(query: String, page: Int, filters: List<SourceFilter>): SourceListing {280 searchCalls += Triple(source.id, query, page)281 return this@MigrationTestFactory.search(source, query, page)282 }283 override suspend fun detail(url: String): RemoteDetail {284 detailCalls += source.id to url285 return this@MigrationTestFactory.detail(source, url)286 }287 }288}289