Skip to content

Commit

Permalink
add more tests for form data + correct snippet doc type (http_form)
Browse files Browse the repository at this point in the history
  • Loading branch information
glendc committed Apr 4, 2024
1 parent 7ab08ad commit 6ab4fdc
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 1 deletion.
2 changes: 1 addition & 1 deletion examples/http_form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
//!
//! Alternatively you can
//!
//! ```
//! ```sh
//! open http://127.0.0.1:8080
//! ```
//!
Expand Down
68 changes: 68 additions & 0 deletions src/http/service/web/endpoint/extract/body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,52 @@ mod test {
assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_form_post_form_urlencoded_missing_data_fail() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Input {
name: String,
age: u8,
}

let service = WebService::default().post("/", |Form(_): Form<Input>| async move {
panic!("should not reach here");
});

let req = http::Request::builder()
.uri("/")
.method(http::Method::POST)
.header("content-type", "application/x-www-form-urlencoded")
.body(r#"age=29"#.into())
.unwrap();
let resp = service.serve(Context::default(), req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn test_form_get_form_urlencoded_fail() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Input {
name: String,
age: u8,
}

let service = WebService::default().get("/", |Form(_): Form<Input>| async move {
panic!("should not reach here");
});

let req = http::Request::builder()
.uri("/")
.method(http::Method::GET)
.header("content-type", "application/x-www-form-urlencoded")
.body(r#"name=Devan&age=29"#.into())
.unwrap();
let resp = service.serve(Context::default(), req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn test_form_get() {
#[derive(Debug, serde::Deserialize)]
Expand All @@ -286,4 +332,26 @@ mod test {
let resp = service.serve(Context::default(), req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}

#[tokio::test]
async fn test_form_get_fail_missing_data() {
#[derive(Debug, serde::Deserialize)]
#[allow(dead_code)]
struct Input {
name: String,
age: u8,
}

let service = WebService::default().get("/", |Form(_): Form<Input>| async move {
panic!("should not reach here");
});

let req = http::Request::builder()
.uri("/?name=Devan")
.method(http::Method::GET)
.body(http::Body::empty())
.unwrap();
let resp = service.serve(Context::default(), req).await.unwrap();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
}

0 comments on commit 6ab4fdc

Please sign in to comment.