mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-26 00:00:23 +02:00
[test] the form example (#3267)
This commit is contained in:
@@ -19,7 +19,7 @@ async fn main() {
|
||||
.init();
|
||||
|
||||
// build our application with some routes
|
||||
let app = Router::new().route("/", get(show_form).post(accept_form));
|
||||
let app = app();
|
||||
|
||||
// run it
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
|
||||
@@ -29,6 +29,10 @@ async fn main() {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
fn app() -> Router {
|
||||
Router::new().route("/", get(show_form).post(accept_form))
|
||||
}
|
||||
|
||||
async fn show_form() -> Html<&'static str> {
|
||||
Html(
|
||||
r#"
|
||||
@@ -62,6 +66,65 @@ struct Input {
|
||||
email: String,
|
||||
}
|
||||
|
||||
async fn accept_form(Form(input): Form<Input>) {
|
||||
async fn accept_form(Form(input): Form<Input>) -> Html<String> {
|
||||
dbg!(&input);
|
||||
Html(format!(
|
||||
"email='{}'\nname='{}'\n",
|
||||
&input.email, &input.name
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{self, Request, StatusCode},
|
||||
};
|
||||
use http_body_util::BodyExt;
|
||||
use tower::ServiceExt; // for `call`, `oneshot`, and `ready` // for `collect`
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get() {
|
||||
let app = app();
|
||||
|
||||
let response = app
|
||||
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = std::str::from_utf8(&body).unwrap();
|
||||
|
||||
assert!(body.contains(r#"<input type="submit" value="Subscribe!">"#));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_post() {
|
||||
let app = app();
|
||||
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method(http::Method::POST)
|
||||
.uri("/")
|
||||
.header(
|
||||
http::header::CONTENT_TYPE,
|
||||
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
|
||||
)
|
||||
.body(Body::from("name=foo&email=bar@axum"))
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||
let body = std::str::from_utf8(&body).unwrap();
|
||||
|
||||
assert_eq!(body, "email='bar@axum'\nname='foo'\n");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user