test-better-matchers 0.2.1

Matcher trait, standard matchers, and the `check!` macro for the test-better testing library.
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
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! Collection matchers and the [`Sequence`] trait they are generic over.
//!
//! [`Sequence`] is the crate's abstraction over an ordered run of items: it is
//! implemented for slices, arrays, `Vec`, `VecDeque`, `BTreeSet`, `HashSet`,
//! and `&S` for any `Sequence` `S`. The matchers in this module
//! ([`have_len`], [`is_empty`], [`is_not_empty`], [`contains`],
//! [`contains_all`], [`contains_in_order`], [`every`], [`at_least_one`]) work
//! for every one of those.
//!
//! Failures name the index of the first item (or, for sets, the offending
//! value) that broke the expectation.

use std::collections::{BTreeSet, HashSet, VecDeque};
use std::fmt;

use crate::description::Description;
use crate::matcher::{MatchResult, Matcher, Mismatch};

/// An ordered run of items a collection matcher can inspect.
///
/// Implemented for `[T]`, `[T; N]`, `Vec<T>`, `VecDeque<T>`, `BTreeSet<T>`,
/// `HashSet<T>`, and `&S` for any `Sequence` `S`. Items are borrowed, not
/// cloned. A lazy iterator is not a `Sequence` (it cannot be inspected through
/// a shared borrow); collect it into a `Vec` first.
pub trait Sequence {
    /// The element type.
    type Item;

    /// Borrows every item, in order.
    fn sequence_items(&self) -> Vec<&Self::Item>;
}

impl<T> Sequence for [T] {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<T, const N: usize> Sequence for [T; N] {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<T> Sequence for Vec<T> {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<T> Sequence for VecDeque<T> {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<T> Sequence for BTreeSet<T> {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<T> Sequence for HashSet<T> {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.iter().collect()
    }
}

impl<S: Sequence + ?Sized> Sequence for &S {
    type Item = S::Item;

    fn sequence_items(&self) -> Vec<&S::Item> {
        (**self).sequence_items()
    }
}

/// An eager [`Sequence`] wrapper around an iterator's collected items.
///
/// A lazy iterator cannot implement [`Sequence`] directly: the trait borrows
/// its items through `&self`, and a blanket `impl<I: Iterator>` would collide
/// with the concrete collection impls under coherence. [`Items`] sidesteps both
/// problems by collecting the iterator into a `Vec<T>` up front, which means
/// the assertion sees a full, indexable view of the produced values.
///
/// Construct one with [`items`]. The wrapper is just a `Vec<T>` underneath, so
/// it carries no surprises around iteration order or repeated reads.
pub struct Items<T>(Vec<T>);

impl<T> Sequence for Items<T> {
    type Item = T;

    fn sequence_items(&self) -> Vec<&T> {
        self.0.iter().collect()
    }
}

/// Collects an iterator into an [`Items`] wrapper that implements [`Sequence`].
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{contains, eq, check, items};
///
/// fn main() -> TestResult {
///     let doubled = (1..=3).map(|n| n * 2);
///     check!(items(doubled)).satisfies(contains(eq(4)))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn items<I>(iter: I) -> Items<I::Item>
where
    I: IntoIterator,
{
    Items(iter.into_iter().collect())
}

/// The matcher behind [`have_len`].
struct LenMatcher {
    expected: usize,
}

impl<C> Matcher<C> for LenMatcher
where
    C: Sequence + ?Sized,
{
    fn check(&self, actual: &C) -> MatchResult {
        let len = actual.sequence_items().len();
        if len == self.expected {
            MatchResult::pass()
        } else {
            MatchResult::fail(Mismatch::new(
                Description::text(format!("a sequence of length {}", self.expected)),
                format!("a sequence of length {len}"),
            ))
        }
    }

    fn description(&self) -> Description {
        Description::text(format!("a sequence of length {}", self.expected))
    }
}

/// Matches a sequence with exactly `n` items.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{check, have_len};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3]).satisfies(have_len(3))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn have_len<C>(n: usize) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
{
    LenMatcher { expected: n }
}

/// The matcher behind [`is_empty`] and [`is_not_empty`].
struct EmptyMatcher {
    want_empty: bool,
}

impl<C> Matcher<C> for EmptyMatcher
where
    C: Sequence + ?Sized,
{
    fn check(&self, actual: &C) -> MatchResult {
        let len = actual.sequence_items().len();
        if (len == 0) == self.want_empty {
            MatchResult::pass()
        } else if self.want_empty {
            MatchResult::fail(Mismatch::new(
                self.description_text(),
                format!("a sequence of length {len}"),
            ))
        } else {
            MatchResult::fail(Mismatch::new(self.description_text(), "an empty sequence"))
        }
    }

    fn description(&self) -> Description {
        self.description_text()
    }
}

impl EmptyMatcher {
    fn description_text(&self) -> Description {
        Description::text(if self.want_empty {
            "an empty sequence"
        } else {
            "a non-empty sequence"
        })
    }
}

/// Matches a sequence with no items.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{check, is_empty};
///
/// fn main() -> TestResult {
///     check!(Vec::<i32>::new()).satisfies(is_empty())?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn is_empty<C>() -> impl Matcher<C>
where
    C: Sequence + ?Sized,
{
    EmptyMatcher { want_empty: true }
}

/// Matches a sequence with at least one item.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{check, is_not_empty};
///
/// fn main() -> TestResult {
///     check!(vec![1]).satisfies(is_not_empty())?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn is_not_empty<C>() -> impl Matcher<C>
where
    C: Sequence + ?Sized,
{
    EmptyMatcher { want_empty: false }
}

/// The matcher behind [`contains`] and [`at_least_one`]: at least one item
/// satisfies the inner matcher.
struct AnyItemMatcher<M> {
    inner: M,
    /// The phrase that heads the expected description (`contains` and
    /// `at_least_one` read differently even though they check the same thing).
    header: &'static str,
}

impl<C, M> Matcher<C> for AnyItemMatcher<M>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    fn check(&self, actual: &C) -> MatchResult {
        let items = actual.sequence_items();
        if items.iter().any(|item| self.inner.check(item).matched) {
            MatchResult::pass()
        } else {
            MatchResult::fail(Mismatch::new(
                Description::labeled(self.header, self.inner.description()),
                format!("{items:?}"),
            ))
        }
    }

