From be3212fb7c5a4b7a9f595f51f821c79cbda9df3a Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Fri, 9 Dec 2022 09:00:12 +0100 Subject: [PATCH] warp-server: Add unit test for /hello route Split out the API into a separate function, to make it accessible for unit tests. --- warp-server/src/main.rs | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) 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!"); + } +} -- 2.39.2