1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 07:53:00 +01:00

actix_web::test::TestRequest::set_form (#1058)

This commit is contained in:
Leland Jansen 2019-08-28 08:32:17 -07:00 committed by Nikolay Kim
parent a07cdd6533
commit c193137905
2 changed files with 38 additions and 0 deletions

View File

@ -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.

View File

@ -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 {
@ -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(