assertables/assert_none/
assert_none.rs

1//! Assert expression is None.
2//!
3//! Pseudocode:<br>
4//! a is None
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a: Option<i8> = Option::None;
12//! assert_none!(a);
13//! ```
14//!
15//! # Module macros
16//!
17//! * [`assert_none`](macro@crate::assert_none)
18//! * [`assert_none_as_result`](macro@crate::assert_none_as_result)
19//! * [`debug_assert_none`](macro@crate::debug_assert_none)
20
21/// Assert an expression is None.
22///
23/// Pseudocode:<br>
24/// a is None
25///
26/// * If true, return Result `Ok(())`.
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_none`](macro@crate::assert_none)
36/// * [`assert_none_as_result`](macro@crate::assert_none_as_result)
37/// * [`debug_assert_none`](macro@crate::debug_assert_none)
38///
39#[macro_export]
40macro_rules! assert_none_as_result {
41    ($a:expr $(,)?) => {{
42        match (&$a) {
43            a => {
44                match (a) {
45                    None => {
46                        Ok(())
47                    },
48                    _ => {
49                        Err(
50                            format!(
51                                concat!(
52                                    "assertion failed: `assert_none!(a)`\n",
53                                    "https://docs.rs/assertables/9.5.6/assertables/macro.assert_none.html\n",
54                                    " a label: `{}`,\n",
55                                    " a debug: `{:?}`",
56                                ),
57                                stringify!($a),
58                                a
59                            )
60                        )
61                    }
62                }
63            }
64        }
65    }};
66}
67
68#[cfg(test)]
69mod test_assert_none_as_result {
70    use std::sync::Once;
71
72    #[test]
73    fn success() {
74        let a: Option<i8> = Option::None;
75        let actual = assert_none_as_result!(a);
76        assert_eq!(actual.unwrap(), ());
77    }
78
79    #[test]
80    fn failure() {
81        let a: Option<i8> = Option::Some(1);
82        let actual = assert_none_as_result!(a);
83        let message = concat!(
84            "assertion failed: `assert_none!(a)`\n",
85            "https://docs.rs/assertables/9.5.6/assertables/macro.assert_none.html\n",
86            " a label: `a`,\n",
87            " a debug: `Some(1)`",
88        );
89        assert_eq!(actual.unwrap_err(), message);
90    }
91}
92
93/// Assert expression is None.
94///
95/// Pseudocode:<br>
96/// a is None
97///
98/// * If true, return `()`.
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: Option<i8> = Option::None;
111/// assert_none!(a);
112///
113/// # let result = panic::catch_unwind(|| {
114/// // This will panic
115/// let a: Option<i8> = Option::Some(1);
116/// assert_none!(a);
117/// # });
118/// // assertion failed: `assert_none!(a)`
119/// // https://docs.rs/assertables/9.5.6/assertables/macro.assert_none.html
120/// //  a label: `a`,
121/// //  a debug: `Some(1)`
122/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
123/// # let message = concat!(
124/// #     "assertion failed: `assert_none!(a)`\n",
125/// #     "https://docs.rs/assertables/9.5.6/assertables/macro.assert_none.html\n",
126/// #     " a label: `a`,\n",
127/// #     " a debug: `Some(1)`",
128/// # );
129/// # assert_eq!(actual, message);
130/// # }
131/// ```
132///
133/// # Module macros
134///
135/// * [`assert_none`](macro@crate::assert_none)
136/// * [`assert_none_as_result`](macro@crate::assert_none_as_result)
137/// * [`debug_assert_none`](macro@crate::debug_assert_none)
138///
139#[macro_export]
140macro_rules! assert_none {
141    ($a:expr $(,)?) => {{
142        match $crate::assert_none_as_result!($a) {
143            Ok(x) => x,
144            Err(err) => panic!("{}", err),
145        }
146    }};
147    ($a:expr, $($message:tt)+) => {{
148        match $crate::assert_none_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_none {
157    use std::panic;
158
159    #[test]
160    fn success() {
161        let a: Option<i8> = Option::None;
162        let actual = assert_none!(a);
163        assert_eq!(actual, ());
164    }
165
166    #[test]
167    fn failure() {
168        let a: Option<i8> = Option::Some(1);
169        let result = panic::catch_unwind(|| {
170            let _actual = assert_none!(a);
171        });
172        let message = concat!(
173            "assertion failed: `assert_none!(a)`\n",
174            "https://docs.rs/assertables/9.5.6/assertables/macro.assert_none.html\n",
175            " a label: `a`,\n",
176            " a debug: `Some(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 None.
190///
191/// Pseudocode:<br>
192/// a is None
193///
194/// This macro provides the same statements as [`assert_none`](macro.assert_none.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_none`](macro@crate::assert_none)
217/// * [`assert_none`](macro@crate::assert_none)
218/// * [`debug_assert_none`](macro@crate::debug_assert_none)
219///
220#[macro_export]
221macro_rules! debug_assert_none {
222    ($($arg:tt)*) => {
223        if $crate::cfg!(debug_assertions) {
224            $crate::assert_none!($($arg)*);
225        }
226    };
227}