assertables/assert_err/
assert_err.rs

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