IsolatedBrowserHttpTest.kt
composeApp/src/wasmJsTest/kotlin/eu/friedcutlet/yokan/services/http/IsolatedBrowserHttpTest.kt
1@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)23package eu.friedcutlet.yokan.services.http45import eu.friedcutlet.yokan.domain.ProfileId6import kotlinx.coroutines.test.runTest7import kotlin.test.*89class IsolatedBrowserHttpTest {10 @Test fun anonymousFetchRetainsExplicitAuthorizationAndBinaryResponse() = runTest {11 installFetchProbe()12 val client = createPlatformHttpService(Extra)13 try {14 val response = client.request(HttpRequest("https://example.test/data", headers = mapOf("Authorization" to "Bearer own-token")))15 assertEquals(200, response.statusCode)16 assertContentEquals(byteArrayOf(65, 0, 66), response.bodyBytes)17 assertEquals("omit:no-store:Bearer own-token", capturedOptions())18 } finally { client.closeAndJoin(); removeFetchProbe() }19 }2021 @Test fun cookieAuthenticationIsRefusedBeforeCallingSharedBrowserTransport() = runTest {22 installFetchProbe()23 val client = createPlatformHttpService(Extra)24 try {25 assertFailsWith<IllegalStateException> { client.request(HttpRequest("https://example.test/data", headers = mapOf("Cookie" to "owner=extra"))) }26 assertEquals(0, capturedCalls())27 } finally { client.closeAndJoin(); removeFetchProbe() }28 }29 companion object { private val Extra = ProfileId("p_${"e".repeat(32)}") }30}31private fun capturedOptions(): String = js("globalThis.__yokanFetchProbe.options")32private fun capturedCalls(): Int = js("globalThis.__yokanFetchProbe.calls")33private fun installFetchProbe(): Unit = js(34 """35 (() => {36 globalThis.__yokanFetchProbe = { original: globalThis.fetch, calls: 0, options: '' };37 globalThis.fetch = async (url, init) => {38 const probe = globalThis.__yokanFetchProbe;39 probe.calls++;40 probe.options = init.credentials + ':' + init.cache + ':' + init.headers.Authorization;41 return new Response(new Uint8Array([65, 0, 66]), {status: 200});42 };43 })()44 """,45)46private fun removeFetchProbe(): Unit = js(47 """48 (() => { globalThis.fetch = globalThis.__yokanFetchProbe.original; delete globalThis.__yokanFetchProbe; })()49 """,50)51