From: Martin Pitt Date: Fri, 9 Dec 2022 08:00:12 +0000 (+0100) Subject: warp-server: Add unit test for /hello route X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=be3212fb7c5a;p=learn-rust.git warp-server: Add unit test for /hello route Split out the API into a separate function, to make it accessible for unit tests. --- diff --git a/warp-server/src/main.rs b/warp-server/src/main.rs index 0664684..7aa6f97 100644 --- a/warp-server/src/main.rs +++ b/warp-server/src/main.rs @@ -58,10 +58,7 @@ async fn ws_rev_connected(websocket: warp::ws::WebSocket) { }); } -#[tokio::main] -async fn main() { - env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); - +pub fn api() -> impl Filter + Clone { let hello = warp::path!("hello" / String) .and(warp::header::("user-agent")) .and_then(hello); @@ -74,12 +71,31 @@ async fn main() { .and(warp::ws()) .map(|ws: warp::ws::Ws| { ws.on_upgrade(ws_rev_connected) }); - let api = hello + hello .or(ws_echo) .or(ws_rev) - .with(warp::log("warp-server")); + .with(warp::log("warp-server")) +} - warp::serve(api) +#[tokio::main] +async fn main() { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + + warp::serve(api()) .run(([127, 0, 0, 1], 3030)) .await; } + +#[cfg(test)] +mod tests { + #[tokio::test] + async fn test_hello() { + let res = warp::test::request() + .path("/hello/rust") + .header("user-agent", "TestBrowser 0.1") + .reply(&super::api()) + .await; + assert_eq!(res.status(), 200); + assert_eq!(res.body(), "Hello, rust from TestBrowser 0.1!"); + } +}