assertables/assert_err/
assert_err_ne.rs

1//! Assert two expressions are Err and their values are not equal.
2//!
3//! Pseudocode:<br>
4//! (a ⇒ Err(a1) ⇒ a1) ≠ (b ⇒ Err(b1) ⇒ b1)
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a: Result<i8, i8> = Err(1);
12//! let b: Result<i8, i8> = Err(2);
13//! assert_err_ne!(a, b);
14//! ```
15//!
16//! # Module macros
17//!
18//! * [`assert_err_ne`](macro@crate::assert_err_ne)
19//! * [`assert_err_ne_as_result`](macro@crate::assert_err_ne_as_result)
20//! * [`debug_assert_err_ne`](macro@crate::debug_assert_err_ne)
21
22/// Assert two expressions are Err and their values are not equal.
23///
24/// Pseudocode:<br>
25/// (a ⇒ Err(a1) ⇒ a1) ≠ (b ⇒ Err(b1) ⇒ b1)
26///
27/// * If true, return Result `Ok((a1, b1))`.
28///
29/// * Otherwise, return Result `Err(message)`.
30///
31/// This macro is useful for runtime checks, such as checking parameters,
32/// or sanitizing inputs, or handling different results in different ways.
33///
34/// # Module macros
35///
36/// * [`assert_err_ne`](macro@crate::assert_err_ne)
37/// * [`assert_err_ne_as_result`](macro@crate::assert_err_ne_as_result)
38/// * [`debug_assert_err_ne`](macro@crate::debug_assert_err_ne)
39///
40#[macro_export]
41macro_rules! assert_err_ne_as_result {
42    ($a:expr, $b:expr $(,)?) => {
43        match ($a, $b) {
44            (a, b) => match (a, b) {
45                (Err(a1), Err(b1)) => {
46                    if a1 != b1 {
47                        Ok((a1, b1))
48                    } else {
49                        Err(format!(
50                            concat!(
51                                "assertion failed: `assert_err_ne!(a, b)`\n",
52                                "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
53                                " a label: `{}`,\n",
54                                " a debug: `{:?}`,\n",
55                                " a inner: `{:?}`,\n",
56                                " b label: `{}`,\n",
57                                " b debug: `{:?}`,\n",
58                                " b inner: `{:?}`"
59                            ),
60                            stringify!($a),
61                            a,
62                            a1,
63                            stringify!($b),
64                            b,
65                            b1
66                        ))
67                    }
68                }
69                _ => Err(format!(
70                    concat!(
71                        "assertion failed: `assert_err_ne!(a, b)`\n",
72                        "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
73                        " a label: `{}`,\n",
74                        " a debug: `{:?}`,\n",
75                        " b label: `{}`,\n",
76                        " b debug: `{:?}`",
77                    ),
78                    stringify!($a),
79                    a,
80                    stringify!($b),
81                    b,
82                )),
83            },
84        }
85    };
86}
87
88#[cfg(test)]
89mod test_assert_err_ne_as_result {
90    use std::sync::Once;
91
92    #[test]
93    fn lt() {
94        let a: Result<i8, i8> = Err(1);
95        let b: Result<i8, i8> = Err(2);
96        for _ in 0..1 {
97            let actual = assert_err_ne_as_result!(a, b);
98            assert_eq!(actual.unwrap(), (1, 2));
99        }
100    }
101
102    #[test]
103    fn lt_once() {
104        static A: Once = Once::new();
105        fn a() -> Result<i8, i8> {
106            if A.is_completed() {
107                panic!("A.is_completed()")
108            } else {
109                A.call_once(|| {})
110            }
111            Err(1)
112        }
113
114        static B: Once = Once::new();
115        fn b() -> Result<i8, i8> {
116            if B.is_completed() {
117                panic!("B.is_completed()")
118            } else {
119                B.call_once(|| {})
120            }
121            Err(2)
122        }
123
124        assert_eq!(A.is_completed(), false);
125        assert_eq!(B.is_completed(), false);
126        let result = assert_err_ne_as_result!(a(), b());
127        assert!(result.is_ok());
128        assert_eq!(A.is_completed(), true);
129        assert_eq!(B.is_completed(), true);
130    }
131
132    #[test]
133    fn gt() {
134        let a: Result<i8, i8> = Err(2);
135        let b: Result<i8, i8> = Err(1);
136        for _ in 0..1 {
137            let actual = assert_err_ne_as_result!(a, b);
138            assert_eq!(actual.unwrap(), (2, 1));
139        }
140    }
141
142    #[test]
143    fn gt_once() {
144        static A: Once = Once::new();
145        fn a() -> Result<i8, i8> {
146            if A.is_completed() {
147                panic!("A.is_completed()")
148            } else {
149                A.call_once(|| {})
150            }
151            Err(2)
152        }
153
154        static B: Once = Once::new();
155        fn b() -> Result<i8, i8> {
156            if B.is_completed() {
157                panic!("B.is_completed()")
158            } else {
159                B.call_once(|| {})
160            }
161            Err(1)
162        }
163
164        assert_eq!(A.is_completed(), false);
165        assert_eq!(B.is_completed(), false);
166        let result = assert_err_ne_as_result!(a(), b());
167        assert!(result.is_ok());
168        assert_eq!(A.is_completed(), true);
169        assert_eq!(B.is_completed(), true);
170    }
171
172    #[test]
173    fn eq() {
174        let a: Result<i8, i8> = Err(1);
175        let b: Result<i8, i8> = Err(1);
176        let actual = assert_err_ne_as_result!(a, b);
177        let message = concat!(
178            "assertion failed: `assert_err_ne!(a, b)`\n",
179            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
180            " a label: `a`,\n",
181            " a debug: `Err(1)`,\n",
182            " a inner: `1`,\n",
183            " b label: `b`,\n",
184            " b debug: `Err(1)`,\n",
185            " b inner: `1`",
186        );
187        assert_eq!(actual.unwrap_err(), message);
188    }
189
190    #[test]
191    fn failure_because_not_err() {
192        let a: Result<i8, i8> = Ok(1);
193        let b: Result<i8, i8> = Err(1);
194        let actual = assert_err_ne_as_result!(a, b);
195        let message = concat!(
196            "assertion failed: `assert_err_ne!(a, b)`\n",
197            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
198            " a label: `a`,\n",
199            " a debug: `Ok(1)`,\n",
200            " b label: `b`,\n",
201            " b debug: `Err(1)`",
202        );
203        assert_eq!(actual.unwrap_err(), message);
204    }
205}
206
207/// Assert two expressions are Err and their values are not equal.
208///
209/// Pseudocode:<br>
210/// (a ⇒ Err(a1) ⇒ a1) ≠ (b ⇒ Err(b1) ⇒ b1)
211///
212/// * If true, return `(a1, b1)`.
213///
214/// * Otherwise, call [`panic!`] with a message and the values of the
215///   expressions with their debug representations.
216///
217/// # Examples
218///
219/// ```rust
220/// use assertables::*;
221/// # use std::panic;
222///
223/// # fn main() {
224/// let a: Result<i8, i8> = Err(1);
225/// let b: Result<i8, i8> = Err(2);
226/// assert_err_ne!(a, b);
227///
228/// # let result = panic::catch_unwind(|| {
229/// // This will panic
230/// let a: Result<i8, i8> = Err(1);
231/// let b: Result<i8, i8> = Err(1);
232/// assert_err_ne!(a, b);
233/// # });
234/// // assertion failed: `assert_err_ne!(a, b)`
235/// // https://docs.rs/assertables/…/assertables/macro.assert_err_ne.html
236/// //  a label: `a`,
237/// //  a debug: `Err(1)`,
238/// //  a inner: `1`,
239/// //  b label: `b`,
240/// //  b debug: `Err(1)`,
241/// //  b inner: `1`
242/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
243/// # let message = concat!(
244/// #     "assertion failed: `assert_err_ne!(a, b)`\n",
245/// #     "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
246/// #     " a label: `a`,\n",
247/// #     " a debug: `Err(1)`,\n",
248/// #     " a inner: `1`,\n",
249/// #     " b label: `b`,\n",
250/// #     " b debug: `Err(1)`,\n",
251/// #     " b inner: `1`",
252/// # );
253/// # assert_eq!(actual, message);
254/// # }
255/// ```
256///
257/// # Module macros
258///
259/// * [`assert_err_ne`](macro@crate::assert_err_ne)
260/// * [`assert_err_ne_as_result`](macro@crate::assert_err_ne_as_result)
261/// * [`debug_assert_err_ne`](macro@crate::debug_assert_err_ne)
262///
263#[macro_export]
264macro_rules! assert_err_ne {
265    ($a:expr, $b:expr $(,)?) => {
266        match $crate::assert_err_ne_as_result!($a, $b) {
267            Ok(x) => x,
268            Err(err) => panic!("{}", err),
269        }
270    };
271    ($a:expr, $b:expr, $($message:tt)+) => {
272        match $crate::assert_err_ne_as_result!($a, $b) {
273            Ok(x) => x,
274            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
275        }
276    };
277}
278
279#[cfg(test)]
280mod test_assert_err_ne {
281    use std::panic;
282
283    #[test]
284    fn success() {
285        let a: Result<i8, i8> = Err(1);
286        let b: Result<i8, i8> = Err(2);
287        for _ in 0..1 {
288            let actual = assert_err_ne!(a, b);
289            assert_eq!(actual, (1, 2));
290        }
291    }
292
293    #[test]
294    fn eq() {
295        let result = panic::catch_unwind(|| {
296            let a: Result<i8, i8> = Err(1);
297            let b: Result<i8, i8> = Err(1);
298            let _actual = assert_err_ne!(a, b);
299        });
300        let message = concat!(
301            "assertion failed: `assert_err_ne!(a, b)`\n",
302            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
303            " a label: `a`,\n",
304            " a debug: `Err(1)`,\n",
305            " a inner: `1`,\n",
306            " b label: `b`,\n",
307            " b debug: `Err(1)`,\n",
308            " b inner: `1`",
309        );
310        assert_eq!(
311            result
312                .unwrap_err()
313                .downcast::<String>()
314                .unwrap()
315                .to_string(),
316            message
317        );
318    }
319
320    #[test]
321    fn failure_because_not_err() {
322        let result = panic::catch_unwind(|| {
323            let a: Result<i8, i8> = Ok(1);
324            let b: Result<i8, i8> = Err(1);
325            let _actual = assert_err_ne!(a, b);
326        });
327        let message = concat!(
328            "assertion failed: `assert_err_ne!(a, b)`\n",
329            "https://docs.rs/assertables/9.8.3/assertables/macro.assert_err_ne.html\n",
330            " a label: `a`,\n",
331            " a debug: `Ok(1)`,\n",
332            " b label: `b`,\n",
333            " b debug: `Err(1)`",
334        );
335        assert_eq!(
336            result
337                .unwrap_err()
338                .downcast::<String>()
339                .unwrap()
340                .to_string(),
341            message
342        );
343    }
344}
345
346/// Assert two expressions are Err and their values are not equal.
347///
348/// This macro provides the same statements as [`assert_err_ne`](macro.assert_err_ne.html),
349/// except this macro's statements are only enabled in non-optimized
350/// builds by default. An optimized build will not execute this macro's
351/// statements unless `-C debug-assertions` is passed to the compiler.
352///
353/// This macro is useful for checks that are too expensive to be present
354/// in a release build but may be helpful during development.
355///
356/// The result of expanding this macro is always type checked.
357///
358/// An unchecked assertion allows a program in an inconsistent state to
359/// keep running, which might have unexpected consequences but does not
360/// introduce unsafety as long as this only happens in safe code. The
361/// performance cost of assertions, however, is not measurable in general.
362/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
363/// after thorough profiling, and more importantly, only in safe code!
364///
365/// This macro is intended to work in a similar way to
366/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
367///
368/// # Module macros
369///
370/// * [`assert_err_ne`](macro@crate::assert_err_ne)
371/// * [`assert_err_ne`](macro@crate::assert_err_ne)
372/// * [`debug_assert_err_ne`](macro@crate::debug_assert_err_ne)
373///
374#[macro_export]
375macro_rules! debug_assert_err_ne {
376    ($($arg:tt)*) => {
377        if $crate::cfg!(debug_assertions) {
378            $crate::assert_err_ne!($($arg)*);
379        }
380    };
381}