Skip to main content

fusion_stack/
testing.rs

1//! Test helpers, as the PHP package's `InteractsWithApi`, `ApiTestResponse` and
2//! `TransformsVersionChanges`: request headers for versions, keys and idempotency, assertions
3//! for JSON:API documents, errors, replays, deprecation and shapes, and helpers that run one
4//! version change on its own.
5//!
6//! ```no_run
7//! use fusion_stack::testing::{ApiRequest, ApiResponse};
8//! use laravel::testing::prelude::*;
9//! # fn create() -> Application { Application::configure().create() }
10//!
11//! #[laravel::test(app = create)]
12//! async fn old_clients_see_the_old_name(app: Application) {
13//!     app.get("/v1/customers/1")
14//!         .api_version("2026-06-01")
15//!         .await
16//!         .assert_json_api_resource(Some("customers"), Some("1"))
17//!         .assert_deprecated(Some("2027-06-01"))
18//!         .assert_shape(json!({ "data": { "type": "string", "id": "string",
19//!             "attributes": { "name": "string" } } }));
20//! }
21//! ```
22
23use laravel::testing::{TestRequest, TestResponse};
24use serde_json::{Map, Value, json};
25
26use crate::errors::ErrorCode;
27use crate::versioning::VersionChange;
28
29const JSON_API: &str = "application/vnd.api+json";
30
31/// Fusion Stack's request headers on a test request.
32pub trait ApiRequest: Sized {
33    /// Pins the request to a version with the `Api-Version` header.
34    #[must_use]
35    fn api_version(self, version: &str) -> Self;
36
37    /// Authenticates with an API key, as a bearer token.
38    #[must_use]
39    fn api_key(self, key: &str) -> Self;
40
41    /// Sends an `Idempotency-Key`, so a retry with the same key is replayed.
42    #[must_use]
43    fn idempotency_key(self, key: &str) -> Self;
44}
45
46impl ApiRequest for TestRequest {
47    fn api_version(self, version: &str) -> Self {
48        self.header("Api-Version", version)
49    }
50
51    fn api_key(self, key: &str) -> Self {
52        self.token(key)
53    }
54
55    fn idempotency_key(self, key: &str) -> Self {
56        self.header("Idempotency-Key", key)
57    }
58}
59
60/// The error an [`ApiResponse::assert_api_error`] expects: a code such as `"not_found"`, which
61/// checks no status, or an [`ErrorCode`], which also checks the code's own status.
62pub trait ExpectedError {
63    /// The code, such as `not_found`.
64    fn expected_code(&self) -> String;
65    /// The status the response must have, if any.
66    fn expected_status(&self) -> Option<u16>;
67}
68
69impl ExpectedError for &str {
70    fn expected_code(&self) -> String {
71        (*self).to_owned()
72    }
73
74    fn expected_status(&self) -> Option<u16> {
75        None
76    }
77}
78
79impl<T: ErrorCode> ExpectedError for T {
80    fn expected_code(&self) -> String {
81        self.code().to_owned()
82    }
83
84    fn expected_status(&self) -> Option<u16> {
85        Some(self.status())
86    }
87}
88
89/// Fusion Stack's assertions on a test response. Each returns the response, so they chain.
90pub trait ApiResponse {
91    /// A successful JSON:API document whose `data` is one resource, of `kind` and `id` when given.
92    fn assert_json_api_resource(&self, kind: Option<&str>, id: Option<&str>) -> &Self;
93
94    /// A successful JSON:API document whose `data` is a list of resources, each of `kind` and
95    /// `count` of them when given.
96    fn assert_json_api_collection(&self, kind: Option<&str>, count: Option<usize>) -> &Self;
97
98    /// A JSON:API error document with an error of `code`. An [`ErrorCode`] also checks its status.
99    fn assert_api_error(&self, code: impl ExpectedError) -> &Self;
100
101    /// The response was replayed from an earlier request with the same `Idempotency-Key`.
102    fn assert_idempotent_replay(&self) -> &Self;
103
104    /// The request ran: it was not replayed.
105    fn assert_not_idempotent_replay(&self) -> &Self;
106
107    /// The version the response was served in is deprecated, sunsetting on `sunset`
108    /// (`YYYY-MM-DD`) when given.
109    fn assert_deprecated(&self, sunset: Option<&str>) -> &Self;
110
111    /// The version the response was served in is not deprecated.
112    fn assert_not_deprecated(&self) -> &Self;
113
114    /// The body's [`shape`]. Key order does not matter.
115    fn assert_shape(&self, expected: Value) -> &Self;
116}
117
118fn assert_json_api(response: &TestResponse, what: &str) {
119    let content_type = response.header("content-type").unwrap_or_default();
120    assert!(
121        content_type.starts_with(JSON_API),
122        "Expected a JSON:API {what}; the Content-Type is [{content_type}]."
123    );
124}
125
126fn data(response: &TestResponse) -> Value {
127    response.assert_successful();
128    assert_json_api(response, "document");
129    let data = response.json().get("data").cloned();
130    assert!(
131        data.as_ref()
132            .is_some_and(|data| data.is_object() || data.is_array()),
133        "Expected a `data` member."
134    );
135    data.unwrap_or_default()
136}
137
138fn assert_resource_object(resource: &Value, kind: Option<&str>) {
139    let actual = resource.get("type").and_then(Value::as_str);
140    assert!(actual.is_some(), "A resource object needs a string `type`.");
141    assert!(
142        resource.get("id").is_some_and(Value::is_string),
143        "A resource object needs a string `id`."
144    );
145    if let Some(kind) = kind {
146        assert_eq!(actual, Some(kind), "The resource has a different type.");
147    }
148}
149
150impl ApiResponse for TestResponse {
151    fn assert_json_api_resource(&self, kind: Option<&str>, id: Option<&str>) -> &Self {
152        let data = data(self);
153        assert!(
154            data.is_object(),
155            "Expected `data` to be one resource, not a list."
156        );
157        assert_resource_object(&data, kind);
158        if let Some(id) = id {
159            assert_eq!(
160                data.get("id").and_then(Value::as_str),
161                Some(id),
162                "The resource has a different id."
163            );
164        }
165        self
166    }
167
168    fn assert_json_api_collection(&self, kind: Option<&str>, count: Option<usize>) -> &Self {
169        let data = data(self);
170        let Value::Array(resources) = &data else {
171            panic!("Expected `data` to be a list of resources.");
172        };
173        for resource in resources {
174            assert_resource_object(resource, kind);
175        }
176        if let Some(count) = count {
177            assert_eq!(
178                resources.len(),
179                count,
180                "Expected {count} resources in `data`."
181            );
182        }
183        self
184    }
185
186    fn assert_api_error(&self, code: impl ExpectedError) -> &Self {
187        let expected = code.expected_code();
188        assert_json_api(self, "error document");
189        let body = self.json();
190        let Some(errors) = body.get("errors").and_then(Value::as_array) else {
191            panic!("Expected an `errors` list.");
192        };
193        let codes: Vec<&str> = errors
194            .iter()
195            .filter_map(|error| error.get("code").and_then(Value::as_str))
196            .collect();
197        assert!(
198            codes.contains(&expected.as_str()),
199            "Expected an error [{expected}]; got [{}].",
200            codes.join(", ")
201        );
202        if let Some(status) = code.expected_status() {
203            self.assert_status(status);
204        }
205        self
206    }
207
208    fn assert_idempotent_replay(&self) -> &Self {
209        assert_eq!(
210            self.header("idempotent-replayed"),
211            Some("true"),
212            "Expected a replayed response (Idempotent-Replayed: true)."
213        );
214        self
215    }
216
217    fn assert_not_idempotent_replay(&self) -> &Self {
218        assert!(
219            self.header("idempotent-replayed").is_none(),
220            "Expected the request to run, not be replayed."
221        );
222        self
223    }
224
225    fn assert_deprecated(&self, sunset: Option<&str>) -> &Self {
226        assert!(
227            self.headers().contains_key("deprecation"),
228            "Expected a Deprecation header."
229        );
230        if let Some(sunset) = sunset {
231            let header = self.header("sunset");
232            assert!(header.is_some(), "Expected a Sunset header.");
233            let header = header.unwrap_or_default();
234            assert_eq!(
235                http_date(header).as_deref().unwrap_or(header),
236                sunset,
237                "The Sunset header has a different date."
238            );
239        }
240        self
241    }
242
243    fn assert_not_deprecated(&self) -> &Self {
244        assert!(
245            !self.headers().contains_key("deprecation"),
246            "Expected no Deprecation header."
247        );
248        self
249    }
250
251    fn assert_shape(&self, expected: Value) -> &Self {
252        assert_eq!(
253            shape(&self.json()),
254            expected,
255            "The response has a different shape."
256        );
257        self
258    }
259}
260
261/// `Mon, 01 Jun 2027 00:00:00 GMT` as `2027-06-01`.
262fn http_date(header: &str) -> Option<String> {
263    const MONTHS: [&str; 12] = [
264        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
265    ];
266    let mut parts = header.split_whitespace().skip(1);
267    let (day, month, year) = (parts.next()?, parts.next()?, parts.next()?);
268    let month = MONTHS.iter().position(|known| *known == month)? + 1;
269    Some(format!("{year}-{month:02}-{day:0>2}"))
270}
271
272/// A value's shape: its keys, with each value replaced by its JSON type (`string`, `integer`,
273/// `number`, `boolean` or `null`) and each list by the shape of its first item.
274#[must_use]
275pub fn shape(value: &Value) -> Value {
276    match value {
277        Value::Array(items) => Value::Array(items.first().map(shape).into_iter().collect()),
278        Value::Object(map) => Value::Object(
279            map.iter()
280                .map(|(key, value)| (key.clone(), shape(value)))
281                .collect(),
282        ),
283        Value::String(_) => json!("string"),
284        Value::Number(number) if number.is_f64() => json!("number"),
285        Value::Number(_) => json!("integer"),
286        Value::Bool(_) => json!("boolean"),
287        Value::Null => json!("null"),
288    }
289}
290
291/// An older client's request body, migrated to the shape after the change.
292#[must_use]
293pub fn upgrade_request(change: &dyn VersionChange, payload: &Value) -> Value {
294    let mut map: Map<String, Value> = payload.as_object().cloned().unwrap_or_default();
295    change.transform_request(&mut map);
296    Value::Object(map)
297}
298
299/// A latest-shape response document, migrated back to the shape before the change.
300#[must_use]
301pub fn downgrade_response(change: &dyn VersionChange, document: &Value) -> Value {
302    let mut document = document.clone();
303    change.transform_response(&mut document);
304    document
305}
306
307/// Downgrading `document` and upgrading the result gives `document` back, so old clients can
308/// send what they receive. Not for changes that drop data, such as a removed attribute. Returns
309/// the downgraded document, for further assertions.
310///
311/// # Panics
312///
313/// When upgrading the downgraded document does not give it back.
314pub fn assert_round_trip(change: &dyn VersionChange, document: &Value) -> Value {
315    let old = downgrade_response(change, document);
316    assert_eq!(
317        &upgrade_request(change, &old),
318        document,
319        "Upgrading the downgraded document does not give it back."
320    );
321    old
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn shapes_use_the_first_item_of_each_list() {
330        assert_eq!(
331            shape(
332                &json!({ "data": [{ "id": "1", "n": 2, "f": 1.5, "b": true, "z": null }, { "x": 1 }], "e": [] })
333            ),
334            json!({ "data": [{ "id": "string", "n": "integer", "f": "number", "b": "boolean", "z": "null" }], "e": [] })
335        );
336    }
337
338    #[test]
339    fn reads_sunset_dates() {
340        assert_eq!(
341            http_date("Tue, 01 Jun 2027 00:00:00 GMT").as_deref(),
342            Some("2027-06-01")
343        );
344    }
345}