From ac7732abd391648f3409d57ee61c6c561df9edcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?G=C3=A1bor=20Szab=C3=B3?= Date: Tue, 18 Mar 2025 11:53:00 +0200 Subject: [PATCH] [test] the anyhow-error-response example (#3274) --- Cargo.lock | 2 ++ examples/anyhow-error-response/Cargo.toml | 4 +++ examples/anyhow-error-response/src/main.rs | 29 +++++++++++++++++++++- 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index ad8a8e8d..005b77f9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1329,7 +1329,9 @@ version = "0.1.0" dependencies = [ "anyhow", "axum", + "http-body-util", "tokio", + "tower 0.5.2", ] [[package]] diff --git a/examples/anyhow-error-response/Cargo.toml b/examples/anyhow-error-response/Cargo.toml index 0c2beb50..6aa80e1e 100644 --- a/examples/anyhow-error-response/Cargo.toml +++ b/examples/anyhow-error-response/Cargo.toml @@ -8,3 +8,7 @@ publish = false anyhow = "1.0" axum = { path = "../../axum" } tokio = { version = "1.0", features = ["full"] } + +[dev-dependencies] +http-body-util = "0.1.0" +tower = { version = "0.5.2", features = ["util"] } diff --git a/examples/anyhow-error-response/src/main.rs b/examples/anyhow-error-response/src/main.rs index b7a2416a..fdc32d92 100644 --- a/examples/anyhow-error-response/src/main.rs +++ b/examples/anyhow-error-response/src/main.rs @@ -13,7 +13,7 @@ use axum::{ #[tokio::main] async fn main() { - let app = Router::new().route("/", get(handler)); + let app = app(); let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await @@ -45,6 +45,10 @@ impl IntoResponse for AppError { } } +fn app() -> Router { + Router::new().route("/", get(handler)) +} + // This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into // `Result<_, AppError>`. That way you don't need to do that manually. impl From for AppError @@ -55,3 +59,26 @@ where Self(err.into()) } } + +#[cfg(test)] +mod tests { + use super::*; + use axum::{body::Body, http::Request, http::StatusCode}; + use http_body_util::BodyExt; + use tower::ServiceExt; + + #[tokio::test] + async fn test_main_page() { + let response = app() + .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) + .await + .unwrap(); + + assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); + let body = response.into_body(); + let bytes = body.collect().await.unwrap().to_bytes(); + let html = String::from_utf8(bytes.to_vec()).unwrap(); + + assert_eq!(html, "Something went wrong: it failed!"); + } +}