[test] the templates example (#3269)

This commit is contained in:
Gábor Szabó 2025-03-17 14:29:27 +02:00 committed by GitHub
parent ab70773f2b
commit 517223f254
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 41 additions and 1 deletions

2
Cargo.lock generated
View File

@ -1814,7 +1814,9 @@ version = "0.1.0"
dependencies = [
"askama",
"axum",
"http-body-util",
"tokio",
"tower 0.5.2",
"tracing",
"tracing-subscriber",
]

View File

@ -10,3 +10,7 @@ axum = { path = "../../axum" }
tokio = { version = "1.0", features = ["full"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[dev-dependencies]
http-body-util = "0.1.0"
tower = { version = "0.5.2", features = ["util"] }

View File

@ -25,7 +25,7 @@ async fn main() {
.init();
// build our application with some routes
let app = Router::new().route("/greet/{name}", get(greet));
let app = app();
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
@ -35,6 +35,10 @@ async fn main() {
axum::serve(listener, app).await.unwrap();
}
fn app() -> Router {
Router::new().route("/greet/{name}", get(greet))
}
async fn greet(extract::Path(name): extract::Path<String>) -> impl IntoResponse {
let template = HelloTemplate { name };
HtmlTemplate(template)
@ -63,3 +67,33 @@ where
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn test_main() {
let response = app()
.oneshot(
Request::builder()
.uri("/greet/Foo")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
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, "<h1>Hello, Foo!</h1>");
}
}