    fn description(&self) -> Description {
        Description::labeled(self.header, self.inner.description())
    }
}

/// Matches a sequence that contains at least one item satisfying `matcher`.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{contains, eq, check};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3]).satisfies(contains(eq(2)))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn contains<C, M>(matcher: M) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    AnyItemMatcher {
        inner: matcher,
        header: "a sequence containing an item that is",
    }
}

/// Matches a sequence in which at least one item satisfies `matcher`.
///
/// The check is the same as [`contains`]; the two exist because they read
/// differently at the call site.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{at_least_one, check, gt};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3]).satisfies(at_least_one(gt(2)))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn at_least_one<C, M>(matcher: M) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    AnyItemMatcher {
        inner: matcher,
        header: "at least one item to satisfy",
    }
}

/// The matcher behind [`every`]: every item satisfies the inner matcher.
struct EveryMatcher<M> {
    inner: M,
}

impl<C, M> Matcher<C> for EveryMatcher<M>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    fn check(&self, actual: &C) -> MatchResult {
        let items = actual.sequence_items();
        for (index, item) in items.iter().enumerate() {
            if let Some(failure) = self.inner.check(item).failure {
                return MatchResult::fail(Mismatch::new(
                    // `EveryMatcher<M>` implements `Matcher<C>` for a family of
                    // `C`, so `description` is spelled out to stay unambiguous.
                    Matcher::<C>::description(self),
                    format!("item at index {index} was {}", failure.actual),
                ));
            }
        }
        MatchResult::pass()
    }

    fn description(&self) -> Description {
        Description::labeled("every item to satisfy", self.inner.description())
    }
}

/// Matches a sequence in which *every* item satisfies `matcher`.
///
/// On failure the error names the index of the first item that did not match.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{every, check, gt};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3]).satisfies(every(gt(0)))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn every<C, M>(matcher: M) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    EveryMatcher { inner: matcher }
}

/// The matcher behind [`contains_in_order`].
struct InOrderMatcher<M, const N: usize> {
    matchers: [M; N],
}

impl<C, M, const N: usize> Matcher<C> for InOrderMatcher<M, N>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    fn check(&self, actual: &C) -> MatchResult {
        let items = actual.sequence_items();
        let mut next = 0;
        for item in &items {
            if next < N && self.matchers[next].check(item).matched {
                next += 1;
            }
        }
        if next == N {
            MatchResult::pass()
        } else {
            MatchResult::fail(Mismatch::new(
                Matcher::<C>::description(self),
                format!(
                    "a sequence matching {next} of {N} in order \
                     (no later item satisfied matcher at index {next}): {items:?}"
                ),
            ))
        }
    }

    fn description(&self) -> Description {
        let joined = self
            .matchers
            .iter()
            .map(|m| m.description().to_string())
            .collect::<Vec<_>>()
            .join(", then ");
        Description::text(format!("a sequence containing, in order: {joined}"))
    }
}

