laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use std::cell::{Cell, RefCell};
use std::collections::BTreeSet;
use std::fmt;
use std::ops::{Bound, RangeBounds};
use std::rc::Rc;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Match {
    Contains,
    Exact,
    Similar,
}

impl Match {
    pub(super) const fn wanted(self) -> &'static str {
        match self {
            Self::Contains => "contain",
            Self::Exact => "be exactly",
            Self::Similar => "be, with lists in any order,",
        }
    }
}

pub(super) fn difference(actual: &Value, expected: &Value, path: &str, matching: Match) -> Option<String> {
    let at = |key: &dyn fmt::Display| join(path, &key.to_string());
    let exact = matching != Match::Contains;

    match (actual, expected) {
        (Value::Object(actual), Value::Object(expected)) => expected
            .iter()
            .find_map(|(key, expected)| match actual.get(key) {
                Some(actual) => difference(actual, expected, &at(key), matching),
                None => Some(format!("`{}` is missing", at(key))),
            })
            .or_else(|| {
                let extra = actual.keys().find(|key| exact && !expected.contains_key(*key))?;
                Some(format!("it has `{}` too", at(extra)))
            }),
        (Value::Array(items), Value::Array(expected)) => expected
            .iter()
            .enumerate()
            .find_map(|(index, expected)| match items.get(index) {
                Some(actual) => difference(actual, expected, &at(&index), matching),
                None => Some(format!("`{}` is missing", at(&index))),
            })
            .or_else(|| {
                (exact && items.len() > expected.len()).then(|| {
                    format!(
                        "{} has {} item{}, not {}",
                        subject(path),
                        items.len(),
                        if items.len() == 1 { "" } else { "s" },
                        expected.len()
                    )
                })
            }),
        _ if actual == expected => None,
        _ => Some(format!("{} is {actual}", subject(path))),
    }
}

/// Find the path, from the root of `actual`, of the first value in `actual` that contains
/// `fragment`, as [`Match::Contains`] matches it.
pub(super) fn find_fragment(actual: &Value, fragment: &Value, path: &str) -> Option<String> {
    if difference(actual, fragment, "", Match::Contains).is_none() {
        return Some(path.to_owned());
    }

    let at = |key: &dyn fmt::Display| join(path, &key.to_string());
    match actual {
        Value::Object(object) => object
            .iter()
            .find_map(|(key, value)| find_fragment(value, fragment, &at(key))),
        Value::Array(items) => items
            .iter()
            .enumerate()
            .find_map(|(index, item)| find_fragment(item, fragment, &at(&index))),
        _ => None,
    }
}

/// Find the first place where `actual` lacks a key that `structure` names. When `exact` is
/// true, also find a key in `actual` that `structure` doesn't name.
///
/// In `structure`, a list names keys and objects of keys, and an object names keys along with
/// the structure of their values. `null` names nothing, and the key `*` applies its structure to
/// every item.
pub(super) fn structure_difference(actual: &Value, structure: &Value, path: &str, exact: bool) -> Option<String> {
    let at = |key: &dyn fmt::Display| join(path, &key.to_string());

    let mut named: Vec<(&str, Option<&Value>)> = Vec::new();
    match structure {
        Value::Null => return None,
        Value::Array(items) => {
            for item in items {
                match item {
                    Value::String(key) => named.push((key, None)),
                    Value::Object(keys) => named.extend(keys.iter().map(|(key, nested)| (key.as_str(), Some(nested)))),
                    other => panic!("a JSON structure lists keys and objects of keys, not {other}"),
                }
            }
        }
        Value::Object(keys) => named.extend(keys.iter().map(|(key, nested)| (key.as_str(), Some(nested)))),
        other => panic!("a JSON structure is a list or an object of keys, not {other}"),
    }

    for (key, nested) in &named {
        if *key == "*" {
            let Some(items) = entries(actual) else {
                return Some(format!("{} is {actual}, not a list or object", subject(path)));
            };
            let difference = items.into_iter().find_map(|(index, item)| {
                structure_difference(item, nested.unwrap_or(&Value::Null), &at(&index), exact)
            });
            if difference.is_some() {
                return difference;
            }
            continue;
        }

        let Value::Object(object) = actual else {
            return Some(format!("{} is {actual}, not an object with `{key}`", subject(path)));
        };
        let Some(value) = object.get(*key) else {
            return Some(format!("`{}` is missing", at(key)));
        };
        if let Some(difference) = nested.and_then(|nested| structure_difference(value, nested, &at(key), exact)) {
            return Some(difference);
        }
    }

    let Value::Object(object) = actual else {
        return None;
    };
    if !exact || named.iter().any(|(key, _)| *key == "*") {
        return None;
    }
    let extra = object.keys().find(|key| named.iter().all(|(named, _)| named != key))?;

    Some(format!("it has `{}` too", at(extra)))
}

