]> piware.de Git - learn-rust.git/commitdiff
axum-server: Add unit test for /hello route
authorMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 12:33:45 +0000 (13:33 +0100)
committerMartin Pitt <martin@piware.de>
Fri, 9 Dec 2022 12:33:45 +0000 (13:33 +0100)
Similar to what commit be3212fb7c5a did for warp-server. Split out the
whole app router into a separate app() function, to make it accessible
to unit testing.

axum-server/Cargo.toml
axum-server/src/main.rs

index 0444b3957dc6e24aeb62b2cb344a5a2bd58c771f..9033d1864fd0b125e1cfc6d79e9fea2b7224a0c4 100644 (file)
@@ -7,6 +7,7 @@ edition = "2021"
 
 [dependencies]
 axum = { version = "0.5", features = ["ws", "headers"] }
+hyper = { version = "0.14" }
 tokio = { version = "1", features = ["full"] }
 tower = "0.4"
 tower-http = { version = "0.3", features = ["trace", "fs"] }
index 2a2eaaab2f63339bbd80235ecf29337af63503e6..7bb1e94fc0cc41f990ec4646eb22d6fd4c26c366 100644 (file)
@@ -42,10 +42,8 @@ async fn ws_echo(mut socket: ws::WebSocket) {
     }
 }
 
-#[tokio::main]
-async fn main() {
-    tracing_subscriber::fmt::init();
-    let app = Router::new()
+fn app() -> Router {
+    Router::new()
         .route("/hello/:name", get(hello))
         .nest("/dir",
                get_service(tower_http::services::ServeDir::new("../static").precompressed_gzip())
@@ -60,12 +58,52 @@ async fn main() {
                     tower_http::trace::TraceLayer::new_for_http()
                          .make_span_with(tower_http::trace::DefaultMakeSpan::default().include_headers(true)),
                 )
-        );
+        )
+}
+
+#[tokio::main]
+async fn main() {
+    tracing_subscriber::fmt::init();
 
     let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3030));
     tracing::info!("listening on {}", addr);
     axum::Server::bind(&addr)
-        .serve(app.into_make_service())
+        .serve(app().into_make_service())
         .await
         .unwrap();
 }
+
+#[cfg(test)]
+mod tests {
+    use axum::{
+        http::{Request, StatusCode},
+        response::Response,
+        body::Body
+    };
+    use tower::ServiceExt; // for `oneshot`
+
+    async fn assert_res_ok_body(res: Response, expected_body: &[u8]) {
+        assert_eq!(res.status(), StatusCode::OK);
+        assert_eq!(hyper::body::to_bytes(res.into_body()).await.unwrap(), expected_body);
+    }
+
+    #[tokio::test]
+    async fn test_hello() {
+        // no user-agent
+        let res = super::app()
+            .oneshot(Request::builder().uri("/hello/rust").body(Body::empty()).unwrap())
+            .await
+            .unwrap();
+        assert_res_ok_body(res, b"Hello rust").await;
+
+        // with user-agent
+        let res = super::app()
+            .oneshot(Request::builder()
+                        .uri("/hello/rust")
+                        .header("user-agent", "TestBrowser 0.1")
+                        .body(Body::empty()).unwrap())
+            .await
+            .unwrap();
+        assert_res_ok_body(res, b"Hello rust from TestBrowser 0.1").await;
+    }
+}