From c19313790547c7b7a3ea42d0a16b9fcfec208f05 Mon Sep 17 00:00:00 2001 From: Leland Jansen Date: Wed, 28 Aug 2019 08:32:17 -0700 Subject: [PATCH] actix_web::test::TestRequest::set_form (#1058) --- CHANGES.md | 3 +++ src/test.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/CHANGES.md b/CHANGES.md index 19232346..aeb270b9 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -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. diff --git a/src/test.rs b/src/test.rs index 562fdf43..903679ca 100644 --- a/src/test.rs +++ b/src/test.rs @@ -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(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(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| { + 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(