/// Join `key` onto the dot-notation `path`, where an empty `path` is the root.
fn join(path: &str, key: &str) -> String {
    match (path.is_empty(), key.is_empty()) {
        (true, _) => key.to_owned(),
        (_, true) => path.to_owned(),
        _ => format!("{path}.{key}"),
    }
}

/// How a failure message names the value at the dot-notation `path`.
pub(super) fn subject(path: &str) -> String {
    if path.is_empty() {
        "the JSON".to_owned()
    } else {
        format!("`{path}`")
    }
}

/// The keys and items of a list or object, where a list's keys are its indexes, or `None` for
/// any other value.
pub(super) fn entries(value: &Value) -> Option<Vec<(String, &Value)>> {
    match value {
        Value::Array(items) => Some(
            items
                .iter()
                .enumerate()
                .map(|(index, item)| (index.to_string(), item))
                .collect(),
        ),
        Value::Object(object) => Some(object.iter().map(|(key, item)| (key.clone(), item)).collect()),
        _ => None,
    }
}

/// Why `value` fails `check`, completing "expected .. to": it doesn't read as a `T`, or the check
/// rejects it. Returns `None` when the value passes.
pub(super) fn rejection<T: DeserializeOwned>(value: &Value, check: impl FnOnce(T) -> bool) -> Option<String> {
    match serde_json::from_value(value.clone()) {
        Ok(read) => (!check(read)).then(|| format!("pass the check, but it's {value}")),
        Err(error) => Some(format!(
            "read as `{}`, but it's {value}: {error}",
            std::any::type_name::<T>()
        )),
    }
}

/// Serialize an assertion's expected value.
#[track_caller]
pub(super) fn to_json(expected: impl Serialize) -> Value {
    serde_json::to_value(expected).expect("the expected value should serialize")
}

/// Fail a JSON assertion with `message`, then the JSON and the response's outline.
#[track_caller]
pub(super) fn fail(json: &Value, outline: &str, message: fmt::Arguments<'_>) -> ! {
    panic!("{message}:\n{}\n\n{outline}", pretty(json))
}

pub(super) fn sorted(value: &Value) -> Value {
    match value {
        Value::Array(items) => {
            let mut items: Vec<Value> = items.iter().map(sorted).collect();
            items.sort_by_cached_key(Value::to_string);

            Value::Array(items)
        }
        Value::Object(object) => {
            let mut entries: Vec<(&String, &Value)> = object.iter().collect();
            entries.sort_by_key(|(key, _)| *key);

            Value::Object(
                entries
                    .into_iter()
                    .map(|(key, value)| (key.clone(), sorted(value)))
                    .collect(),
            )
        }
        _ => value.clone(),
    }
}

/// The value at a dot-notation path inside `value`, where an empty path is `value` itself.
pub(super) fn descend<'a>(value: &'a Value, path: &str) -> Option<&'a Value> {
    if path.is_empty() {
        return Some(value);
    }

    path.split('.').try_fold(value, |value, segment| match value {
        Value::Object(object) => object.get(segment),
        Value::Array(items) => segment.parse::<usize>().ok().and_then(|index| items.get(index)),
        _ => None,
    })
}

pub(super) fn pretty(value: &impl Serialize) -> String {
    serde_json::to_string_pretty(value).unwrap_or_default()
}

/// JSON under test, which [`TestResponse::assert_json_matches`](super::TestResponse::assert_json_matches)
/// passes to its closure.
///
/// Each assertion returns the JSON, so assertions chain. When an assertion fails, it panics with
/// a message that says what it expected and shows the JSON.
///
/// Paths use dot notation, such as `data.0.name`, where list items are numbered from `0`. Inside
/// a [`scope`](Self::scope), paths start at the scoped value, and the empty path `""` is the
/// scoped value itself. Each closure must assert on every key of the object or list it scopes,
/// or call [`etc`](Self::etc) to allow the keys it doesn't check.
///
/// ```no_run
/// # use laravel::testing::MakesHttpRequests;
/// # async fn test(app: laravel::Application) {
/// app.get("/api/users").await.assert_json_matches(|json| {
///     json.has_count("data", 2)
///         .first("data", |user| user.equals("name", "Taylor").missing("password").etc())
///         .each("data", |user| user.satisfies("id", |id: u64| id > 0).etc())
///         .scope("meta", |meta| meta.equals("total", 2))
/// });
/// # }
/// ```
pub struct AssertableJson {
    json: Rc<Value>,
    outline: Rc<str>,
    scope: Scope,
}

