Skip to content

Commit ac7732a

Browse files
authored
[test] the anyhow-error-response example (#3274)
1 parent 6fa7cce commit ac7732a

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed

Cargo.lock

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/anyhow-error-response/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,7 @@ publish = false
88
anyhow = "1.0"
99
axum = { path = "../../axum" }
1010
tokio = { version = "1.0", features = ["full"] }
11+
12+
[dev-dependencies]
13+
http-body-util = "0.1.0"
14+
tower = { version = "0.5.2", features = ["util"] }

examples/anyhow-error-response/src/main.rs

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use axum::{
1313

1414
#[tokio::main]
1515
async fn main() {
16-
let app = Router::new().route("/", get(handler));
16+
let app = app();
1717

1818
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
1919
.await
@@ -45,6 +45,10 @@ impl IntoResponse for AppError {
4545
}
4646
}
4747

48+
fn app() -> Router {
49+
Router::new().route("/", get(handler))
50+
}
51+
4852
// This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into
4953
// `Result<_, AppError>`. That way you don't need to do that manually.
5054
impl<E> From<E> for AppError
@@ -55,3 +59,26 @@ where
5559
Self(err.into())
5660
}
5761
}
62+
63+
#[cfg(test)]
64+
mod tests {
65+
use super::*;
66+
use axum::{body::Body, http::Request, http::StatusCode};
67+
use http_body_util::BodyExt;
68+
use tower::ServiceExt;
69+
70+
#[tokio::test]
71+
async fn test_main_page() {
72+
let response = app()
73+
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
74+
.await
75+
.unwrap();
76+
77+
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
78+
let body = response.into_body();
79+
let bytes = body.collect().await.unwrap().to_bytes();
80+
let html = String::from_utf8(bytes.to_vec()).unwrap();
81+
82+
assert_eq!(html, "Something went wrong: it failed!");
83+
}
84+
}

0 commit comments

Comments
 (0)