MockHttpClient.kt (3065B)
1 /* 2 * This file is part of GNU Taler 3 * (C) 2020 Taler Systems S.A. 4 * 5 * GNU Taler is free software; you can redistribute it and/or modify it under the 6 * terms of the GNU General Public License as published by the Free Software 7 * Foundation; either version 3, or (at your option) any later version. 8 * 9 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY 10 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR 11 * A PARTICULAR PURPOSE. See the GNU General Public License for more details. 12 * 13 * You should have received a copy of the GNU General Public License along with 14 * GNU Taler; see the file COPYING. If not, see <http://www.gnu.org/licenses/> 15 */ 16 17 package net.taler.merchantlib 18 19 import io.ktor.client.HttpClient 20 import io.ktor.client.engine.mock.MockEngine 21 import io.ktor.client.engine.mock.MockEngineConfig 22 import io.ktor.client.engine.mock.respond 23 import io.ktor.client.plugins.contentnegotiation.ContentNegotiation 24 import io.ktor.http.ContentType.Application.Json 25 import io.ktor.http.HttpStatusCode 26 import io.ktor.http.Url 27 import io.ktor.http.content.TextContent 28 import io.ktor.http.fullPath 29 import io.ktor.http.headersOf 30 import io.ktor.http.hostWithPort 31 import io.ktor.serialization.kotlinx.json.json 32 import kotlinx.serialization.json.Json 33 import kotlinx.serialization.json.Json.Default.parseToJsonElement 34 import org.junit.Assert.assertEquals 35 36 object MockHttpClient { 37 38 val httpClient = HttpClient(MockEngine) { 39 engine { 40 addHandler { error("No response handler set") } 41 } 42 expectSuccess = true 43 install(ContentNegotiation) { 44 json(Json { 45 encodeDefaults = false 46 ignoreUnknownKeys = true 47 }) 48 } 49 } 50 51 fun HttpClient.giveJsonResponse( 52 url: String, 53 expectedBody: String? = null, 54 statusCode: HttpStatusCode = HttpStatusCode.OK, 55 jsonProducer: () -> String, 56 ) { 57 val httpConfig = engineConfig as MockEngineConfig 58 httpConfig.requestHandlers.removeAt(0) 59 httpConfig.requestHandlers.add { request -> 60 if (request.url.fullUrl == url) { 61 val headers = headersOf("Content-Type" to listOf(Json.toString())) 62 if (expectedBody != null) { 63 val content = request.body as TextContent 64 assertJsonEquals(expectedBody, content.text) 65 } 66 respond(jsonProducer(), headers = headers, status = statusCode) 67 } else { 68 error("Unexpected URL: ${request.url.fullUrl}") 69 } 70 } 71 } 72 73 private val Url.hostWithPortIfRequired: String get() = if (port == protocol.defaultPort) host else hostWithPort 74 private val Url.fullUrl: String get() = "${protocol.name}://$hostWithPortIfRequired$fullPath" 75 76 private fun assertJsonEquals(json1: String, json2: String) { 77 val parsed1 = parseToJsonElement(json1) 78 val parsed2 = parseToJsonElement(json2) 79 assertEquals(parsed1, parsed2) 80 } 81 82 }