/// The value that a closure asserts on, and the keys of that value the closure has checked.
struct Scope {
    path: String,
    interacted: RefCell<BTreeSet<String>>,
    etc: Cell<bool>,
}

impl AssertableJson {
    /// Run `assertions` on a response's JSON. The closure must assert on every key or item at the
    /// root, or call [`etc`](Self::etc).
    #[track_caller]
    pub(super) fn assert_root(json: Value, outline: String, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) {
        let root = Self {
            json: Rc::new(json),
            outline: outline.into(),
            scope: Scope::at(String::new()),
        };

        assertions(&root);

        root.assert_interacted();
    }

    /// The value at the path, or `None` when the path has no value.
    ///
    /// Reading a value counts as asserting on it, so the closure doesn't need
    /// [`etc`](Self::etc) to allow that key.
    pub fn prop(&self, path: &str) -> Option<&Value> {
        if let Some(key) = path.split('.').next().filter(|key| !key.is_empty()) {
            self.scope.interacted.borrow_mut().insert(key.to_owned());
        }

        descend(&self.json, &self.full_path(path))
    }

    #[track_caller]
    fn expect_prop(&self, path: &str) -> &Value {
        match self.prop(path) {
            Some(value) => value,
            None => self.fail(format_args!("expected the JSON to have `{}`", self.full_path(path))),
        }
    }

    fn full_path(&self, path: &str) -> String {
        join(&self.scope.path, path)
    }

    fn subject(&self, path: &str) -> String {
        subject(&self.full_path(path))
    }

    #[track_caller]
    fn fail(&self, message: fmt::Arguments<'_>) -> ! {
        fail(&self.json, &self.outline, message)
    }

