Skip to content
Myr

main.rs

This file

Path

examples/testing/src/main.rs

191 lines · 5.9 KiB · Rust

Last changed by

examples: Simplify Request and Response construction (#3653)tottotobefore adoption3f8956d

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo test -p example-testing5//! ```67use std::net::SocketAddr;89use axum::{10    extract::ConnectInfo,11    routing::{get, post},12    Json, Router,13};14use tower_http::trace::TraceLayer;15use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1617#[tokio::main]18async fn main() {19    tracing_subscriber::registry()20        .with(21            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {22                format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()23            }),24        )25        .with(tracing_subscriber::fmt::layer())26        .init();2728    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")29        .await30        .unwrap();31    tracing::debug!("listening on {}", listener.local_addr().unwrap());32    axum::serve(listener, app()).await;33}3435/// Having a function that produces our app makes it easy to call it from tests36/// without having to create an HTTP server.37fn app() -> Router {38    Router::new()39        .route("/", get(|| async { "Hello, World!" }))40        .route(41            "/json",42            post(|payload: Json<serde_json::Value>| async move {43                Json(serde_json::json!({ "data": payload.0 }))44            }),45        )46        .route(47            "/requires-connect-info",48            get(|ConnectInfo(addr): ConnectInfo<SocketAddr>| async move { format!("Hi {addr}") }),49        )50        // We can still add middleware51        .layer(TraceLayer::new_for_http())52}5354#[cfg(test)]55mod tests {56    use super::*;57    use axum::{58        body::Body,59        extract::connect_info::MockConnectInfo,60        http::{self, Request, StatusCode},61    };62    use http_body_util::BodyExt; // for `collect`63    use serde_json::{json, Value};64    use tokio::net::TcpListener;65    use tower::{Service, ServiceExt}; // for `call`, `oneshot`, and `ready`6667    #[tokio::test]68    async fn hello_world() {69        let app = app();7071        // `Router` implements `tower::Service<Request<Body>>` so we can72        // call it like any tower service, no need to run an HTTP server.73        let response = app74            .oneshot(Request::get("/").body(Body::empty()).unwrap())75            .await76            .unwrap();7778        assert_eq!(response.status(), StatusCode::OK);7980        let body = response.into_body().collect().await.unwrap().to_bytes();81        assert_eq!(&body[..], b"Hello, World!");82    }8384    #[tokio::test]85    async fn json() {86        let app = app();8788        let response = app89            .oneshot(90                Request::post("/json")91                    .header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())92                    .body(Body::from(93                        serde_json::to_vec(&json!([1, 2, 3, 4])).unwrap(),94                    ))95                    .unwrap(),96            )97            .await98            .unwrap();99100        assert_eq!(response.status(), StatusCode::OK);101102        let body = response.into_body().collect().await.unwrap().to_bytes();103        let body: Value = serde_json::from_slice(&body).unwrap();104        assert_eq!(body, json!({ "data": [1, 2, 3, 4] }));105    }106107    #[tokio::test]108    async fn not_found() {109        let app = app();110111        let response = app112            .oneshot(Request::get("/does-not-exist").body(Body::empty()).unwrap())113            .await114            .unwrap();115116        assert_eq!(response.status(), StatusCode::NOT_FOUND);117        let body = response.into_body().collect().await.unwrap().to_bytes();118        assert!(body.is_empty());119    }120121    // You can also spawn a server and talk to it like any other HTTP server:122    #[tokio::test]123    async fn the_real_deal() {124        let listener = TcpListener::bind("0.0.0.0:0").await.unwrap();125        let addr = listener.local_addr().unwrap();126127        tokio::spawn(async move {128            axum::serve(listener, app()).await;129        });130131        let client =132            hyper_util::client::legacy::Client::builder(hyper_util::rt::TokioExecutor::new())133                .build_http();134135        let response = client136            .request(137                Request::get(format!("http://{addr}"))138                    .header("Host", "localhost")139                    .body(Body::empty())140                    .unwrap(),141            )142            .await143            .unwrap();144145        let body = response.into_body().collect().await.unwrap().to_bytes();146        assert_eq!(&body[..], b"Hello, World!");147    }148149    // You can use `ready()` and `call()` to avoid using `clone()`150    // in multiple request151    #[tokio::test]152    async fn multiple_request() {153        let mut app = app().into_service();154155        let request = Request::get("/").body(Body::empty()).unwrap();156        let response = ServiceExt::<Request<Body>>::ready(&mut app)157            .await158            .unwrap()159            .call(request)160            .await161            .unwrap();162        assert_eq!(response.status(), StatusCode::OK);163164        let request = Request::get("/").body(Body::empty()).unwrap();165        let response = ServiceExt::<Request<Body>>::ready(&mut app)166            .await167            .unwrap()168            .call(request)169            .await170            .unwrap();171        assert_eq!(response.status(), StatusCode::OK);172    }173174    // Here we're calling `/requires-connect-info` which requires `ConnectInfo`175    //176    // That is normally set with `Router::into_make_service_with_connect_info` but we can't easily177    // use that during tests. The solution is instead to set the `MockConnectInfo` layer during178    // tests.179    #[tokio::test]180    async fn with_into_make_service_with_connect_info() {181        let mut app = app()182            .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000))))183            .into_service();184185        let request = Request::get("/requires-connect-info")186            .body(Body::empty())187            .unwrap();188        let response = app.ready().await.unwrap().call(request).await.unwrap();189        assert_eq!(response.status(), StatusCode::OK);190    }191}