/// Matches a sequence that contains items satisfying `matchers` in order, not
/// necessarily contiguously.
///
/// On failure the error names the index of the first matcher that no remaining
/// item could satisfy.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{contains_in_order, eq, check};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3, 4]).satisfies(contains_in_order([eq(2), eq(4)]))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn contains_in_order<C, M, const N: usize>(matchers: [M; N]) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    M: Matcher<C::Item>,
{
    InOrderMatcher { matchers }
}

/// A tuple of matchers, all over the same `Item`, for [`contains_all`].
///
/// Implemented for tuples of arity 2 through 8 by a macro in this module; you
/// do not implement it yourself.
pub trait ContainsAll<Item> {
    /// The description of the first matcher that no item in `items` satisfies,
    /// or `None` if every matcher is satisfied.
    fn first_unsatisfied(&self, items: &[&Item]) -> Option<Description>;

    /// The conjunction (`a and b and ...`) of the tuple's descriptions.
    fn describe(&self) -> Description;
}

/// Implements [`ContainsAll`] for one tuple arity. The first type parameter is
/// split out so the description fold has a guaranteed first element.
macro_rules! impl_contains_all {
    ($first:ident, $($rest:ident),+) => {
        #[allow(non_snake_case)]
        impl<Item, $first, $($rest,)+> ContainsAll<Item> for ($first, $($rest,)+)
        where
            $first: Matcher<Item>,
            $($rest: Matcher<Item>,)+
        {
            fn first_unsatisfied(&self, items: &[&Item]) -> Option<Description> {
                let ($first, $($rest,)+) = self;
                if !items.iter().any(|item| $first.check(item).matched) {
                    return Some($first.description());
                }
                $(
                    if !items.iter().any(|item| $rest.check(item).matched) {
                        return Some($rest.description());
                    }
                )+
                None
            }

            fn describe(&self) -> Description {
                let ($first, $($rest,)+) = self;
                let desc = $first.description();
                $( let desc = desc.and($rest.description()); )+
                desc
            }
        }
    };
}

impl_contains_all!(M1, M2);
impl_contains_all!(M1, M2, M3);
impl_contains_all!(M1, M2, M3, M4);
impl_contains_all!(M1, M2, M3, M4, M5);
impl_contains_all!(M1, M2, M3, M4, M5, M6);
impl_contains_all!(M1, M2, M3, M4, M5, M6, M7);
impl_contains_all!(M1, M2, M3, M4, M5, M6, M7, M8);

/// The matcher behind [`contains_all`].
struct ContainsAllMatcher<Tup> {
    matchers: Tup,
}

impl<C, Tup> Matcher<C> for ContainsAllMatcher<Tup>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    Tup: ContainsAll<C::Item>,
{
    fn check(&self, actual: &C) -> MatchResult {
        let items = actual.sequence_items();
        match self.matchers.first_unsatisfied(&items) {
            None => MatchResult::pass(),
            Some(unsatisfied) => MatchResult::fail(Mismatch::new(
                Description::labeled("a sequence containing an item that is", unsatisfied),
                format!("{items:?}"),
            )),
        }
    }

    fn description(&self) -> Description {
        Description::labeled("a sequence containing all of", self.matchers.describe())
    }
}

