MihonExtensionRuntimeServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/extensions/mihon/MihonExtensionRuntimeServiceTest.kt
1package eu.friedcutlet.yokan.services.extensions.mihon23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.database.DbSource5import eu.friedcutlet.yokan.database.DbSourceCodeLanguage6import eu.friedcutlet.yokan.database.DbSourcePreference7import eu.friedcutlet.yokan.database.InMemoryYokanDatabase8import eu.friedcutlet.yokan.database.seedDatabaseSnapshot9import eu.friedcutlet.yokan.domain.Chapter10import eu.friedcutlet.yokan.domain.TitleCredit11import eu.friedcutlet.yokan.services.http.HttpRequest12import eu.friedcutlet.yokan.services.http.HttpResponse13import eu.friedcutlet.yokan.services.http.HttpService14import kotlin.test.Test15import kotlin.test.assertEquals16import kotlin.test.assertFailsWith17import kotlin.test.assertNotNull18import kotlin.test.assertNull19import kotlin.test.assertTrue20import kotlinx.coroutines.test.runTest21import eu.friedcutlet.yokan.services.extensions.DynamicExtensionRuntimeFactory2223/**24 * Integration-style test: drives `MihonExtensionRuntimeService` against a fake `HttpService` that25 * replays canned ApkBridge `/dalvik` responses, covering the popular/search/detail round trips,26 * Cloudflare HTTP 503, ApkBridge HTTP 404, and bridge-level error JSON.27 */28class MihonExtensionRuntimeServiceTest {29 private val source = DbSource(30 id = 555L,31 name = "Mihon Sample",32 baseUrl = "https://example.org",33 lang = "en",34 itemType = DbItemType.Manga,35 sourceCodeLanguage = DbSourceCodeLanguage.Mihon,36 sourceCode = "BASE64_BUNDLE",37 supportLatest = true,38 )3940 @Test41 fun popularRoundTripsThroughDalvik() = runTest {42 val http = MihonFakeHttpService { request ->43 assertEquals("$PROXY/dalvik", request.url)44 assertEquals("POST", request.method)45 assertTrue(request.body!!.contains("\"method\":\"getPopularManga\""))46 HttpResponse(47 statusCode = 200,48 body = """49 {50 "list": [51 {"name": "Apex", "link": "/manga/apex", "imageUrl": "https://example.org/apex.jpg"},52 {"name": "Bravo", "link": "/manga/bravo"}53 ],54 "hasNextPage": true55 }56 """.trimIndent(),57 )58 }59 val service = MihonExtensionRuntimeService(source, http, PROXY)60 val listing = service.popular(0)61 assertEquals(2, listing.items.size)62 assertEquals("Apex", listing.items.first().title)63 assertTrue(listing.hasNextPage)64 service.dispose()65 }6667 @Test68 fun preparesLocalServerBeforeFirstDalvikRequest() = runTest {69 var preparations = 070 val http = MihonFakeHttpService { request ->71 assertEquals("http://localhost:7788/dalvik", request.url)72 HttpResponse(200, """{"list": [], "hasNextPage": false}""")73 }74 val service = MihonExtensionRuntimeService(source, http, PROXY) {75 preparations += 176 "http://localhost:7788"77 }7879 service.popular(0)8081 assertEquals(1, preparations)82 }8384 @Test85 fun searchSendsFilterListAndMapsResults() = runTest {86 val http = MihonFakeHttpService { request ->87 assertTrue(request.body!!.contains("\"method\":\"getSearchManga\""))88 assertTrue(request.body.contains("\"search\":\"hero\""))89 assertTrue(request.body.contains("\"filterList\""))90 HttpResponse(91 statusCode = 200,92 body = """93 {"list": [{"name": "Hero Match", "link": "/manga/hero-match"}], "hasNextPage": false}94 """.trimIndent(),95 )96 }97 val service = MihonExtensionRuntimeService(source, http, PROXY)98 val listing = service.search("hero", 1, emptyList())99 assertEquals(1, listing.items.size)100 assertEquals("Hero Match", listing.items.first().title)101 service.dispose()102 }103104 @Test105 fun detailParsesMetadataAndChapters() = runTest {106 val responses = ArrayDeque(107 listOf(108 """109 {110 "name": "Apex",111 "url": "/manga/apex",112 "description": "Synopsis here.",113 "author": "Anon",114 "artist": "Anon",115 "cast": [{"name":"Actor A","character":"Hero","image_url":"https://cdn.example/a.jpg"}]116 }117 """.trimIndent(),118 """119 [120 {"name": "Chapter 1", "url": "/manga/apex/c1", "dateUpload": "1700000000"},121 {"name": "Chapter 2", "url": "/manga/apex/c2", "dateUpload": "1700100000", "scanlator": "Scans"}122 ]123 """.trimIndent(),124 ),125 )126 val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 200, body = responses.removeFirst()) }127 val service = MihonExtensionRuntimeService(source, http, PROXY)128 val detail = service.detail("/manga/apex")129 assertEquals("Apex", detail.title)130 assertEquals(listOf(TitleCredit("Actor A", character = "Hero", imageUrl = "https://cdn.example/a.jpg")), detail.cast)131 assertEquals(2, detail.chapters.size)132 assertEquals("Scans", detail.chapters[1].scanlator)133 service.dispose()134 }135136 @Test137 fun cloudflareResponseSurfacesUsefulError() = runTest {138 val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 503, body = "challenge page") }139 val service = MihonExtensionRuntimeService(source, http, PROXY)140 val exception = assertFailsWith<IllegalStateException> { service.popular(0) }141 assertTrue("Cloudflare" in exception.message.orEmpty())142 service.dispose()143 }144145 @Test146 fun missingDalvikEndpointSurfacesActionableError() = runTest {147 val http = MihonFakeHttpService { _ -> HttpResponse(statusCode = 404, body = "Not Found") }148 val service = MihonExtensionRuntimeService(source, http, PROXY)149 val exception = assertFailsWith<IllegalStateException> { service.popular(0) }150 assertTrue("404" in exception.message.orEmpty())151 service.dispose()152 }153154 @Test155 fun bridgeJsonErrorIsUnwrapped() = runTest {156 val http = MihonFakeHttpService { _ ->157 HttpResponse(158 statusCode = 200,159 body = """{"error": "APK payload invalid", "code": "MIHON_APK_INVALID"}""",160 )161 }162 val service = MihonExtensionRuntimeService(source, http, PROXY)163 val exception = assertFailsWith<IllegalStateException> { service.popular(0) }164 assertTrue("APK" in exception.message.orEmpty() || "Re-install" in exception.message.orEmpty())165 service.dispose()166 }167168 @Test169 fun browserFetchFailureSurfacesCorsHint() = runTest {170 val http = MihonFakeHttpService { _ -> throw IllegalStateException("TypeError: Failed to fetch") }171 val service = MihonExtensionRuntimeService(source, http, "https://extensions.example")172 val exception = assertFailsWith<IllegalStateException> { service.popular(0) }173 assertTrue("CORS" in exception.message.orEmpty())174 service.dispose()175 }176177 @Test178 fun multiSourceContextRidesInPreferences() = runTest {179 val factorySource = source.copy(180 id = 601L,181 additionalParams = """{"sourceId":"8842237058298566885"}""",182 )183 val http = MihonFakeHttpService { request ->184 assertTrue(request.body!!.contains("\"__mangayomi_bridge_context__\""))185 assertTrue(request.body.contains("\"sourceId\":\"8842237058298566885\""))186 HttpResponse(statusCode = 200, body = """{"list": [], "hasNextPage": false}""")187 }188 val service = MihonExtensionRuntimeService(factorySource, http, PROXY)189 service.popular(0)190 service.dispose()191 }192193 @Test194 fun sourcesWithoutUpstreamIdSendNoBridgeContext() = runTest {195 val http = MihonFakeHttpService { request ->196 assertTrue("__mangayomi_bridge_context__" !in request.body!!)197 HttpResponse(statusCode = 200, body = """{"list": [], "hasNextPage": false}""")198 }199 val service = MihonExtensionRuntimeService(source.copy(id = 602L), http, PROXY)200 service.popular(0)201 service.dispose()202 }203204 @Test205 fun extensionHandleReplacesApkPayloadOnSubsequentCalls() = runTest {206 val handleSource = source.copy(id = 603L)207 val bodies = mutableListOf<String>()208 val http = MihonFakeHttpService { request ->209 bodies += request.body!!210 HttpResponse(211 statusCode = 200,212 body = """{"list": [], "hasNextPage": false}""",213 headers = mapOf("X-Mangayomi-Extension-Id" to "handle-603"),214 )215 }216 val service = MihonExtensionRuntimeService(handleSource, http, PROXY)217 service.popular(0)218 service.popular(0)219 assertTrue("\"data\":\"BASE64_BUNDLE\"" in bodies[0])220 assertTrue("extensionId" !in bodies[0])221 assertTrue("\"extensionId\":\"handle-603\"" in bodies[1])222 assertTrue("BASE64_BUNDLE" !in bodies[1])223 }224225 @Test226 fun staleHandleRetriesWithApkAfterConflict() = runTest {227 val handleSource = source.copy(id = 604L)228 val bodies = mutableListOf<String>()229 var conflictSent = false230 val http = MihonFakeHttpService { request ->231 bodies += request.body!!232 when {233 "extensionId" in request.body && !conflictSent -> {234 conflictSent = true235 HttpResponse(statusCode = 409, body = """{"error":"Extension not loaded","code":409}""")236 }237 else -> HttpResponse(238 statusCode = 200,239 body = """{"list": [], "hasNextPage": false}""",240 headers = mapOf("X-Mangayomi-Extension-Id" to "handle-604"),241 )242 }243 }244 val service = MihonExtensionRuntimeService(handleSource, http, PROXY)245 service.popular(0)246 val listing = service.popular(0)247 assertEquals(0, listing.items.size)248 assertEquals(3, bodies.size)249 assertTrue("\"extensionId\":\"handle-604\"" in bodies[1])250 assertTrue("\"data\":\"BASE64_BUNDLE\"" in bodies[2])251 }252253 @Test254 fun updatedApkPayloadInvalidatesCachedHandle() = runTest {255 val handleSource = source.copy(id = 605L)256 val bodies = mutableListOf<String>()257 val http = MihonFakeHttpService { request ->258 bodies += request.body!!259 HttpResponse(260 statusCode = 200,261 body = """{"list": [], "hasNextPage": false}""",262 headers = mapOf("X-Mangayomi-Extension-Id" to "handle-605"),263 )264 }265 val factory = DynamicExtensionRuntimeFactory(InMemoryYokanDatabase(), http)266 factory.withRuntime(handleSource) { it.popular(0) }267 factory.withRuntime(handleSource) { it.popular(0) }268 factory.withRuntime(handleSource.copy(sourceCode = "UPDATED_BUNDLE")) { it.popular(0) }269 assertTrue("\"extensionId\":\"handle-605\"" in bodies[1])270 assertTrue("\"data\":\"UPDATED_BUNDLE\"" in bodies[2])271 assertTrue("extensionId" !in bodies[2])272 }273274 @Test275 fun fetchMetadataRetrievesAllMetadataForManga() = runTest {276 val requests = mutableListOf<HttpRequest>()277 val http = MihonFakeHttpService { request ->278 requests += request279 val body = request.body.orEmpty()280 when {281 "\"method\":\"headersManga\"" in body -> HttpResponse(282 statusCode = 200,283 body = """["User-Agent", "Test-Agent/1.0", "Referer", "https://example.org/"]""",284 )285 "\"method\":\"supportLatestManga\"" in body -> HttpResponse(286 statusCode = 200,287 body = "true",288 )289 "\"method\":\"filtersManga\"" in body -> HttpResponse(290 statusCode = 200,291 body = """[{"name":"Sort","type_name":"SortFilter","state":{"index":0,"ascending":true},"values":["A","B"]}]""",292 )293 "\"method\":\"preferencesManga\"" in body -> HttpResponse(294 statusCode = 200,295 body = """[{"key":"pref1","switchPreferenceCompat":{"title":"Pref 1","value":true}}]""",296 )297 else -> HttpResponse(statusCode = 404, body = "Not Found")298 }299 }300 val service = MihonExtensionRuntimeService(source, http, PROXY)301 val metadata = service.fetchMetadata()302303 assertEquals(4, requests.size)304 // Verify sourceId and lang are sent305 assertTrue(requests.all { it.body!!.contains("\"sourceId\":\"555\"") })306 assertTrue(requests.all { it.body!!.contains("\"lang\":\"en\"") })307308 assertNotNull(metadata.headers)309 assertTrue(metadata.headers.contains("\"User-Agent\":\"Test-Agent/1.0\""))310 assertEquals(true, metadata.supportLatest)311 assertNotNull(metadata.filterList)312 assertTrue(metadata.filterList.contains("SortFilter"))313 assertNotNull(metadata.preferenceList)314 assertTrue(metadata.preferenceList.contains("switchPreferenceCompat"))315 service.dispose()316 }317318 @Test319 fun fetchMetadataRetrievesAnimeMethodsForAnimeSource() = runTest {320 val animeSource = source.copy(itemType = DbItemType.Anime)321 val calledMethods = mutableListOf<String>()322 val http = MihonFakeHttpService { request ->323 val body = request.body.orEmpty()324 when {325 "headersAnime" in body -> {326 calledMethods += "headersAnime"327 HttpResponse(200, """["User-Agent", "AnimeUA"]""")328 }329 "supportLatestAnime" in body -> {330 calledMethods += "supportLatestAnime"331 HttpResponse(200, "false")332 }333 "filtersAnime" in body -> {334 calledMethods += "filtersAnime"335 HttpResponse(200, "[]")336 }337 "preferencesAnime" in body -> {338 calledMethods += "preferencesAnime"339 HttpResponse(200, "[]")340 }341 else -> HttpResponse(404, "Not Found")342 }343 }344 val service = MihonExtensionRuntimeService(animeSource, http, PROXY)345 val metadata = service.fetchMetadata()346347 assertEquals(listOf("headersAnime", "supportLatestAnime", "filtersAnime", "preferencesAnime"), calledMethods)348 assertEquals(false, metadata.supportLatest)349 service.dispose()350 }351352 @Test353 fun fetchMetadataToleratesServerFailureGracefully() = runTest {354 val http = MihonFakeHttpService { _ ->355 throw IllegalStateException("Connection refused")356 }357 val service = MihonExtensionRuntimeService(source, http, PROXY)358 val metadata = service.fetchMetadata()359360 assertNull(metadata.headers)361 assertNull(metadata.supportLatest)362 assertNull(metadata.filterList)363 assertNull(metadata.preferenceList)364 service.dispose()365 }366367 @Test368 fun sourcePreferencesFetchesFromDalvikWhenEmptyAndSavesToDb() = runTest {369 val db = InMemoryYokanDatabase(seedDatabaseSnapshot().copy(sources = listOf(source)))370 val http = MihonFakeHttpService { request ->371 assertTrue(request.body!!.contains("\"method\":\"preferencesManga\""))372 HttpResponse(373 statusCode = 200,374 body = """375 [376 {377 "key": "pref_theme",378 "listPreference": {379 "title": "Theme",380 "summary": "Choose theme",381 "valueIndex": 1,382 "entries": ["Light", "Dark"],383 "entryValues": ["light", "dark"]384 }385 },386 {387 "key": "pref_auto_download",388 "switchPreferenceCompat": {389 "title": "Auto Download",390 "summary": "Download new chapters",391 "value": true392 }393 }394 ]395 """.trimIndent(),396 )397 }398 val service = MihonExtensionRuntimeService(source, http, PROXY, database = db)399 val prefs = service.sourcePreferences()400401 assertEquals(2, prefs.size)402 assertEquals("pref_theme", prefs[0].key)403 assertEquals("Theme", prefs[0].title)404 assertEquals("dark", prefs[0].value)405 assertEquals("listPreference", prefs[0].type)406 assertEquals(listOf("light", "dark"), prefs[0].values)407408 assertEquals("pref_auto_download", prefs[1].key)409 assertEquals("true", prefs[1].value)410411 // Verify the raw JSON array was persisted in the database for the source412 val updatedSource = db.source(source.id)413 assertNotNull(updatedSource?.preferenceList)414 assertTrue(updatedSource.preferenceList.contains("pref_theme"))415 service.dispose()416 }417418 @Test419 fun sourcePreferencesUsesExistingListWithoutNetworkRequest() = runTest {420 var networkCalls = 0421 val sourceWithPrefs = source.copy(422 preferenceList = """[{"key":"cached_pref","switchPreferenceCompat":{"title":"Cached","value":true}}]""",423 )424 val http = MihonFakeHttpService { _ ->425 networkCalls += 1426 HttpResponse(200, "[]")427 }428 val service = MihonExtensionRuntimeService(sourceWithPrefs, http, PROXY)429 val prefs = service.sourcePreferences()430431 assertEquals(0, networkCalls)432 assertEquals(1, prefs.size)433 assertEquals("cached_pref", prefs.first().key)434 assertEquals("true", prefs.first().value)435 service.dispose()436 }437438 @Test439 fun userPreferenceOverridesAppliedInDalvikRequests() = runTest {440 val sourceWithPrefs = source.copy(441 preferenceList = """442 [443 {"key":"pref_dark","switchPreferenceCompat":{"title":"Dark Mode","value":false}},444 {"key":"pref_quality","listPreference":{"title":"Quality","valueIndex":0,"entries":["Low","High"],"entryValues":["low","high"]}}445 ]446 """.trimIndent(),447 )448 val db = InMemoryYokanDatabase(449 seedDatabaseSnapshot().copy(450 sources = listOf(sourceWithPrefs),451 settings = seedDatabaseSnapshot().settings.copy(452 sourcePreferences = listOf(453 DbSourcePreference(sourceId = sourceWithPrefs.id, key = "pref_dark", value = "true"),454 DbSourcePreference(sourceId = sourceWithPrefs.id, key = "pref_quality", value = "high"),455 ),456 ),457 ),458 )459 var capturedBody = ""460 val http = MihonFakeHttpService { request ->461 capturedBody = request.body.orEmpty()462 HttpResponse(200, """{"list":[],"hasNextPage":false}""")463 }464 val service = MihonExtensionRuntimeService(sourceWithPrefs, http, PROXY, database = db)465 service.popular(0)466467 assertTrue(capturedBody.contains("\"pref_dark\""))468 assertTrue(capturedBody.contains("\"value\":true"))469 assertTrue(capturedBody.contains("\"pref_quality\""))470 assertTrue(capturedBody.contains("\"valueIndex\":1"))471 service.dispose()472 }473474 companion object {475 private const val PROXY = "https://extensions.example"476 }477}478479private class MihonFakeHttpService(private val handler: (HttpRequest) -> HttpResponse) : HttpService {480 override suspend fun request(request: HttpRequest): HttpResponse = handler(request)481}482