1use 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
31pub trait ApiRequest: Sized {
33 #[must_use]
35 fn api_version(self, version: &str) -> Self;
36
37 #[must_use]
39 fn api_key(self, key: &str) -> Self;
40
41 #[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
60pub trait ExpectedError {
63 fn expected_code(&self) -> String;
65 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
89pub trait ApiResponse {
91 fn assert_json_api_resource(&self, kind: Option<&str>, id: Option<&str>) -> &Self;
93
94 fn assert_json_api_collection(&self, kind: Option<&str>, count: Option<usize>) -> &Self;
97
98 fn assert_api_error(&self, code: impl ExpectedError) -> &Self;
100
101 fn assert_idempotent_replay(&self) -> &Self;
103
104 fn assert_not_idempotent_replay(&self) -> &Self;
106
107 fn assert_deprecated(&self, sunset: Option<&str>) -> &Self;
110
111 fn assert_not_deprecated(&self) -> &Self;
113
114 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
261fn 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#[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#[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#[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
307pub 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}