1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use std::collections::HashMap;
use http::{header, header::HeaderName, Extensions, HeaderMap, HeaderValue, Method};
use serde::Serialize;
use serde_json::Value;
use crate::{
test::{TestClient, TestForm, TestResponse},
Body, Endpoint, Request,
};
pub struct TestRequestBuilder<'a, E> {
cli: &'a TestClient<E>,
uri: String,
method: Method,
query: HashMap<String, Value>,
headers: HeaderMap,
body: Body,
extensions: Extensions,
}
impl<'a, E> TestRequestBuilder<'a, E>
where
E: Endpoint,
{
pub(crate) fn new(cli: &'a TestClient<E>, method: Method, uri: String) -> Self {
Self {
cli,
uri,
method,
query: Default::default(),
headers: Default::default(),
body: Body::empty(),
extensions: Default::default(),
}
}
#[must_use]
pub fn query(mut self, name: impl Into<String>, value: &impl Serialize) -> Self {
if let Ok(value) = serde_json::to_value(value) {
self.query.insert(name.into(), value);
}
self
}
#[must_use]
pub fn header<K, V>(mut self, key: K, value: V) -> Self
where
K: TryInto<HeaderName>,
V: TryInto<HeaderValue>,
{
let key = key.try_into().map_err(|_| ()).expect("valid header name");
let value = value
.try_into()
.map_err(|_| ())
.expect("valid header value");
self.headers.append(key, value);
self
}
#[must_use]
pub fn content_type(self, content_type: impl AsRef<str>) -> Self {
self.header(header::CONTENT_TYPE, content_type.as_ref())
}
#[must_use]
pub fn body(self, body: impl Into<Body>) -> Self {
Self {
body: body.into(),
..self
}
}
#[must_use]
pub fn body_json(self, body: &impl Serialize) -> Self {
Self {
body: serde_json::to_string(&body).expect("valid json").into(),
..self
}
}
#[must_use]
pub fn multipart(self, form: TestForm) -> Self {
self.content_type(format!("multipart/form-data; boundary={}", form.boundary()))
.body(Body::from_async_read(form.into_async_read()))
}
fn make_request(self) -> Request {
let uri = if self.query.is_empty() {
self.uri
} else {
format!(
"{}?{}",
self.uri,
serde_urlencoded::to_string(&self.query).unwrap()
)
};
let mut req = Request::builder()
.method(self.method)
.uri(uri.parse().expect("valid uri"))
.finish();
req.headers_mut().extend(self.cli.default_headers.clone());
req.headers_mut().extend(self.headers);
*req.extensions_mut() = self.extensions;
req.set_body(self.body);
req
}
#[must_use]
pub fn data<T>(mut self, data: T) -> Self
where
T: Send + Sync + 'static,
{
self.extensions.insert(data);
self
}
pub async fn send(self) -> TestResponse {
let ep = &self.cli.ep;
let req = self.make_request();
let resp = ep.get_response(req).await;
TestResponse::new(resp)
}
}