Skip to content

Commit 1876b15

Browse files
committed
handle body encoded as form
1 parent 443a585 commit 1876b15

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ async-trait = "0.1"
3333
once_cell = "1"
3434
assert-json-diff = "2.0.1"
3535
base64 = "0.21.0"
36+
serde_urlencoded = "0.7.1"
3637

3738
[dev-dependencies]
3839
async-std = { version = "1.9.0", features = ["attributes"] }

src/request.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ impl Request {
5353
serde_json::from_slice(&self.body)
5454
}
5555

56+
pub fn body_form<T: DeserializeOwned>(&self) -> Result<T, serde_urlencoded::de::Error> {
57+
serde_urlencoded::from_bytes(&self.body)
58+
}
59+
5660
pub async fn from(mut request: http_types::Request) -> Request {
5761
let method = request.method();
5862
let url = request.url().to_owned();

tests/request.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use std::{
2+
collections::HashMap,
3+
sync::{Arc, RwLock},
4+
};
5+
6+
use http_types::mime;
7+
use wiremock::{matchers::any, Mock, MockServer, Request, ResponseTemplate};
8+
9+
#[async_std::test]
10+
async fn reuqest_form_data_body() {
11+
// Arrange
12+
let form_data: Arc<RwLock<HashMap<String, String>>> = Arc::new(RwLock::new(HashMap::new()));
13+
let mock_server = MockServer::start().await;
14+
let form_data_clone = form_data.clone();
15+
Mock::given(any())
16+
.respond_with(move |request: &Request| {
17+
let form_data = request.body_form::<HashMap<String, String>>().unwrap();
18+
*form_data_clone.write().unwrap() = form_data;
19+
ResponseTemplate::new(200)
20+
})
21+
.mount(&mock_server)
22+
.await;
23+
24+
// Act
25+
let _ = surf::post(&mock_server.uri())
26+
.content_type(mime::FORM)
27+
.body_string(r#"foo=bar&foo2="h%25l""#.to_string())
28+
.await
29+
.unwrap()
30+
.status();
31+
32+
// Assert
33+
let result = form_data.read().unwrap().clone();
34+
let expected = HashMap::from([
35+
("foo".to_string(), "bar".to_string()),
36+
("foo2".to_string(), "\"h%l\"".to_string()),
37+
]);
38+
assert_eq!(result, expected);
39+
}

0 commit comments

Comments
 (0)