assertables/assert_success/
assert_success.rs

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