[test] the anyhow-error-response example (#3274)

This commit is contained in:
Gábor Szabó 2025-03-18 11:53:00 +02:00 committed by GitHub
parent 6fa7cce19d
commit ac7732abd3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 34 additions and 1 deletions

2
Cargo.lock generated
View File

@ -1329,7 +1329,9 @@ version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"http-body-util",
"tokio",
"tower 0.5.2",
]
[[package]]

View File

@ -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"] }

View File

@ -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<E> From<E> 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!");
}
}