Skip to content

Instantly share code, notes, and snippets.

@nikarh
Created March 13, 2020 22:33
Show Gist options
  • Save nikarh/f6547297b48cc0e8e091741cb45c173c to your computer and use it in GitHub Desktop.
Save nikarh/f6547297b48cc0e8e091741cb45c173c to your computer and use it in GitHub Desktop.
A 0 dependency replacement for Hoverfly, WireMock and MockServer. Simple stupid and extendable
package net.arhipov
import com.sun.net.httpserver.Headers
import com.sun.net.httpserver.HttpServer
import java.net.InetSocketAddress
import java.net.URI
import java.util.Collections.synchronizedList
class MockHttpServer(
port: Int = 0
) : AutoCloseable {
data class Capture(
val request: Request,
val response: Response
)
class Request(
val uri: URI,
val method: String,
val body: ByteArray,
val headers: Headers
)
class Response(
val body: ByteArray,
val status: Int,
val headers: Headers
)
private val httpServer: HttpServer = HttpServer.create(InetSocketAddress(port), 0)
.apply {
start()
createContext("/") { ctx ->
val request = Request(
uri = ctx.requestURI,
method = ctx.requestMethod,
body = ctx.requestBody.readAllBytes(),
headers = ctx.requestHeaders
)
val response = matchers
.asSequence()
.map { it(request) }
.firstOrNull { it != null }
?: Response("".toByteArray(), 500, Headers())
captures.add(response)
ctx.responseHeaders.putAll(response.headers)
ctx.sendResponseHeaders(response.status, response.body.size.toLong())
ctx.responseBody.write(response.body)
}
}
val captures: MutableList<Response> = synchronizedList(mutableListOf())
val matchers: MutableList<(request: Request) -> Response?> = synchronizedList(mutableListOf())
val port: Int get() = httpServer.address.port
fun reset() {
captures.clear()
matchers.clear()
}
override fun close() {
httpServer.stop(0)
}
}
fun MockHttpServer.addHandler(
matcher: (request: MockHttpServer.Request) -> Boolean,
responseWriter: (request: MockHttpServer.Request) -> MockHttpServer.Response
) {
matchers.add {
if (matcher(it)) responseWriter(it)
else null
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment