xpct/format/
len.rs

1use std::fmt;
2
3use crate::core::Matcher;
4use crate::matchers::collections::{BeEmptyMatcher, HaveLenMatcher, Len};
5
6use super::{ExpectationFormat, MismatchFormat};
7
8/// Succeeds when the actual value has the given length.
9///
10/// You can use this matcher for your own types by implementing [`Len`] on them.
11///
12/// # Examples
13///
14/// ```
15/// use xpct::{expect, have_len};
16///
17/// expect!("foo").to(have_len(3));
18/// expect!(&vec!["bar"]).to(have_len(1));
19/// ```
20pub fn have_len<'a, Actual>(len: usize) -> Matcher<'a, Actual, Actual>
21where
22    Actual: fmt::Debug + Len + 'a,
23{
24    Matcher::new(
25        HaveLenMatcher::new(len),
26        MismatchFormat::new("to have length", "to not have length"),
27    )
28}
29
30/// Succeeds when the actual value is empty.
31///
32/// You can use this matcher for your own types by implementing [`Len`] on them.
33///
34/// # Examples
35///
36/// ```
37/// use xpct::{expect, be_empty};
38///
39/// expect!("").to(be_empty());
40/// expect!(&Vec::<()>::new()).to(be_empty());
41/// ```
42pub fn be_empty<'a, Actual>() -> Matcher<'a, Actual, Actual>
43where
44    Actual: fmt::Debug + Len + 'a,
45{
46    Matcher::new(
47        BeEmptyMatcher::new(),
48        ExpectationFormat::new("to be empty", "to not be empty"),
49    )
50}
51
52#[cfg(test)]
53mod tests {
54    use super::{be_empty, have_len};
55    use crate::expect;
56
57    #[test]
58    fn succeeds_when_has_len() {
59        expect!(&vec!["foo"]).to(have_len(1));
60    }
61
62    #[test]
63    fn succeeds_when_not_has_len() {
64        expect!(&vec!["foo"]).to_not(have_len(100));
65    }
66
67    #[test]
68    #[should_panic]
69    fn fails_when_has_len() {
70        expect!(&vec!["foo"]).to_not(have_len(1));
71    }
72
73    #[test]
74    #[should_panic]
75    fn fails_when_not_has_len() {
76        expect!(&vec!["foo"]).to(have_len(100));
77    }
78
79    #[test]
80    fn succeeds_when_is_empty() {
81        expect!(&Vec::<&'static str>::new()).to(be_empty());
82    }
83
84    #[test]
85    fn succeeds_when_not_empty() {
86        expect!(&vec!["foo"]).to_not(be_empty());
87    }
88
89    #[test]
90    #[should_panic]
91    fn fails_when_is_empty() {
92        expect!(&Vec::<&'static str>::new()).to_not(be_empty());
93    }
94
95    #[test]
96    #[should_panic]
97    fn fails_when_not_empty() {
98        expect!(&vec!["foo"]).to(be_empty());
99    }
100}