nitr_http/testing/
request.rs1use std::net::SocketAddr;
10use std::time::Duration;
11
12use base64::Engine as _;
13use hyper::body::Bytes;
14use mlua::{Table, Value};
15
16#[derive(Debug, Clone, Default)]
19pub struct TestRequest {
20 pub method: String,
22 pub path: String,
24 pub headers: Vec<(String, String)>,
26 pub body: Option<Bytes>,
28 pub remote_addr: Option<SocketAddr>,
30 pub timeout: Option<Duration>,
32}
33
34const BODY_OPTIONS: &[&str] = &["body", "json", "form", "multipart"];
37
38fn refuse(message: String) -> mlua::Error {
39 mlua::Error::RuntimeError(message)
40}
41
42fn scalar_text(key: &str, value: Value) -> mlua::Result<String> {
45 Ok(match value {
46 Value::String(s) => s.to_string_lossy().to_string(),
47 Value::Integer(i) => i.to_string(),
48 Value::Number(n) => n.to_string(),
49 Value::Boolean(b) => b.to_string(),
50 other => {
51 return Err(refuse(format!(
52 "`{key}` values must be strings, numbers or booleans, got {}",
53 other.type_name()
54 )));
55 }
56 })
57}
58
59fn pairs(option: &str, table: &Table) -> mlua::Result<Vec<(String, String)>> {
63 let mut out = Vec::new();
64 for pair in table.pairs::<String, Value>() {
65 let (key, value) = pair?;
66 match value {
67 Value::Table(list) => {
68 for item in list.sequence_values::<Value>() {
69 out.push((key.clone(), scalar_text(option, item?)?));
70 }
71 }
72 other => out.push((key, scalar_text(option, other)?)),
73 }
74 }
75 out.sort_by(|a, b| a.0.cmp(&b.0));
77 Ok(out)
78}
79
80impl TestRequest {
81 pub fn from_lua(method: &str, path: &str, opts: Option<&Table>) -> mlua::Result<Self> {
91 let mut req = TestRequest {
92 method: method.to_string(),
93 path: path.to_string(),
94 ..Default::default()
95 };
96 let Some(opts) = opts else {
97 return Ok(req);
98 };
99
100 if let Some(headers) = opts.get::<Option<Table>>("headers")? {
101 for (name, value) in pairs("headers", &headers)? {
102 req.headers.push((name.to_ascii_lowercase(), value));
103 }
104 }
105 let has_header = |req: &TestRequest, name: &str| {
106 req.headers
107 .iter()
108 .any(|(k, _)| k.eq_ignore_ascii_case(name))
109 };
110
111 if let Some(query) = opts.get::<Option<Table>>("query")? {
112 let mut encoder = url::form_urlencoded::Serializer::new(String::new());
113 for (key, value) in pairs("query", &query)? {
114 encoder.append_pair(&key, &value);
115 }
116 let encoded = encoder.finish();
117 if !encoded.is_empty() {
118 let joiner = if req.path.contains('?') { '&' } else { '?' };
119 req.path = format!("{}{joiner}{encoded}", req.path);
120 }
121 }
122
123 if let Some(cookies) = opts.get::<Option<Table>>("cookies")? {
124 let line = pairs("cookies", &cookies)?
125 .into_iter()
126 .map(|(name, value)| format!("{name}={value}"))
127 .collect::<Vec<_>>()
128 .join("; ");
129 if !line.is_empty() {
130 req.headers.push(("cookie".into(), line));
131 }
132 }
133
134 if let Some(auth) = opts.get::<Option<Table>>("auth")? {
135 if has_header(&req, "authorization") {
136 return Err(refuse(
137 "`auth` and an `authorization` header both given; a request carries one \
138 credential"
139 .into(),
140 ));
141 }
142 let value = if let Some(token) = auth.get::<Option<String>>("bearer")? {
143 format!("Bearer {token}")
144 } else if let Some(basic) = auth.get::<Option<Table>>("basic")? {
145 let user: String = basic.get(1)?;
146 let pass: String = basic.get(2)?;
147 format!(
148 "Basic {}",
149 base64::engine::general_purpose::STANDARD.encode(format!("{user}:{pass}"))
150 )
151 } else {
152 return Err(refuse(
153 "`auth` takes { bearer = token } or { basic = { user, password } }".into(),
154 ));
155 };
156 req.headers.push(("authorization".into(), value));
157 }
158
159 let given: Vec<&str> = BODY_OPTIONS
160 .iter()
161 .copied()
162 .filter(|key| opts.contains_key(*key).unwrap_or(false))
163 .collect();
164 if let [first, second, ..] = given.as_slice() {
165 return Err(refuse(format!(
166 "`{first}` and `{second}` both given; a request has one body"
167 )));
168 }
169 let content_type = match given.first().copied() {
170 Some("body") => {
171 let raw: mlua::LuaString = opts.get("body")?;
172 req.body = Some(Bytes::copy_from_slice(&raw.as_bytes()));
173 None
174 }
175 Some("json") => {
176 let value: Value = opts.get("json")?;
177 req.body = Some(Bytes::from(nitr_std::json_encode(&value)?));
178 Some("application/json".to_string())
179 }
180 Some("form") => {
181 let form: Table = opts.get("form")?;
182 let mut encoder = url::form_urlencoded::Serializer::new(String::new());
183 for (key, value) in pairs("form", &form)? {
184 encoder.append_pair(&key, &value);
185 }
186 req.body = Some(Bytes::from(encoder.finish()));
187 Some("application/x-www-form-urlencoded".to_string())
188 }
189 Some("multipart") => {
190 let parts: Table = opts.get("multipart")?;
191 let (content_type, body) = multipart_body(&parts)?;
192 req.body = Some(Bytes::from(body));
193 Some(content_type)
194 }
195 _ => None,
196 };
197 if let Some(content_type) = content_type
200 && !has_header(&req, "content-type")
201 {
202 req.headers.push(("content-type".into(), content_type));
203 }
204
205 if let Some(addr) = opts.get::<Option<String>>("remote_addr")? {
206 req.remote_addr = Some(super::parse_peer(&addr).ok_or_else(|| {
207 refuse(format!(
208 "`remote_addr` must be an IP address or ip:port, got {addr:?}"
209 ))
210 })?);
211 }
212 if let Some(secs) = opts.get::<Option<f64>>("timeout")? {
213 req.timeout = Some(super::seconds("timeout", secs)?);
214 }
215 Ok(req)
216 }
217}
218
219fn multipart_body(parts: &Table) -> mlua::Result<(String, Vec<u8>)> {
224 let boundary = format!("----nitr-test-{}", uuid::Uuid::now_v7().simple());
225 let mut body = Vec::new();
226 let mut entries: Vec<(String, Value)> = Vec::new();
227 for pair in parts.pairs::<String, Value>() {
228 entries.push(pair?);
229 }
230 entries.sort_by(|a, b| a.0.cmp(&b.0));
231 for (name, value) in entries {
232 body.extend_from_slice(format!("--{boundary}\r\n").as_bytes());
233 match value {
234 Value::Table(file) => {
235 let filename: String = file.get::<Option<String>>("filename")?.unwrap_or_default();
236 let content_type: Option<String> = file.get("content_type")?;
237 let data: mlua::LuaString = file.get("data")?;
238 body.extend_from_slice(
239 format!(
240 "Content-Disposition: form-data; name=\"{name}\"; filename=\"{filename}\"\r\n"
241 )
242 .as_bytes(),
243 );
244 if let Some(ct) = content_type {
245 body.extend_from_slice(format!("Content-Type: {ct}\r\n").as_bytes());
246 }
247 body.extend_from_slice(b"\r\n");
248 body.extend_from_slice(&data.as_bytes());
249 }
250 other => {
251 body.extend_from_slice(
252 format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n").as_bytes(),
253 );
254 body.extend_from_slice(scalar_text("multipart", other)?.as_bytes());
255 }
256 }
257 body.extend_from_slice(b"\r\n");
258 }
259 body.extend_from_slice(format!("--{boundary}--\r\n").as_bytes());
260 Ok((format!("multipart/form-data; boundary={boundary}"), body))
261}