assertables/assert_is_match/
assert_not_match.rs

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