|
| 1 | +use http_types::{url::Url, Method}; |
| 2 | +use serde::Deserialize; |
| 3 | + |
| 4 | +#[derive(Deserialize)] |
| 5 | +struct Params { |
| 6 | + msg: String, |
| 7 | +} |
| 8 | + |
| 9 | +#[derive(Deserialize)] |
| 10 | +struct OptionalParams { |
| 11 | + _msg: Option<String>, |
| 12 | + _time: Option<u64>, |
| 13 | +} |
| 14 | + |
| 15 | +#[test] |
| 16 | +fn successfully_deserialize_query() { |
| 17 | + let req = http_types::Request::new( |
| 18 | + Method::Get, |
| 19 | + Url::parse("http://example.com/?msg=Hello").unwrap(), |
| 20 | + ); |
| 21 | + |
| 22 | + let params = req.query::<Params>(); |
| 23 | + assert!(params.is_ok()); |
| 24 | + assert_eq!(params.unwrap().msg, "Hello"); |
| 25 | +} |
| 26 | + |
| 27 | +#[test] |
| 28 | +fn unsuccessfully_deserialize_query() { |
| 29 | + let req = http_types::Request::new(Method::Get, Url::parse("http://example.com/").unwrap()); |
| 30 | + |
| 31 | + let params = req.query::<Params>(); |
| 32 | + assert!(params.is_err()); |
| 33 | + assert_eq!(params.err().unwrap().to_string(), "invalid data"); |
| 34 | +} |
| 35 | + |
| 36 | +#[test] |
| 37 | +fn malformatted_query() { |
| 38 | + let req = http_types::Request::new( |
| 39 | + Method::Get, |
| 40 | + Url::parse("http://example.com/?error=should_fail").unwrap(), |
| 41 | + ); |
| 42 | + |
| 43 | + let params = req.query::<Params>(); |
| 44 | + assert!(params.is_err()); |
| 45 | + assert_eq!(params.err().unwrap().to_string(), "missing field `msg`"); |
| 46 | +} |
| 47 | + |
| 48 | +#[test] |
| 49 | +fn empty_query_string_for_struct_with_no_required_fields() { |
| 50 | + let req = http_types::Request::new(Method::Get, Url::parse("http://example.com").unwrap()); |
| 51 | + |
| 52 | + let params = req.query::<OptionalParams>(); |
| 53 | + assert!(params.is_ok()); |
| 54 | +} |
0 commit comments