1use std::sync::Arc;
12
13use serde::Serialize;
14use serde_json::Value;
15
16const BASE: &str = "http://test.invalid";
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum Method {
24 Get,
25 Post,
26 Put,
27 Patch,
28 Delete,
29 Options,
31}
32
33#[derive(Clone)]
35pub struct TestApp {
36 service: Arc<salvo::Service>,
37}
38
39impl TestApp {
40 pub fn new(service: salvo::Service) -> Self {
41 Self {
42 service: Arc::new(service),
43 }
44 }
45
46 pub fn get(&self, path: &str) -> TestRequest {
47 self.request(Method::Get, path)
48 }
49
50 pub fn post(&self, path: &str) -> TestRequest {
51 self.request(Method::Post, path)
52 }
53
54 pub fn put(&self, path: &str) -> TestRequest {
55 self.request(Method::Put, path)
56 }
57
58 pub fn patch(&self, path: &str) -> TestRequest {
59 self.request(Method::Patch, path)
60 }
61
62 pub fn delete(&self, path: &str) -> TestRequest {
63 self.request(Method::Delete, path)
64 }
65
66 pub fn options(&self, path: &str) -> TestRequest {
68 self.request(Method::Options, path)
69 }
70
71 fn request(&self, method: Method, path: &str) -> TestRequest {
72 TestRequest {
73 app: self.clone(),
74 method,
75 path: path.to_owned(),
76 headers: Vec::new(),
77 body: None,
78 }
79 }
80}
81
82pub struct TestRequest {
83 app: TestApp,
84 method: Method,
85 path: String,
86 headers: Vec<(String, String)>,
87 body: Option<String>,
88}
89
90impl TestRequest {
91 #[must_use]
92 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
93 self.headers.push((name.into(), value.into()));
94 self
95 }
96
97 #[must_use]
99 pub fn json(mut self, body: impl Serialize) -> Self {
100 let rendered = serde_json::to_string(&body).expect("the test body serializes");
101
102 self.body = Some(rendered);
103 self.header("content-type", "application/json")
104 }
105
106 #[must_use]
108 pub fn bearer(self, token: impl std::fmt::Display) -> Self {
109 self.header("authorization", format!("Bearer {token}"))
110 }
111
112 #[must_use]
119 pub fn acting_as(self, secret: &str, subject: impl std::fmt::Display) -> Self {
120 let token = luxid_core::Jwt::new(secret)
121 .sign(&luxid_core::Identity::new(subject.to_string()))
122 .expect("signing a test token");
123
124 self.bearer(token)
125 }
126
127 #[must_use]
129 pub fn acting_as_with(
130 self,
131 secret: &str,
132 subject: impl std::fmt::Display,
133 claims: impl IntoIterator<Item = (String, serde_json::Value)>,
134 ) -> Self {
135 let mut identity = luxid_core::Identity::new(subject.to_string());
136
137 for (name, value) in claims {
138 identity = identity.with_claim(name, value);
139 }
140
141 let token = luxid_core::Jwt::new(secret)
142 .sign(&identity)
143 .expect("signing a test token");
144
145 self.bearer(token)
146 }
147
148 #[must_use]
150 pub fn with_session(self, cookie: impl std::fmt::Display) -> Self {
151 self.header("cookie", format!("luxid_session={cookie}"))
152 }
153
154 pub async fn send(self) -> TestResponse {
155 let url = format!("{BASE}{}", self.path);
156
157 let mut builder = match self.method {
158 Method::Get => salvo::test::TestClient::get(url),
159 Method::Post => salvo::test::TestClient::post(url),
160 Method::Put => salvo::test::TestClient::put(url),
161 Method::Patch => salvo::test::TestClient::patch(url),
162 Method::Delete => salvo::test::TestClient::delete(url),
163 Method::Options => salvo::test::TestClient::options(url),
164 };
165
166 for (name, value) in self.headers {
167 let name = salvo::http::HeaderName::try_from(name.as_str())
170 .unwrap_or_else(|_| panic!("`{name}` is not a valid header name"));
171
172 builder = builder.add_header(name, value, true);
173 }
174 if let Some(body) = self.body {
175 builder = builder.text(body);
176 }
177
178 let mut response = builder.send(self.app.service.as_ref()).await;
179
180 let status = response
181 .status_code
182 .map(|code| code.as_u16())
183 .unwrap_or(200);
184 let headers: Vec<(String, String)> = response
185 .headers()
186 .iter()
187 .filter_map(|(name, value)| {
188 value
189 .to_str()
190 .ok()
191 .map(|value| (name.as_str().to_owned(), value.to_owned()))
192 })
193 .collect();
194
195 use salvo::test::ResponseExt;
196 let body = response.take_string().await.unwrap_or_default();
197
198 TestResponse {
199 status,
200 headers,
201 body,
202 }
203 }
204}
205
206pub struct TestResponse {
207 status: u16,
208 headers: Vec<(String, String)>,
209 body: String,
210}
211
212impl TestResponse {
213 pub fn status(&self) -> u16 {
214 self.status
215 }
216
217 pub fn body(&self) -> &str {
218 &self.body
219 }
220
221 pub fn header(&self, name: &str) -> Option<&str> {
222 self.headers
223 .iter()
224 .find(|(key, _)| key.eq_ignore_ascii_case(name))
225 .map(|(_, value)| value.as_str())
226 }
227
228 pub fn json(&self) -> Value {
231 serde_json::from_str(&self.body).unwrap_or_else(|err| {
232 panic!(
233 "expected a JSON body but could not parse it: {err}\nbody: {}",
234 self.body
235 )
236 })
237 }
238
239 pub fn assert_status(self, expected: u16) -> Self {
240 assert!(
241 self.status == expected,
242 "expected status {expected}, got {}\nbody: {}",
243 self.status,
244 self.body
245 );
246 self
247 }
248
249 pub fn assert_ok(self) -> Self {
250 self.assert_status(200)
251 }
252
253 pub fn assert_created(self) -> Self {
254 self.assert_status(201)
255 }
256
257 pub fn assert_no_content(self) -> Self {
258 self.assert_status(204)
259 }
260
261 pub fn assert_unauthorized(self) -> Self {
262 self.assert_status(401)
263 }
264
265 pub fn assert_forbidden(self) -> Self {
266 self.assert_status(403)
267 }
268
269 pub fn assert_not_found(self) -> Self {
270 self.assert_status(404)
271 }
272
273 pub fn assert_header(self, name: &str, expected: &str) -> Self {
274 match self.header(name) {
275 Some(actual) => assert!(
276 actual == expected,
277 "expected header `{name}: {expected}`, got `{actual}`"
278 ),
279 None => panic!(
280 "expected header `{name}` but it was absent. Present: {:?}",
281 self.headers.iter().map(|(key, _)| key).collect::<Vec<_>>()
282 ),
283 }
284 self
285 }
286
287 pub fn assert_json_path(self, path: &str, expected: impl Into<Value>) -> Self {
289 let expected = expected.into();
290 let json = self.json();
291
292 match resolve(&json, path) {
293 Some(actual) => assert!(
294 *actual == expected,
295 "at `{path}`: expected {expected}, got {actual}\nbody: {}",
296 self.body
297 ),
298 None => panic!("no value at `{path}`\nbody: {}", self.body),
299 }
300 self
301 }
302
303 pub fn assert_json_count(self, path: &str, expected: usize) -> Self {
305 let json = self.json();
306
307 let Some(value) = resolve(&json, path) else {
308 panic!("no value at `{path}`\nbody: {}", self.body);
309 };
310 let Some(array) = value.as_array() else {
311 panic!("`{path}` is not an array\nbody: {}", self.body);
312 };
313
314 assert!(
315 array.len() == expected,
316 "at `{path}`: expected {expected} items, got {}\nbody: {}",
317 array.len(),
318 self.body
319 );
320 self
321 }
322
323 pub fn assert_validation_message(self, field: &str, expected: &str) -> Self {
328 let json = self.json();
329
330 let Some(messages) = json
331 .pointer(&format!("/errors/{field}"))
332 .and_then(Value::as_array)
333 else {
334 panic!("no validation errors for `{field}`\nbody: {}", self.body);
335 };
336
337 let found = messages
338 .iter()
339 .filter_map(Value::as_str)
340 .any(|message| message == expected);
341
342 assert!(
343 found,
344 "expected `{field}` to report {expected:?}, got {:?}\nbody: {}",
345 messages
346 .iter()
347 .filter_map(Value::as_str)
348 .collect::<Vec<_>>(),
349 self.body
350 );
351 self
352 }
353
354 pub fn assert_validation_errors(self, fields: &[&str]) -> Self {
357 let response = self.assert_status(422);
358 let json = response.json();
359
360 let Some(errors) = json.get("errors").and_then(Value::as_object) else {
361 panic!("expected an `errors` object\nbody: {}", response.body);
362 };
363
364 for field in fields {
365 assert!(
366 errors.contains_key(*field),
367 "expected a validation error for `{field}`, got {:?}\nbody: {}",
368 errors.keys().collect::<Vec<_>>(),
369 response.body
370 );
371 }
372
373 assert!(
374 errors.len() == fields.len(),
375 "expected errors for exactly {:?}, got {:?}",
376 fields,
377 errors.keys().collect::<Vec<_>>()
378 );
379 response
380 }
381}
382
383fn resolve<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
385 let mut current = value;
386
387 for segment in path.split('.').filter(|segment| !segment.is_empty()) {
388 current = match segment.parse::<usize>() {
389 Ok(index) => current.get(index)?,
390 Err(_) => current.get(segment)?,
391 };
392 }
393
394 Some(current)
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400 use serde_json::json;
401
402 fn response(status: u16, body: Value) -> TestResponse {
403 TestResponse {
404 status,
405 headers: Vec::new(),
406 body: body.to_string(),
407 }
408 }
409
410 #[test]
411 fn resolves_object_and_array_segments() {
412 let value = json!({ "data": [{ "name": "Ada" }, { "name": "Alan" }] });
413
414 assert_eq!(resolve(&value, "data.1.name"), Some(&json!("Alan")));
415 assert_eq!(resolve(&value, "data"), value.get("data"));
416 assert_eq!(resolve(&value, "data.9.name"), None);
417 assert_eq!(resolve(&value, "missing"), None);
418 }
419
420 #[test]
421 fn passing_assertions_return_the_response_for_chaining() {
422 response(200, json!({ "data": [1, 2, 3], "page": 1 }))
423 .assert_ok()
424 .assert_json_count("data", 3)
425 .assert_json_path("page", 1);
426 }
427
428 #[test]
429 #[should_panic(expected = "expected status 200, got 500")]
430 fn a_wrong_status_fails_with_the_body() {
431 response(500, json!({ "title": "boom" })).assert_ok();
432 }
433
434 #[test]
435 #[should_panic(expected = "at `page`: expected 2, got 1")]
436 fn a_wrong_json_value_reports_both_sides() {
437 response(200, json!({ "page": 1 })).assert_json_path("page", 2);
438 }
439
440 #[test]
441 #[should_panic(expected = "no value at `nope`")]
442 fn a_missing_path_names_the_path() {
443 response(200, json!({ "page": 1 })).assert_json_path("nope", 1);
444 }
445
446 #[test]
447 fn validation_errors_match_exactly_the_named_fields() {
448 response(
449 422,
450 json!({ "errors": { "email": ["is invalid"], "name": ["is required"] } }),
451 )
452 .assert_validation_errors(&["email", "name"]);
453 }
454
455 #[test]
456 #[should_panic(expected = "expected a validation error for `name`")]
457 fn a_missing_validation_field_is_reported() {
458 response(422, json!({ "errors": { "email": ["is invalid"] } }))
459 .assert_validation_errors(&["name"]);
460 }
461
462 #[test]
463 #[should_panic(expected = "expected errors for exactly")]
464 fn extra_validation_fields_are_reported_too() {
465 response(
466 422,
467 json!({ "errors": { "email": ["is invalid"], "name": ["is required"] } }),
468 )
469 .assert_validation_errors(&["email"]);
470 }
471}