Yokan / rebuild
Course 1 8624561

ExtensionHostContractTest.kt

composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/services/extensions/ExtensionHostContractTest.kt

test / fixture112 lines
1package eu.friedcutlet.yokan.services.extensions23import eu.friedcutlet.yokan.database.DbItemType4import eu.friedcutlet.yokan.services.files.JvmLocalFileService5import eu.friedcutlet.yokan.services.http.HttpRequest6import eu.friedcutlet.yokan.services.http.HttpResponse7import eu.friedcutlet.yokan.services.http.HttpService8import java.nio.file.Path9import kotlin.test.Test10import kotlin.test.assertTrue11import kotlinx.coroutines.test.runTest12import eu.friedcutlet.yokan.services.extensions.js.JavaScriptExtensionRuntimeService1314/**15 * Drives every generated source's popular / search / detail / video-or-page16 * paths through the real QuickJS runtime using canned HTML (no network), to17 * prove the host contract is complete — no missing globals, JS builtins,18 * `SharedPreferences` accessors, `Crypto` helpers, or DOM methods. Errors are19 * classified: host/runtime defects fail the test; domain errors (a source20 * throwing because the fixture doesn't match its site, or JSON.parse on HTML)21 * are expected and ignored.22 *23 * Deterministic and offline, so it runs in the default suite whenever24 * `-Dyokan.generated.repository` points at a built anime index.25 */26class ExtensionHostContractTest {27    @Test28    fun everySourceExercisesHostContractWithoutDefects() = runTest {29        val repoProperty = System.getProperty("yokan.generated.repository") ?: return@runTest30        val repositoryPath = Path.of(repoProperty).toAbsolutePath().normalize()31        val repositoryUrl = repositoryPath.toUri().toString()32        val files = JvmLocalFileService(33            downloadRoot = repositoryPath.parent.toString(),34            backupRoot = repositoryPath.parent.toString(),35            cacheRoot = repositoryPath.parent.toString(),36        )37        val catalog = HttpSourceCatalogService(FixtureHttpService, files)38        val sources = catalog.fetchSources(repositoryUrl, DbItemType.Anime)39        assertTrue(sources.isNotEmpty(), "no anime sources found")4041        val defects = mutableListOf<String>()42        for (source in sources) {43            val payload = catalog.fetchSourcePayload(source)?.decodeToString() ?: continue44            val runtime = JavaScriptExtensionRuntimeService(source = source.copy(sourceCode = payload), http = FixtureHttpService)45            try {46                exercise(source.name, "popular") { runtime.popular(1) }?.let { defects += it }47                exercise(source.name, "search") { runtime.search("a", 1, emptyList()) }?.let { defects += it }48                val listing = runCatching { runtime.popular(1) }.getOrNull()49                val entry = listing?.items?.firstOrNull()50                if (entry != null) {51                    val detail = runCatching { runtime.detail(entry.url) }.getOrNull()52                    exercise(source.name, "detail") { runtime.detail(entry.url) }?.let { defects += it }53                    val chapter = detail?.chapters?.firstOrNull()54                    if (chapter != null) {55                        exercise(source.name, "videoList") { runtime.videoList(chapter.url) }?.let { defects += it }56                    }57                }58            } finally {59                runtime.dispose()60            }61        }62        assertTrue(63            defects.isEmpty(),64            "Host-contract defects in ${defects.size} path(s):\n${defects.joinToString("\n")}",65        )66    }6768    /** Returns a defect description if the step hit a host/runtime gap, else null. */69    private suspend fun exercise(name: String, step: String, block: suspend () -> Any?): String? {70        return try {71            block()72            null73        } catch (error: Throwable) {74            val message = (generateSequence(error) { it.cause }.lastOrNull()?.message ?: error.message).orEmpty()75            if (isHostDefect(message)) "$name.$step: ${message.take(160)}" else null76        }77    }7879    private companion object {80        fun isHostDefect(message: String): Boolean {81            val lower = message.lowercase()82            return "is not a function" in lower || "is not defined" in lower || "no setter" in lower ||83                "not a constructor" in lower || "bridge channel" in lower ||84                "is not an object" in lower85        }86    }87}8889/** Serves a rich generic anime/listing HTML for any URL so parsing code paths execute. */90private object FixtureHttpService : HttpService {91    private val html = """92        <!doctype html><html><head><title>Fixture</title>93        <meta property="og:image" content="/img/cover.jpg">94        <meta itemprop="embedUrl" content="https://player.test/embed/1"></head><body>95        <div class="listupd"><article class="bs"><a class="tip" href="/anime/one"><div class="tt">One</div>96        <h2>One</h2><img class="ts-post-image" src="/i/1.jpg" data-src="/i/1.jpg" data-original="/i/1.jpg"></a></article></div>97        <div class="result"><div class="item"><a href="/anime/one"><div class="title">One</div><img src="/i/1.jpg"></a></div></div>98        <ul class="episodios"><li><div class="episodiotitle"><a href="/ep/1">Ep 1</a></div></li></ul>99        <ul class="eplister"><li><a href="/ep/1"><div class="epl-num">1</div><div class="epl-title">E1</div></a></li></ul>100        <div class="pagination"><a class="next page-numbers" href="/page/2">Next</a></div>101        <div class="image-container"><div class="image-wrapper"><a class="overlay" href="/v/1">V1</a><img src="/t/1.jpg" data-original="/t/1.jpg"></div></div>102        <div class="download-container"><a class="download-button" href="/dl/1">DL</a></div>103        <select class="mirror"><option data-index="0" value="s1">S1</option></select>104        <article><h1 class="entry-title">Title</h1><div class="entry-content" itemprop="description">Desc</div></article>105        <div id="pembed"><iframe src="https://player.test/embed/1"></iframe></div>106        <script>var config = {"file":"https://cdn.test/master.m3u8","sources":[{"file":"https://cdn.test/1.mp4","label":"720p"}]};</script>107        </body></html>108    """.trimIndent()109110    override suspend fun request(request: HttpRequest): HttpResponse =111        HttpResponse(statusCode = 200, body = html, headers = mapOf("content-type" to "text/html"))112}113

Search chapters, reference and source filenames.