std::http::testing
Serves std::http’s requests with a function instead of the network, and
records them. testing.run(answer, body) runs body; every request
std::http sends in it, and in the tasks it starts, gets its response from
answer, and the result holds body’s value and the requests, in order.
ran = testing.run(fn _ -> Ok(Response{body: Body.Text("ann")}), fn -> user_name("7")) assert ran.value == Ok("ann")
answer can be a program’s own handler, so a client and a server are
tested together with no network.
Import with import std::http::testing.
Exports
Section titled “Exports”Types
struct Ran
Section titled “struct Ran”struct Ran<T> value: T requests: List<Request> end
What run returns: body’s value, and each request the fake served,
in order.
Ran.inspect
Section titled “Ran.inspect”impl Debug for Ran<T>
fn inspect<T>(value: Ran<T>) -> String where T: Debug
impl Debug.inspect
testing.run
Section titled “testing.run”fn run<T>(answer: (Request) -> Result<Response, Error>, body: () -> T) -> Ran<T>
Runs body with answer responding to every std::http request in it.
import std::http.{Body, Status}
import std::http::testing
ran = testing.run(fn request ->
Ok(Response{status: Status.created, body: Body.Text("${request.url}")})
end, fn ->
http.get(Url"https://example.com/a")
end)
response = ran.value!
assert response.status == Status.created
assert Response.text(response) == Ok("https://example.com/a")
assert Iter.count(ran.requests) == 1
testing.request
Section titled “testing.request”fn request(method: Method, target: String) -> Request
A request for target, a URL or a path, as a server receives one: a
path is on http://example.com, and host is the URL’s host, as the
Host header a client sends. A served request’s url is absolute too,
so a handler sees the same url and host in a test and when served.
import std::http.{Body, Request, Response} import std::http::testing r = testing.request(Method.Post, "/users?x=1") assert "${r.url}" == "http://example.com/users?x=1" assert r.host == Some("example.com") echo = fn r: Request -> Response{body: Body.Text("${r.url} ${r.host}")} agree = fn secure: Bool -> served = testing.with_server(echo, tls: secure, fn server -> Response.text(Client.get(server.client, Url.resolve_text(server.url, "/a?b=1")!)!)! end) url = String.split(served, " ") |> List.first()! tested = testing.request(Method.Get, url) (served, "${tested.url} ${tested.host}") end (plain, tested) = agree(False) assert String.starts_with(plain, "http://127.0.0.1:") assert String.contains(plain, "/a?b=1 Some(127.0.0.1:") assert plain == tested (secure, tested_secure) = agree(True) assert String.starts_with(secure, "https://127.0.0.1:") assert secure == tested_secure
Not run here: this example serves network requests, which a browser cannot do. nomi test runs it.
testing.form_request
Section titled “testing.form_request”fn form_request(method: Method, target: String, fields: List<(String, String)>) -> Request
A request that posts fields as a form, as a browser does: a
URL-encoded body holding them in order, repeated keys kept, and its
Content-Type.
import std::http.{Method, Request}
import std::http::testing
r = testing.form_request(Method.Post, "/signup", [("email", "ada@example.com")])
assert Request.form_value(r, "email") == Some("ada@example.com")
testing.chunks
Section titled “testing.chunks”fn chunks(response: Response) -> List<Bytes>
What a Body.Produce response sends, one element per flush: the
writes between two Writer.flush calls, then what is left at the end.
A test of a streamed response checks it flushes where it means to (Go’s
ResponseRecorder.Flushed). Any other body is one chunk.
import std::http.{Body, Response}
import std::http::testing
import std::io.Writer
streamed = Response{
body: Body.Produce(fn w ->
_ = Writer.write_text(w, "a")
_ = Writer.flush(w)
Writer.write_text(w, "b")
end),
}
assert testing.chunks(streamed) == [String.to_bytes("a"), String.to_bytes("b")]
testing.decompressed
Section titled “testing.decompressed”fn decompressed(response: Response) -> Result<Bytes, Error>
The body response holds before any compression: what http.compress
gzipped, unzipped, when its Content-Encoding is gzip, and any other
body as it is. A Body.Produce is read as chunks reads it.
import std::http.{self, Body, Method, Response}
import std::http::testing
page = String.repeat("hello ", 500)
app = (fn _ -> Response{body: Body.Text(page)}) |> http.compress()
r = testing.request(Method.Get, "/")
sent = app({..r, headers: Headers[("Accept-Encoding", "gzip")]})
assert Headers.get(sent.headers, "Content-Encoding") == Some("gzip")
assert testing.decompressed(sent) == Ok(String.to_bytes(page))
struct TestServer
Section titled “struct TestServer”struct TestServer url: Url client: Client certificate: Maybe<CertificateInfo> listener: Listener end
A server with_server runs for its body: where it listens, a client
that trusts it, and the certificate it serves TLS with.
TestServer.close_client_connections
Section titled “TestServer.close_client_connections”fn close_client_connections(server: TestServer) -> Unit
type function on TestServer
Closes every connection the server holds, idle or busy, so the next
request opens a new one. Go’s Server.CloseClientConnections.
TestServer.inspect
Section titled “TestServer.inspect”impl Debug for TestServer
fn inspect(value: TestServer) -> String
impl Debug.inspect
testing.with_server
Section titled “testing.with_server”fn with_server<T>(handler: Handler, tls: Bool = False, http2: Bool = False, server: Server = Server{}, body: (TestServer) -> T) -> T
Runs body while a real server listens on 127.0.0.1 with handler,
then shuts it down: Go’s httptest.NewServer. With tls, it serves
HTTPS with a certificate made for it, which TestServer.client trusts
(NewTLSServer). server configures it (NewUnstartedServer); its
address is replaced.
import std::http.{Body, Client, Response} import std::http::testing said = testing.with_server(fn _ -> Response{body: Body.Text("hi")}, fn server -> response = Client.get(server.client, server.url)! Response.text(response)! end) assert said == "hi"
Not run here: this example serves network requests, which a browser cannot do. nomi test runs it.
testing.open_websocket
Section titled “testing.open_websocket”fn open_websocket<T>(handler: Handler, target: String = "/", headers: Headers = Headers[], body: (WebSocket) -> T) -> Result<T, Response>
Sends handler a WebSocket handshake for target, with headers
added, and when it accepts, runs body with the client’s end of a
connection in memory, whose other end the handler’s function serves on
a task of its own; no socket is opened. The client’s end is closed when
body returns, and the handler’s function is waited for. A handler
that does not accept returns its response as the Err.
import std::http.{Request, Status}
import std::http::testing
import std::websocket.{self, Message, WebSocket}
shout = fn request: Request ->
websocket.accept(request, fn ws ->
case WebSocket.receive(ws)
Ok(Some(.Text(text))) ->
_ = WebSocket.send_text(ws, String.uppercase(text))
_ ->
Unit
end
end)
end
got = testing.open_websocket(shout, "/", fn ws ->
_ = WebSocket.send_text(ws, "hi")
WebSocket.receive(ws)
end)
assert Ok(received) = got
assert received == Ok(Some(Message.Text("HI")))
page = fn _: Request -> Response{body: Body.Text("not a socket")}
assert Err(response) = testing.open_websocket(page, "/", fn _ -> Unit)
assert response.status == Status.ok