TrackerTestHttp.kt
composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/services/tracking/TrackerTestHttp.kt
1package eu.friedcutlet.yokan.services.tracking23import eu.friedcutlet.yokan.services.http.HttpService4import eu.friedcutlet.yokan.services.http.KtorHttpService5import io.ktor.client.engine.mock.MockEngine6import io.ktor.client.engine.mock.respond7import io.ktor.client.request.HttpRequestData8import io.ktor.http.HttpStatusCode9import io.ktor.http.content.OutgoingContent10import io.ktor.http.headersOf1112/** One request as it reached the Ktor engine: the real HTTP boundary of the adapters. */13data class RecordedRequest(val method: String, val url: String, val headers: Map<String, String>, val body: String)1415/**16 * A [KtorHttpService] over a [MockEngine] whose [route] returns `status to body` (JSON) for each request.17 * Every request is appended to [requests]. Use 4xx for failures: KtorHttpService retries 5xx.18 */19class MockTrackerHttp(private val route: (RecordedRequest) -> Pair<Int, String>) {20 val requests = mutableListOf<RecordedRequest>()2122 val http: HttpService = KtorHttpService(23 MockEngine { data ->24 val recorded = data.recorded()25 requests += recorded26 val (status, body) = route(recorded)27 respond(body, HttpStatusCode.fromValue(status), headersOf("Content-Type", "application/json"))28 },29 )3031 private fun HttpRequestData.recorded(): RecordedRequest = RecordedRequest(32 method = method.value,33 url = url.toString(),34 headers = headers.entries().associate { (k, v) -> k to v.joinToString(",") } +35 (body.contentType?.let { mapOf("Content-Type" to it.toString()) } ?: emptyMap()),36 body = when (val content = body) {37 is OutgoingContent.ByteArrayContent -> content.bytes().decodeToString()38 else -> ""39 },40 )41}42