Skip to content

Commit

Permalink
actix_web::test::TestRequest::set_form (actix#1058)
Browse files Browse the repository at this point in the history
  • Loading branch information
lelandjansen authored and fafhrd91 committed Aug 28, 2019
1 parent a07cdd6 commit c193137
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@

* Add `into_inner` to `Data`

* Add `test::TestRequest::set_form()` convenience method to automatically serialize data and set
the header in test requests.

### Changed

* `Query` payload made `pub`. Allows user to pattern-match the payload.
Expand Down
35 changes: 35 additions & 0 deletions src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,16 @@ impl TestRequest {
self
}

/// Serialize `data` to a URL encoded form and set it as the request payload. The `Content-Type`
/// header is set to `application/x-www-form-urlencoded`.
pub fn set_form<T: Serialize>(mut self, data: &T) -> Self {
let bytes = serde_urlencoded::to_string(data)
.expect("Failed to serialize test data as a urlencoded form");
self.req.set_payload(bytes);
self.req.set(ContentType::form_url_encoded());
self
}

/// Serialize `data` to JSON and set it as the request payload. The `Content-Type` header is
/// set to `application/json`.
pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
Expand Down Expand Up @@ -670,6 +680,31 @@ mod tests {
assert_eq!(&result.id, "12345");
}

#[test]
fn test_request_response_form() {
let mut app = init_service(App::new().service(web::resource("/people").route(
web::post().to(|person: web::Form<Person>| {
HttpResponse::Ok().json(person.into_inner())
}),
)));

let payload = Person {
id: "12345".to_string(),
name: "User name".to_string(),
};

let req = TestRequest::post()
.uri("/people")
.set_form(&payload)
.to_request();

assert_eq!(req.content_type(), "application/x-www-form-urlencoded");

let result: Person = read_response_json(&mut app, req);
assert_eq!(&result.id, "12345");
assert_eq!(&result.name, "User name");
}

#[test]
fn test_request_response_json() {
let mut app = init_service(App::new().service(web::resource("/people").route(
Expand Down

0 comments on commit c193137

Please sign in to comment.