ProfileWebViewServiceTest.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/webview/ProfileWebViewServiceTest.kt
1@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)23package eu.friedcutlet.yokan.services.webview45import eu.friedcutlet.yokan.domain.ProfileId6import eu.friedcutlet.yokan.database.InMemoryYokanDatabase7import eu.friedcutlet.yokan.database.emptySnapshot8import eu.friedcutlet.yokan.services.http.HttpResponse9import eu.friedcutlet.yokan.services.http.cookies.CookieJar10import eu.friedcutlet.yokan.services.http.cookies.platformBrowserIsolation11import kotlinx.coroutines.CancellationException12import kotlinx.coroutines.CompletableDeferred13import kotlinx.coroutines.CoroutineScope14import kotlinx.coroutines.Job15import kotlinx.coroutines.NonCancellable16import kotlinx.coroutines.SupervisorJob17import kotlinx.coroutines.awaitCancellation18import kotlinx.coroutines.cancel19import kotlinx.coroutines.cancelAndJoin20import kotlinx.coroutines.currentCoroutineContext21import kotlinx.coroutines.launch22import kotlinx.coroutines.test.StandardTestDispatcher23import kotlinx.coroutines.test.UnconfinedTestDispatcher24import kotlinx.coroutines.test.runTest25import kotlinx.coroutines.withContext26import kotlin.test.Test27import kotlin.test.assertEquals28import kotlin.test.assertFailsWith29import kotlin.test.assertFalse30import kotlin.test.assertNull31import kotlin.test.assertTrue3233class ProfileWebViewServiceTest {34 @Test fun extraOwnersUseTheBrowserOnlyWithPlatformIsolation() = runTest {35 val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra)36 val browser = FakeBrowser(); var creations = 037 val service = ProfileWebViewService(jar, null) { creations++; browser }38 assertEquals(platformBrowserIsolation, service.open(Request))39 assertEquals(if (platformBrowserIsolation) "result" else "", service.evaluateScript(Request.url, "script"))40 assertEquals(if (platformBrowserIsolation) 1 else 0, creations)41 assertEquals(platformBrowserIsolation, jar.canUseBrowserStorage)42 }4344 @Test fun retiredExtraCannotConstructOrCallTheBrowser() = runTest {45 val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), Extra) { false }46 val service = ProfileWebViewService(jar, null) { error("Browser store accessed by retired extra owner") }47 assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request))48 assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url))49 }5051 @Test fun retiredDefaultCannotConstructOrCallTheBrowser() = runTest {52 val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { false }53 val service = ProfileWebViewService(jar, null) { error("Shared store accessed by retired owner") }54 assertFalse(service.open(Request)); assertNull(service.resolveCloudflare(Request))55 assertEquals("", service.evaluateScript(Request.url, "script")); assertNull(service.syncCookies(Request.url))56 }5758 @Test fun defaultUsesOneLazyBrowserAndPreservesAllRequestArguments() = runTest {59 val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()))60 val browser = FakeBrowser(); var creations = 061 val service = ProfileWebViewService(jar, null) { creations++; browser }62 assertEquals(0, creations)63 assertTrue(service.open(Request)); assertEquals(200, service.resolveCloudflare(Request)?.statusCode)64 assertEquals("result", service.evaluateScript(Request.url, "script", "agent"))65 assertEquals("session=cookie", service.syncCookies(Request.url))66 assertEquals(1, creations)67 assertEquals(listOf("open:$Request", "resolve:$Request", "script:${Request.url}:script:agent", "cookies:${Request.url}"), browser.calls)68 }6970 @Test fun ownerRetirementJoinsNativeCleanupAndSuppressesLateCookieHarvest() = runTest {71 val database = InMemoryYokanDatabase(emptySnapshot())72 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))73 val jar = CookieJar(database, ProfileId.Default) { parent.isActive }74 jar.put("source.test", "session=original")75 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()76 var finalized = false77 val browser = FakeBrowser().apply { action = {78 try { entered.complete(Unit); awaitCancellation() }79 finally { withContext(NonCancellable) {80 release.await(); jar.put("source.test", "session=late"); finalized = true81 } }82 } }83 val service = ProfileWebViewService(jar, scope) { browser }84 val caller = launch { service.resolveCloudflare(Request) }85 entered.await()86 val retiring = launch { parent.cancelAndJoin() }87 testScheduler.runCurrent(); assertFalse(retiring.isCompleted); assertFalse(caller.isCompleted)88 assertNull(service.syncCookies(Request.url))89 release.complete(Unit); retiring.join(); caller.join()90 assertTrue(finalized)91 assertEquals("session=original", CookieJar(database).cookieHeader(Request.url))92 assertEquals(1, browser.calls.size)93 }9495 @Test fun callerExpiryJoinsBrowserCleanupWithoutRetiringTheOwner() = runTest {96 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))97 val jar = CookieJar(InMemoryYokanDatabase(emptySnapshot()), ProfileId.Default) { parent.isActive }98 val entered = CompletableDeferred<Unit>(); val release = CompletableDeferred<Unit>()99 val browser = FakeBrowser().apply { action = {100 try { entered.complete(Unit); awaitCancellation() }101 finally { withContext(NonCancellable) { release.await() } }102 } }103 val service = ProfileWebViewService(jar, scope) { browser }104 val sibling = scope.launch { awaitCancellation() }105 val caller = launch { service.evaluateScript(Request.url, "script") }106 entered.await(); caller.cancel(); testScheduler.runCurrent()107 assertFalse(caller.isCompleted); assertTrue(parent.isActive); assertTrue(sibling.isActive)108 release.complete(Unit); caller.join(); browser.action = {}109 assertTrue(service.open(Request))110 parent.cancelAndJoin()111 }112113 @Test fun alreadyExpiredCallerCannotAccessTheBrowserWithImmediateDispatch() = runTest {114 val parent = SupervisorJob(); val scope = CoroutineScope(parent + UnconfinedTestDispatcher(testScheduler))115 var creations = 0116 val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() }117 val caller = launch {118 currentCoroutineContext().cancel()119 assertFailsWith<CancellationException> { service.open(Request) }120 }121 caller.join(); assertEquals(0, creations); assertTrue(parent.isActive)122 parent.cancelAndJoin()123 }124125 @Test fun queuedCallCanceledBeforeDispatchCannotInitializeTheBrowser() = runTest {126 val parent = SupervisorJob(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))127 var creations = 0128 val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { creations++; FakeBrowser() }129 val caller = launch(UnconfinedTestDispatcher(testScheduler)) { service.open(Request) }130 parent.cancel(); testScheduler.runCurrent(); caller.join(); parent.join()131 assertEquals(0, creations)132 assertFalse(service.open(Request)) // The owner gate also covers standalone jars with no lifetime predicate.133 }134135 @Test fun browserFailureDoesNotCancelAnOrdinaryParentJobOrSiblingWork() = runTest {136 val parent = Job(); val scope = CoroutineScope(parent + StandardTestDispatcher(testScheduler))137 val browser = FakeBrowser().apply { action = { error("Native browser failure") } }138 val service = ProfileWebViewService(CookieJar(InMemoryYokanDatabase(emptySnapshot())), scope) { browser }139 val sibling = scope.launch { awaitCancellation() }140 assertFailsWith<IllegalStateException> { service.syncCookies(Request.url) }141 assertTrue(parent.isActive); assertTrue(sibling.isActive)142 browser.action = {}; assertTrue(service.open(Request)); parent.cancelAndJoin()143 }144145 private class FakeBrowser : WebViewService {146 val calls = mutableListOf<String>()147 var action: suspend () -> Unit = {}148 override suspend fun open(request: WebViewRequest): Boolean { calls += "open:$request"; action(); return true }149 override suspend fun resolveCloudflare(request: WebViewRequest): HttpResponse { calls += "resolve:$request"; action(); return HttpResponse(200, "ok") }150 override suspend fun evaluateScript(url: String, script: String, userAgent: String?): String { calls += "script:$url:$script:$userAgent"; action(); return "result" }151 override suspend fun syncCookies(url: String): String { calls += "cookies:$url"; action(); return "session=cookie" }152 }153154 private companion object {155 val Extra = ProfileId("p_11111111111111111111111111111111")156 val Request = WebViewRequest("https://source.test/", "Source", mapOf("Referer" to "https://source.test"))157 }158}159