/// Matches a sequence in which every matcher in the tuple is satisfied by some
/// item (each matcher independently; one item may satisfy several).
///
/// On failure the error names the first matcher that no item satisfied.
///
/// ```
/// use test_better_core::TestResult;
/// use test_better_matchers::{contains_all, eq, check, gt};
///
/// fn main() -> TestResult {
///     check!(vec![1, 2, 3]).satisfies(contains_all((eq(1), gt(2))))?;
///     Ok(())
/// }
/// ```
#[must_use]
pub fn contains_all<C, Tup>(matchers: Tup) -> impl Matcher<C>
where
    C: Sequence + ?Sized,
    C::Item: fmt::Debug,
    Tup: ContainsAll<C::Item>,
{
    ContainsAllMatcher { matchers }
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeSet, HashSet, VecDeque};

    use test_better_core::{OrFail, TestResult};

    use super::*;
    use crate::{check, eq, gt, is_false, is_true, lt};

    #[test]
    fn have_len_matches_the_exact_length() -> TestResult {
        check!(have_len(3).check(&vec![1, 2, 3]).matched).satisfies(is_true())?;
        let failure = have_len(3)
            .check(&vec![1, 2])
            .failure
            .or_fail_with("length 2 is not 3")?;
        check!(failure.expected.to_string()).satisfies(eq("a sequence of length 3".to_string()))?;
        check!(failure.actual).satisfies(eq("a sequence of length 2".to_string()))?;
        Ok(())
    }

    #[test]
    fn items_collects_an_iterator_into_a_sequence() -> TestResult {
        // A lazy iterator wrapped by `items` behaves like a `Vec` under every
        // collection matcher: it has a length, it indexes, and `contains` /
        // `contains_in_order` produce the same failure shape they do on a
        // hand-collected `Vec<T>`.
        let lazy = (1..=3).map(|n| n * 10);
        let collected = items(lazy);
        check!(have_len(3).check(&collected).matched).satisfies(is_true())?;
        check!(contains(eq(20)).check(&collected).matched).satisfies(is_true())?;
        let failure = contains(eq(99))
            .check(&collected)
            .failure
            .or_fail_with("99 is not in the iterator")?;
        check!(failure.actual).satisfies(eq("[10, 20, 30]".to_string()))?;
        Ok(())
    }

    #[test]
    fn items_on_an_empty_iterator_is_empty() -> TestResult {
        let empty: Items<i32> = items(std::iter::empty());
        check!(is_empty().check(&empty).matched).satisfies(is_true())?;
        Ok(())
    }

    #[test]
    fn is_empty_and_is_not_empty_are_opposites() -> TestResult {
        check!(is_empty().check(&Vec::<i32>::new()).matched).satisfies(is_true())?;
        check!(is_empty().check(&vec![1]).matched).satisfies(is_false())?;
        check!(is_not_empty().check(&vec![1]).matched).satisfies(is_true())?;
        check!(is_not_empty().check(&Vec::<i32>::new()).matched).satisfies(is_false())?;
        Ok(())
    }

    #[test]
    fn contains_finds_a_matching_item() -> TestResult {
        check!(contains(eq(2)).check(&vec![1, 2, 3]).matched).satisfies(is_true())?;
        let failure = contains(eq(9))
            .check(&vec![1, 2, 3])
            .failure
            .or_fail_with("9 is not in the sequence")?;
        check!(failure.actual).satisfies(eq("[1, 2, 3]".to_string()))?;
        Ok(())
    }

    #[test]
    fn every_names_the_index_of_the_first_failure() -> TestResult {
        check!(every(gt(0)).check(&vec![1, 2, 3]).matched).satisfies(is_true())?;
        let failure = every(gt(0))
            .check(&vec![1, 2, -1, 4])
            .failure
            .or_fail_with("-1 is not greater than 0")?;
        check!(failure.actual.contains("index 2")).satisfies(is_true())?;
        Ok(())
    }

    #[test]
    fn at_least_one_matches_when_some_item_does() -> TestResult {
        check!(at_least_one(gt(2)).check(&vec![1, 2, 3]).matched).satisfies(is_true())?;
        check!(at_least_one(gt(9)).check(&vec![1, 2, 3]).matched).satisfies(is_false())?;
        Ok(())
    }

    #[test]
    fn contains_in_order_respects_order_but_not_adjacency() -> TestResult {
        check!(
            contains_in_order([eq(2), eq(4)])
                .check(&vec![1, 2, 3, 4])
                .matched
        )
        .satisfies(is_true())?;
        let failure = contains_in_order([eq(4), eq(2)])
            .check(&vec![1, 2, 3, 4])
            .failure
            .or_fail_with("2 does not come after 4")?;
        check!(failure.actual.contains("matcher at index 1")).satisfies(is_true())?;
        Ok(())
    }

    #[test]
    fn contains_all_requires_every_matcher_to_be_satisfied() -> TestResult {
        check!(contains_all((eq(1), gt(2))).check(&vec![1, 2, 3]).matched).satisfies(is_true())?;
        let failure = contains_all((eq(1), gt(9)))
            .check(&vec![1, 2, 3])
            .failure
            .or_fail_with("nothing is greater than 9")?;
        check!(failure.expected.to_string().contains("greater than 9")).satisfies(is_true())?;
        Ok(())
    }

    #[test]
    fn collection_matchers_work_across_collection_types() -> TestResult {
        let deque: VecDeque<i32> = VecDeque::from(vec![1, 2, 3]);
        check!(have_len(3).check(&deque).matched).satisfies(is_true())?;

        let btree: BTreeSet<i32> = BTreeSet::from([1, 2, 3]);
        check!(contains(eq(2)).check(&btree).matched).satisfies(is_true())?;

        let set: HashSet<i32> = HashSet::from([1, 2, 3]);
        check!(every(gt(0)).check(&set).matched).satisfies(is_true())?;

        let slice: &[i32] = &[10, 20, 30];
        check!(contains_in_order([eq(10), eq(30)]).check(&slice).matched).satisfies(is_true())?;

        let array = [1, 2, 3];
        check!(every(lt(4)).check(&array).matched).satisfies(is_true())?;
        Ok(())
    }
}