]> piware.de Git - learn-rust.git/commitdiff
warp-server: Add unit test for /hello route
authorMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 08:00:12 +0000 (09:00 +0100)
committerMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 08:05:14 +0000 (09:05 +0100)
Split out the API into a separate function, to make it accessible for
unit tests.

warp-server/src/main.rs

index 0664684196c3173d1b1a2361c0039cbf9b230001..7aa6f977d831c977800cb248818231a3b85d21fe 100644 (file)
@@ -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<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
     let hello = warp::path!("hello" / String)
         .and(warp::header::<String>("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!");
+    }
+}