|
| 1 | +package io.github.smiley4.ktorredoc |
| 2 | + |
| 3 | +import io.github.smiley4.ktorredoc.config.RedocConfig |
| 4 | +import io.kotest.matchers.shouldBe |
| 5 | +import io.kotest.matchers.string.shouldNotBeEmpty |
| 6 | +import io.ktor.client.HttpClient |
| 7 | +import io.ktor.client.request.* |
| 8 | +import io.ktor.client.statement.bodyAsText |
| 9 | +import io.ktor.http.ContentType |
| 10 | +import io.ktor.http.HttpStatusCode |
| 11 | +import io.ktor.http.contentType |
| 12 | +import io.ktor.http.withCharset |
| 13 | +import io.ktor.server.response.respondText |
| 14 | +import io.ktor.server.routing.get |
| 15 | +import io.ktor.server.routing.route |
| 16 | +import io.ktor.server.testing.testApplication |
| 17 | +import kotlin.test.Test |
| 18 | + |
| 19 | +class RoutingTests { |
| 20 | + |
| 21 | + @Test |
| 22 | + fun defaultConfig() = redocTestApplication { |
| 23 | + get("hello").also { |
| 24 | + it.status shouldBe HttpStatusCode.OK |
| 25 | + it.body shouldBe "Hello Test" |
| 26 | + } |
| 27 | + get("/redoc").also { |
| 28 | + it.status shouldBe HttpStatusCode.Found |
| 29 | + it.redirect shouldBe "/redoc/index.html" |
| 30 | + } |
| 31 | + get("/redoc/index.html").also { |
| 32 | + it.status shouldBe HttpStatusCode.OK |
| 33 | + it.contentType shouldBe ContentType.Text.Html.withCharset(java.nio.charset.Charset.forName("UTF-8")) |
| 34 | + it.body.shouldNotBeEmpty() |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private fun redocTestApplication(config: RedocConfig.() -> Unit = {}, block: suspend TestContext.() -> Unit = {}) { |
| 39 | + testApplication { |
| 40 | + val client = createClient { |
| 41 | + this.followRedirects = false |
| 42 | + } |
| 43 | + routing { |
| 44 | + route("redoc") { |
| 45 | + redoc("api.json", config) |
| 46 | + } |
| 47 | + get("hello") { |
| 48 | + call.respondText("Hello Test") |
| 49 | + } |
| 50 | + } |
| 51 | + TestContext(client).apply { block() } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + class TestContext(private val client: HttpClient) { |
| 56 | + |
| 57 | + suspend fun get(path: String): GetResult { |
| 58 | + return client.get(path) |
| 59 | + .let { |
| 60 | + GetResult( |
| 61 | + path = path, |
| 62 | + status = it.status, |
| 63 | + contentType = it.contentType(), |
| 64 | + body = it.bodyAsText(), |
| 65 | + redirect = it.headers["Location"] |
| 66 | + ) |
| 67 | + } |
| 68 | + .also { it.print() } |
| 69 | + } |
| 70 | + |
| 71 | + |
| 72 | + private fun GetResult.print() { |
| 73 | + println("GET ${this.path} => ${this.status} (${this.contentType}): ${this.body}") |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + data class GetResult( |
| 78 | + val path: String, |
| 79 | + val status: HttpStatusCode, |
| 80 | + val contentType: ContentType?, |
| 81 | + val body: String, |
| 82 | + val redirect: String? |
| 83 | + ) |
| 84 | + |
| 85 | +} |
0 commit comments