    /// Assert that the path has a value, which may be `null`.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn has(&self, path: &str) -> &Self {
        self.expect_prop(path);
        self
    }

    /// Assert that at least one of the paths has a value.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn has_any(&self, paths: &[&str]) -> &Self {
        let found: Vec<bool> = paths.iter().map(|path| self.prop(path).is_some()).collect();
        if !found.contains(&true) {
            let paths: Vec<String> = paths.iter().map(|path| format!("`{}`", self.full_path(path))).collect();
            self.fail(format_args!("expected the JSON to have one of {}", paths.join(", ")));
        }
        self
    }

    /// Assert that the value at the path is a list or object with the given number of items.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn has_count(&self, path: &str, count: usize) -> &Self {
        self.has_count_in(path, count..=count)
    }

    /// Assert that the value at the path is a list or object whose number of items is in the
    /// range, such as `1..=3`.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn has_count_in(&self, path: &str, counts: impl RangeBounds<usize> + fmt::Debug) -> &Self {
        let actual = self.items(path).len();
        if !counts.contains(&actual) {
            let expected = match (counts.start_bound(), counts.end_bound()) {
                (Bound::Included(start), Bound::Included(end)) if start == end => start.to_string(),
                _ => format!("{counts:?}"),
            };
            self.fail(format_args!(
                "expected {} to have {expected} items, but it has {actual}",
                self.subject(path)
            ));
        }
        self
    }

    /// The keys of the list or object at the path. A list's keys are its indexes.
    #[track_caller]
    fn items(&self, path: &str) -> Vec<String> {
        let value = self.expect_prop(path);
        match entries(value) {
            Some(entries) => entries.into_iter().map(|(key, _)| key).collect(),
            None => self.fail(format_args!(
                "expected {} to be a list or object, but it's {value}",
                self.subject(path)
            )),
        }
    }

    /// Assert that the path has no value. A `null` is a value.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn missing(&self, path: &str) -> &Self {
        if let Some(value) = self.prop(path) {
            self.fail(format_args!(
                "expected the JSON to have no `{}`, but it's {value}",
                self.full_path(path)
            ));
        }
        self
    }

    /// Assert that the value at the path equals the given value.
    ///
    /// Objects match with their keys in any order. Lists must have their items in the same order.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails, or the expected value can't be serialized.
    #[track_caller]
    pub fn equals(&self, path: &str, expected: impl Serialize) -> &Self {
        let expected = to_json(expected);
        let actual = self.expect_prop(path);

        if actual != &expected {
            self.fail(format_args!(
                "expected {} to be {expected}, but it's {actual}",
                self.subject(path)
            ));
        }
        self
    }

    /// Assert that the value at the path reads as a `T` that passes the check.
    ///
    /// Name the type in the closure, as in `|age: u32| age >= 18`. To assert only the type,
    /// return `true`, as in `|_: Option<String>| true`.
    ///
    /// # Panics
    ///
    /// Panics when the path has no value, the value doesn't read as a `T`, or the check fails.
    #[track_caller]
    pub fn satisfies<T: DeserializeOwned>(&self, path: &str, check: impl FnOnce(T) -> bool) -> &Self {
        if let Some(rejection) = rejection(self.expect_prop(path), check) {
            self.fail(format_args!("expected {} to {rejection}", self.subject(path)));
        }
        self
    }

    /// Assert that the list or object at the path has an item equal to the given value.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails, or the expected value can't be serialized.
    #[track_caller]
    pub fn contains(&self, path: &str, item: impl Serialize) -> &Self {
        let item = to_json(item);
        let found = match self.expect_prop(path) {
            Value::Array(items) => items.contains(&item),
            Value::Object(object) => object.values().any(|value| value == &item),
            other => self.fail(format_args!(
                "expected {} to be a list or object, but it's {other}",
                self.subject(path)
            )),
        };

        if !found {
            self.fail(format_args!("expected {} to contain {item}", self.subject(path)));
        }
        self
    }

    /// Assert on the object or list at the path, in a closure whose paths start there.
    ///
    /// The closure must assert on every key in the scope, or call [`etc`](Self::etc) to allow
    /// the keys it doesn't check.
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn scope(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) -> &Self {
        self.assert_scoped(path, assertions);
        self
    }

    /// Assert on the first item of the list or object at the path, in a closure that works as
    /// it does with [`scope`](Self::scope).
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn first(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) -> &Self {
        let Some(first) = self.items(path).into_iter().next() else {
            self.fail(format_args!("expected {} to have an item", self.subject(path)));
        };

        self.assert_scoped(&join(path, &first), assertions);
        self
    }

    /// Assert on each item of the list or object at the path, in a closure that works as it does
    /// with [`scope`](Self::scope).
    ///
    /// # Panics
    ///
    /// Panics when the assertion fails.
    #[track_caller]
    pub fn each(&self, path: &str, mut assertions: impl for<'a> FnMut(&'a Self) -> &'a Self) -> &Self {
        let items = self.items(path);
        if items.is_empty() {
            self.fail(format_args!("expected {} to have an item", self.subject(path)));
        }

        for item in items {
            self.assert_scoped(&join(path, &item), &mut assertions);
        }
        self
    }

    /// Allow the keys in this scope that the closure doesn't assert on.
    pub fn etc(&self) -> &Self {
        self.scope.etc.set(true);
        self
    }

    #[track_caller]
    fn assert_scoped(&self, path: &str, assertions: impl for<'a> FnOnce(&'a Self) -> &'a Self) {
        self.items(path);
        let scoped = Self {
            json: Rc::clone(&self.json),
            outline: Rc::clone(&self.outline),
            scope: Scope::at(self.full_path(path)),
        };

        assertions(&scoped);

        scoped.assert_interacted();
    }

    /// Assert that the closure asserted on every key of the scoped value, unless it called `etc`.
    #[track_caller]
    fn assert_interacted(&self) {
        if self.scope.etc.get() {
            return;
        }
        let entries = descend(&self.json, &self.scope.path).and_then(entries);
        let interacted = self.scope.interacted.borrow();
        let unexpected: Vec<String> = entries
            .unwrap_or_default()
            .into_iter()
            .filter(|(key, _)| !interacted.contains(key))
            .map(|(key, _)| format!("`{}`", join(&self.scope.path, &key)))
            .collect();

        if !unexpected.is_empty() {
            self.fail(format_args!(
                "unexpected keys in {}: {}. Assert on them, or call `etc()` to allow them",
                self.subject(""),
                unexpected.join(", ")
            ));
        }
    }
}

impl Scope {
    fn at(path: String) -> Self {
        Self {
            path,
            interacted: RefCell::default(),
            etc: Cell::new(false),
        }
    }
}

impl fmt::Debug for AssertableJson {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AssertableJson")
            .field("path", &self.scope.path)
            .field("json", &descend(&self.json, &self.scope.path))
            .finish()
    }
}