package eu.friedcutlet.yokan.services.tracking import eu.friedcutlet.yokan.services.http.HttpService import eu.friedcutlet.yokan.services.http.KtorHttpService import io.ktor.client.engine.mock.MockEngine import io.ktor.client.engine.mock.respond import io.ktor.client.request.HttpRequestData import io.ktor.http.HttpStatusCode import io.ktor.http.content.OutgoingContent import io.ktor.http.headersOf /** One request as it reached the Ktor engine: the real HTTP boundary of the adapters. */ data class RecordedRequest(val method: String, val url: String, val headers: Map, val body: String) /** * A [KtorHttpService] over a [MockEngine] whose [route] returns `status to body` (JSON) for each request. * Every request is appended to [requests]. Use 4xx for failures: KtorHttpService retries 5xx. */ class MockTrackerHttp(private val route: (RecordedRequest) -> Pair) { val requests = mutableListOf() val http: HttpService = KtorHttpService( MockEngine { data -> val recorded = data.recorded() requests += recorded val (status, body) = route(recorded) respond(body, HttpStatusCode.fromValue(status), headersOf("Content-Type", "application/json")) }, ) private fun HttpRequestData.recorded(): RecordedRequest = RecordedRequest( method = method.value, url = url.toString(), headers = headers.entries().associate { (k, v) -> k to v.joinToString(",") } + (body.contentType?.let { mapOf("Content-Type" to it.toString()) } ?: emptyMap()), body = when (val content = body) { is OutgoingContent.ByteArrayContent -> content.bytes().decodeToString() else -> "" }, ) }