Testing and Mixing with Rust Code
In Process
wisp::prepare::<App>().await?;
let mut req = wisp::Request::new("GET", "/posts?page=2");
req.header("accept", "text/html");
let reply = wisp::handle::<App>(req).await; // reply.status, .headers (Vec<(name, value)>), .body (wisp::Body)
Same parser, limits, hooks and CSRF check as the server.
Your Own Listener
wisp::serve_on::<App>(listener) serves on a std::net::TcpListener you bound (port 0, a socket systemd handed over, or one shared with another server). It runs init first. It errs if that fails, if the socket is unusable, or when the OS cannot start the clock thread (cannot start the clock thread: {e}). It runs until you drop its future. wisp::serve::<App>(addr) binds for you. Both need your own tokio runtime and wisp::app!(); in place of wisp::main!();:
wisp::app!();
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = std::net::TcpListener::bind("127.0.0.1:0")?;
wisp::serve_on::<App>(listener).await
}
Testing an App
Smaller tests (one component, a Cx by hand, a mocked API call), coverage and Playwright are on the Testing page. wisp::test::client needs no port and keeps cookies:
// tests/app.rs
wisp::app!();
#[test]
fn counter() {
let mut app = wisp::test::client::<App>();
assert!(app.get("/").text().contains("Clicked 0 times"));
app.post_form("/?/increment", &[]);
assert!(app.get("/").text().contains("Clicked 1 times"));
assert!(app.cookie("user").is_none());
}
| Method | What it does |
|---|---|
get(path) | GET |
post_form(target, &[(name, value)]) | form POST with a browser's Host, Origin (the app's ORIGIN, else http://localhost) and Sec-Fetch-Site: same-origin |
header(name, value) | a header for the next request ("" leaves one out) |
send(req) | any request |
next_chunk(&mut reply) | next chunk of a stream |
cookie(name) | a stored cookie |
websocket(target) | a TestSocket over the upgrade of a Response::websocket route, with the client's cookies (send, recv, close). It panics when the route does not upgrade |
More in OpenAPI and tests and wisp-ref/api.md. In process, get or send on a Response::websocket route gets a 501. Use websocket(target) to test the socket.
WebSockets
A +server.rs upgrades with Response::websocket. The connection closes when the handler returns.
// src/routes/ws/+server.rs
fn get() -> Response {
Response::websocket(|ws| async move {
while let Some(msg) = ws.recv().await {
ws.send(msg).await?; // a String is text, a Vec<u8> binary
}
Ok(())
})
}
ws.recv()is the nextwisp::Message(TextorBinary, withmsg.text()andmsg.bytes()), orNoneonce the client or server is gone. The server answers pings and joins fragments.ws.send(msg)fails once the connection closes.recvandsendcan overlap (tokio::select!, orwisp::spawna sender withws.clone()). Dropping asendorrecvafter it wrote part of a frame ends the socket. A close ends arecvthat another clone of the socket waits in, on the built-in server and on the edge build.- While
recvwaits, the server pings a quiet client after half ofWISP_WS_IDLE. It closes the socket (1001) after all of it.WISP_WS_IDLEis 60 s by default (0means never). A send-only handler has no timeout. A message sent in pieces must make progress every 10 s and come whole at 1 KB/s after that. Else the socket closes with 1008, whateverWISP_WS_IDLEis. - A message over the route's
BODY_LIMIT(1 MB default) closes the connection with 1009. - On the edge build the socket holds what the handler did not read: twice the message limit plus 64 KiB. A client that sends more gets a close with 1009 (4009 on Deno). A handler that only sends gets this close in place of its next send, and that send fails.
- After its close frame, the built-in server reads what the client still sends and keeps none of it. It reads for 2 s and 1 MiB at most. Then it closes the connection.
- A cross-site page gets 403 (
Originmust name the host, orORIGIN). A request that does not upgrade gets 426.beforeruns first. - The built-in server and each host that can hold a socket upgrade (deploy targets).
toweranswers 501. The build for Vercel and Netlify fails on a WebSocket route. The test client answers 501 too, except towebsocket(target).
The tower Feature
Wisp becomes a tower::Service. The feature adds bytes, http, http-body and tower-service. Without it, the runtime needs Wisp's own wisp-web-macros and wisp-web-shared, then httparse and tokio, and libc on Linux.
wisp = { git = "https://wisp.ar0.eu/", features = ["tower"] }
let wisp = wisp::tower::service::<App>().await?; // Service<http::Request<B>>
axum answers its own routes and Wisp the rest (examples/axum):
wisp::app!();
#[tokio::main]
async fn main() -> std::io::Result<()> {
let listener = tokio::net::TcpListener::bind(wisp::address()).await?;
let wisp = wisp::tower::service::<App>().await?;
let app = axum::Router::new()
.route("/api/hello", axum::routing::get(|| async { "hello from axum" }))
.fallback_service(wisp);
axum::serve(listener, app).await
}
Wrap it in a tower::ServiceBuilder for middleware such as tower_http::compression::CompressionLayer.
hyper:
let svc = hyper_util::service::TowerToHyperService::new(wisp::tower::service::<App>().await?);
hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
.serve_connection(hyper_util::rt::TokioIo::new(stream), svc)
.await?;
Lambda with a main of your own (--target lambda needs no code). Put WISP_SECRET in the function's environment:
wisp::app!();
#[tokio::main]
async fn main() -> Result<(), lambda_http::Error> {
lambda_http::run(wisp::tower::service::<App>().await?).await
}
Axum Inside Wisp
Send paths to an axum Router from before (or a catch-all +server.rs). Some answers instead of the route. async fn before takes every route off the no-wait fast path.
// src/hooks.rs
async fn before(cx: &mut Cx) -> Result<Option<Response>> {
if cx.path().starts_with("/api") {
let mut api = api_router(); // an axum::Router
return Ok(Some(wisp::tower::call(&mut api, cx).await?));
}
Ok(None)
}
Is This Page Useful?