assertables/
assert_all.rs

1//! Assert every element of the iterator matches a predicate.
2//!
3//! Pseudocode:<br>
4//! collection into iter ∀ predicate
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a = [1, 2, 3];
12//! assert_all!(a.into_iter(), |x: i8| x > 0);
13//! ```
14//!
15//! This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
16//!
17//! # Module macros
18//!
19//! * [`assert_all`](macro@crate::assert_all)
20//! * [`assert_all_as_result`](macro@crate::assert_all_as_result)
21//! * [`debug_assert_all`](macro@crate::debug_assert_all)
22
23/// Assert every element of the iterator matches a predicate.
24///
25/// Pseudocode:<br>
26/// collection into iter ∀ predicate
27///
28/// * If true, return Result `Ok(())`.
29///
30/// * Otherwise, return Result `Err(message)`.
31///
32/// This macro is useful for runtime checks, such as checking parameters,
33/// or sanitizing inputs, or handling different results in different ways.
34///
35/// This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
36///
37/// # Module macros
38///
39/// * [`assert_all`](macro@crate::assert_all)
40/// * [`assert_all_as_result`](macro@crate::assert_all_as_result)
41/// * [`debug_assert_all`](macro@crate::debug_assert_all)
42///
43#[macro_export]
44macro_rules! assert_all_as_result {
45    ($collection:expr, $predicate:expr $(,)?) => {
46        match ($collection, $predicate) {
47            (mut collection, predicate) => {
48                if collection.all(predicate) {
49                    Ok(())
50                } else {
51                    Err(format!(
52                        concat!(
53                            "assertion failed: `assert_all!(collection, predicate)`\n",
54                            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_all.html\n",
55                            " collection label: `{}`,\n",
56                            " collection debug: `{:?}`,\n",
57                            "        predicate: `{}`"
58                        ),
59                        stringify!($collection),
60                        $collection,
61                        stringify!($predicate)
62                    ))
63                }
64            }
65        }
66    };
67}
68
69#[cfg(test)]
70mod test_assert_all_as_result {
71    use std::sync::Once;
72
73    #[test]
74    fn success() {
75        let a = [1, 2, 3];
76        for _ in 0..1 {
77            let actual = assert_all_as_result!(a.into_iter(), |x: i8| x > 0);
78            assert_eq!(actual.unwrap(), ());
79        }
80    }
81    #[test]
82    fn success_once() {
83        static A: Once = Once::new();
84        fn a() -> [i8; 3] {
85            if A.is_completed() {
86                panic!("A.is_completed()")
87            } else {
88                A.call_once(|| {})
89            }
90            [1, 2, 3]
91        }
92
93        assert_eq!(A.is_completed(), false);
94        let result = assert_all_as_result!(a().into_iter(), |x: i8| x > 0);
95        assert!(result.is_ok());
96        assert_eq!(A.is_completed(), true);
97    }
98
99    #[test]
100    fn failure() {
101        let a = [1, -2, 3];
102        let actual = assert_all_as_result!(a.into_iter(), |x: i8| x > 0);
103        let message = concat!(
104            "assertion failed: `assert_all!(collection, predicate)`\n",
105            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_all.html\n",
106            " collection label: `a.into_iter()`,\n",
107            " collection debug: `IntoIter([1, -2, 3])`,\n",
108            "        predicate: `|x: i8| x > 0`"
109        );
110        assert_eq!(actual.unwrap_err(), message);
111    }
112}
113
114/// Assert every element of the iterator matches a predicate.
115///
116/// Pseudocode:<br>
117/// collection into iter ∀ predicate
118///
119/// * If true, return `()`.
120///
121/// * Otherwise, call [`panic!`] with a message and the values of the
122///   expressions with their debug representations.
123///
124/// # Examples
125///
126/// ```rust
127/// use assertables::*;
128/// # use std::panic;
129///
130/// # fn main() {
131/// let a = [1, 2, 3];
132/// assert_all!(a.into_iter(), |x: i8| x > 0);
133///
134/// # let result = panic::catch_unwind(|| {
135/// // This will panic
136/// let a = [1, -2, 3];
137/// assert_all!(a.into_iter(), |x: i8| x > 0);
138/// # });
139/// // assertion failed: `assert_all!(collection, predicate)`
140/// // https://docs.rs/assertables/…/assertables/macro.assert_all.html
141/// //  collection label: `a.into_iter()`,
142/// //  collection debug: `IntoIter([1, -2, 3])`,
143/// //         predicate: `|x: i8| x > 0`
144/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
145/// # let message = concat!(
146/// #     "assertion failed: `assert_all!(collection, predicate)`\n",
147/// #     "https://docs.rs/assertables/9.8.2/assertables/macro.assert_all.html\n",
148/// #     " collection label: `a.into_iter()`,\n",
149/// #     " collection debug: `IntoIter([1, -2, 3])`,\n",
150/// #     "        predicate: `|x: i8| x > 0`",
151/// # );
152/// # assert_eq!(actual, message);
153/// # }
154/// ```
155///
156/// This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
157///
158/// # Module macros
159///
160/// * [`assert_all`](macro@crate::assert_all)
161/// * [`assert_all_as_result`](macro@crate::assert_all_as_result)
162/// * [`debug_assert_all`](macro@crate::debug_assert_all)
163///
164#[macro_export]
165macro_rules! assert_all {
166    ($collection:expr, $predicate:expr $(,)?) => {
167        match $crate::assert_all_as_result!($collection, $predicate) {
168            Ok(()) => (),
169            Err(err) => panic!("{}", err),
170        }
171    };
172    ($collection:expr, $predicate:expr, $($message:tt)+) => {
173        match $crate::assert_all_as_result!($collection, $predicate) {
174            Ok(()) => (),
175            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
176        }
177    };
178}
179
180#[cfg(test)]
181mod test_assert_all {
182    use std::panic;
183
184    #[test]
185    fn success() {
186        let a = [1, 2, 3];
187        for _ in 0..1 {
188            let actual = assert_all!(a.into_iter(), |x: i8| x > 0);
189            assert_eq!(actual, ());
190        }
191    }
192
193    #[test]
194    fn failure() {
195        let a = [1, -2, 3];
196        let result = panic::catch_unwind(|| {
197            let _actual = assert_all!(a.into_iter(), |x: i8| x > 0);
198        });
199        let message = concat!(
200            "assertion failed: `assert_all!(collection, predicate)`\n",
201            "https://docs.rs/assertables/9.8.2/assertables/macro.assert_all.html\n",
202            " collection label: `a.into_iter()`,\n",
203            " collection debug: `IntoIter([1, -2, 3])`,\n",
204            "        predicate: `|x: i8| x > 0`"
205        );
206        assert_eq!(
207            result
208                .unwrap_err()
209                .downcast::<String>()
210                .unwrap()
211                .to_string(),
212            message
213        );
214    }
215}
216
217/// Assert every element of the iterator matches a predicate.
218///
219/// Pseudocode:<br>
220/// collection into iter ∀ predicate
221///
222/// This macro provides the same statements as [`assert_all`](macro.assert_all.html),
223/// except this macro's statements are only enabled in non-optimized
224/// builds by default. An optimized build will not execute this macro's
225/// statements unless `-C debug-assertions` is passed to the compiler.
226///
227/// This macro is useful for checks that are too expensive to be present
228/// in a release build but may be helpful during development.
229///
230/// The result of expanding this macro is always type checked.
231///
232/// An unchecked assertion allows a program in an inconsistent state to
233/// keep running, which might have unexpected consequences but does not
234/// introduce unsafety as long as this only happens in safe code. The
235/// performance cost of assertions, however, is not measurable in general.
236/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
237/// after thorough profiling, and more importantly, only in safe code!
238///
239/// This macro is intended to work in a similar way to
240/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
241///
242/// # Module macros
243///
244/// * [`assert_all`](macro@crate::assert_all)
245/// * [`assert_all`](macro@crate::assert_all)
246/// * [`debug_assert_all`](macro@crate::debug_assert_all)
247///
248#[macro_export]
249macro_rules! debug_assert_all {
250    ($($arg:tt)*) => {
251        if $crate::cfg!(debug_assertions) {
252            $crate::assert_all!($($arg)*);
253        }
254    };
255}