Skip to main content

luxid_testing/
lib.rs

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