Skip to main content

assertables/assert_fn/
assert_fn_eq_x.rs

1//! Assert a function output is equal to an expression.
2//!
3//! Pseudocode:<br>
4//! function(a) = b
5//!
6//! # Example
7//!
8//! ```rust
9//! use assertables::*;
10//!
11//! let a: i8 = -1;
12//! let b: i8 = 1;
13//! assert_fn_eq_x!(i8::abs, a, b);
14//! ```
15//!
16//! # Module macros
17//!
18//! * [`assert_fn_eq_x`](macro@crate::assert_fn_eq_x)
19//! * [`assert_fn_eq_x_as_result`](macro@crate::assert_fn_eq_x_as_result)
20//! * [`debug_assert_fn_eq_x`](macro@crate::debug_assert_fn_eq_x)
21
22/// Assert a function output is equal to an expression.
23///
24/// Pseudocode:<br>
25/// function(a) = b
26///
27/// * If true, return Result `Ok(a)`.
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_fn_eq_x`](macro@crate::assert_fn_eq_x)
37/// * [`assert_fn_eq_x_as_result`](macro@crate::assert_fn_eq_x_as_result)
38/// * [`debug_assert_fn_eq_x`](macro@crate::debug_assert_fn_eq_x)
39///
40#[macro_export]
41macro_rules! assert_fn_eq_x_as_result {
42    //// Arity 1
43    ($a_function:path, $a_param:expr, $b_expr:expr $(,)?) => {
44        match (&$a_function, &$a_param, &$b_expr) {
45            (_a_function, a_param, b_expr) => {
46                let a = $a_function($a_param);
47                if a == $b_expr {
48                    Ok(a)
49                } else {
50                    Err(format!(
51                        concat!(
52                            "assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`\n",
53                            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
54                            " a_function label: `{}`,\n",
55                            "    a_param label: `{}`,\n",
56                            "    a_param debug: `{:?}`,\n",
57                            "     b_expr label: `{}`,\n",
58                            "     b_expr debug: `{:?}`,\n",
59                            "                a: `{:?}`,\n",
60                            "                b: `{:?}`"
61                        ),
62                        stringify!($a_function),
63                        stringify!($a_param),
64                        a_param,
65                        stringify!($b_expr),
66                        b_expr,
67                        a,
68                        b_expr
69                    ))
70                }
71            }
72        }
73    };
74
75    //// Arity 0
76    ($a_function:path, $b_expr:expr $(,)?) => {
77        match (&$a_function, &$b_expr) {
78            (_a_function, b_expr) => {
79                let a = $a_function();
80                if a == $b_expr {
81                    Ok(a)
82                } else {
83                    Err(format!(
84                        concat!(
85                            "assertion failed: `assert_fn_eq_x!(a_function, b_expr)`\n",
86                            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
87                            " a_function label: `{}`,\n",
88                            "     b_expr label: `{}`,\n",
89                            "     b_expr debug: `{:?}`,\n",
90                            "                a: `{:?}`,\n",
91                            "                b: `{:?}`"
92                        ),
93                        stringify!($a_function),
94                        stringify!($b_expr),
95                        b_expr,
96                        a,
97                        b_expr
98                    ))
99                }
100            }
101        }
102    };
103}
104
105#[cfg(test)]
106mod test_assert_fn_eq_x_as_result {
107    // use std::sync::Once;
108
109    mod arity_1 {
110
111        fn f(i: i8) -> i8 {
112            return i;
113        }
114
115        #[test]
116        fn eq() {
117            let a: i8 = 1;
118            let b: i8 = 1;
119            for _ in 0..1 {
120                let actual = assert_fn_eq_x_as_result!(f, a, b);
121                assert_eq!(actual.unwrap(), 1);
122            }
123        }
124
125        #[test]
126        fn failure() {
127            let a: i8 = 1;
128            let b: i8 = 2;
129            let actual = assert_fn_eq_x_as_result!(f, a, b);
130            let message = concat!(
131                "assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`\n",
132                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
133                " a_function label: `f`,\n",
134                "    a_param label: `a`,\n",
135                "    a_param debug: `1`,\n",
136                "     b_expr label: `b`,\n",
137                "     b_expr debug: `2`,\n",
138                "                a: `1`,\n",
139                "                b: `2`"
140            );
141            assert_eq!(actual.unwrap_err(), message);
142        }
143    }
144
145    mod arity_0 {
146
147        fn f() -> i8 {
148            return 1;
149        }
150
151        #[test]
152        fn eq() {
153            let b: i8 = 1;
154            for _ in 0..1 {
155                let actual = assert_fn_eq_x_as_result!(f, b);
156                assert_eq!(actual.unwrap(), 1);
157            }
158        }
159
160        #[test]
161        fn ne() {
162            let b: i8 = 2;
163            let actual = assert_fn_eq_x_as_result!(f, b);
164            let message = concat!(
165                "assertion failed: `assert_fn_eq_x!(a_function, b_expr)`\n",
166                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
167                " a_function label: `f`,\n",
168                "     b_expr label: `b`,\n",
169                "     b_expr debug: `2`,\n",
170                "                a: `1`,\n",
171                "                b: `2`"
172            );
173            assert_eq!(actual.unwrap_err(), message);
174        }
175    }
176}
177
178/// Assert a function output is equal to an expression.
179///
180/// Pseudocode:<br>
181/// function(a) = b
182///
183/// * If true, return `a`.
184///
185/// * Otherwise, call [`panic!`] with a message and the values of the
186///   expressions with their debug representations.
187///
188/// # Examples
189///
190/// ```rust
191/// use assertables::*;
192/// # use std::panic;
193///
194/// # fn main() {
195/// let a: i8 = -1;
196/// let b: i8 = 1;
197/// assert_fn_eq_x!(i8::abs, a, b);
198///
199/// # let result = panic::catch_unwind(|| {
200/// // This will panic
201/// let a: i8 = -1;
202/// let b: i8 = 2;
203/// assert_fn_eq_x!(i8::abs, a, b);
204/// # });
205/// // assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`
206/// // https://docs.rs/assertables/…/assertables/macro.assert_fn_eq_x.html
207/// //  a_function label: `i8::abs`,
208/// //     a_param label: `a`,
209/// //     a_param debug: `-1`,
210/// //      b_expr label: `b`,
211/// //      b_expr debug: `2`,
212/// //                 a: `1`,
213/// //                 b: `2`
214/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
215/// # let message = concat!(
216/// #     "assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`\n",
217/// #     "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
218/// #     " a_function label: `i8::abs`,\n",
219/// #     "    a_param label: `a`,\n",
220/// #     "    a_param debug: `-1`,\n",
221/// #     "     b_expr label: `b`,\n",
222/// #     "     b_expr debug: `2`,\n",
223/// #     "                a: `1`,\n",
224/// #     "                b: `2`"
225/// # );
226/// # assert_eq!(actual, message);
227/// # }
228/// ```
229///
230/// # Module macros
231///
232/// * [`assert_fn_eq_x`](macro@crate::assert_fn_eq_x)
233/// * [`assert_fn_eq_x_as_result`](macro@crate::assert_fn_eq_x_as_result)
234/// * [`debug_assert_fn_eq_x`](macro@crate::debug_assert_fn_eq_x)
235///
236#[macro_export]
237macro_rules! assert_fn_eq_x {
238
239    //// Arity 1
240
241    ($a_function:path, $a_param:expr, $b_expr:expr $(,)?) => {
242        match $crate::assert_fn_eq_x_as_result!($a_function, $a_param, $b_expr) {
243            Ok(x) => x,
244            Err(err) => panic!("{}", err),
245        }
246    };
247
248    ($a_function:path, $a_param:expr, $b_expr:expr, $($message:tt)+) => {
249        match $crate::assert_fn_eq_x_as_result!($a_function, $a_param, $b_expr) {
250            Ok(x) => x,
251            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
252        }
253    };
254
255    //// Arity 0
256
257    ($a_function:path, $b_expr:expr $(,)?) => {
258        match $crate::assert_fn_eq_x_as_result!($a_function, $b_expr) {
259            Ok(x) => x,
260            Err(err) => panic!("{}", err),
261        }
262    };
263
264    ($a_function:path, $b_expr:expr, $($message:tt)+) => {
265        match $crate::assert_fn_eq_x_as_result!($a_function, $a_param, $b_expr) {
266            Ok(x) => x,
267            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
268        }
269    };
270
271}
272
273#[cfg(test)]
274mod test_assert_fn_eq_x {
275    use std::panic;
276
277    mod arity_1 {
278        use super::*;
279
280        fn f(i: i8) -> i8 {
281            return i;
282        }
283
284        #[test]
285        fn eq() {
286            let a: i8 = 1;
287            let b: i8 = 1;
288            for _ in 0..1 {
289                let actual = assert_fn_eq_x!(f, a, b);
290                let expect = 1;
291                assert_eq!(actual, expect);
292            }
293        }
294
295        #[test]
296        fn failure() {
297            let result = panic::catch_unwind(|| {
298                let a: i8 = 1;
299                let b: i8 = 2;
300                let _actual = assert_fn_eq_x!(f, a, b);
301            });
302            let message = concat!(
303                "assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`\n",
304                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
305                " a_function label: `f`,\n",
306                "    a_param label: `a`,\n",
307                "    a_param debug: `1`,\n",
308                "     b_expr label: `b`,\n",
309                "     b_expr debug: `2`,\n",
310                "                a: `1`,\n",
311                "                b: `2`"
312            );
313            assert_eq!(
314                result
315                    .unwrap_err()
316                    .downcast::<String>()
317                    .unwrap()
318                    .to_string(),
319                message
320            );
321        }
322    }
323
324    mod arity_0 {
325        use super::*;
326
327        fn f() -> i8 {
328            return 1;
329        }
330
331        #[test]
332        fn eq() {
333            let b: i8 = 1;
334            for _ in 0..1 {
335                let actual = assert_fn_eq_x!(f, b);
336                let expect = 1;
337                assert_eq!(actual, expect);
338            }
339        }
340
341        #[test]
342        fn ne() {
343            let result = panic::catch_unwind(|| {
344                let b: i8 = 2;
345                let _actual = assert_fn_eq_x!(f, b);
346            });
347            let message = concat!(
348                "assertion failed: `assert_fn_eq_x!(a_function, b_expr)`\n",
349                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
350                " a_function label: `f`,\n",
351                "     b_expr label: `b`,\n",
352                "     b_expr debug: `2`,\n",
353                "                a: `1`,\n",
354                "                b: `2`"
355            );
356            assert_eq!(
357                result
358                    .unwrap_err()
359                    .downcast::<String>()
360                    .unwrap()
361                    .to_string(),
362                message
363            );
364        }
365    }
366}
367
368/// Assert a function output is equal to an expression.
369///
370/// Pseudocode:<br>
371/// function(a) = b
372///
373/// This macro provides the same statements as [`assert_fn_eq_x`](macro.assert_fn_eq_x.html),
374/// except this macro's statements are only enabled in non-optimized
375/// builds by default. An optimized build will not execute this macro's
376/// statements unless `-C debug-assertions` is passed to the compiler.
377///
378/// This macro is useful for checks that are too expensive to be present
379/// in a release build but may be helpful during development.
380///
381/// The result of expanding this macro is always type checked.
382///
383/// An unchecked assertion allows a program in an inconsistent state to
384/// keep running, which might have unexpected consequences but does not
385/// introduce unsafety as long as this only happens in safe code. The
386/// performance cost of assertions, however, is not measurable in general.
387/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
388/// after thorough profiling, and more importantly, only in safe code!
389///
390/// This macro is intended to work in a similar way to
391/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
392///
393/// # Module macros
394///
395/// * [`assert_fn_eq_x`](macro@crate::assert_fn_eq_x)
396/// * [`assert_fn_eq_x`](macro@crate::assert_fn_eq_x)
397/// * [`debug_assert_fn_eq_x`](macro@crate::debug_assert_fn_eq_x)
398///
399#[macro_export]
400macro_rules! debug_assert_fn_eq_x {
401    ($($arg:tt)*) => {
402        if cfg!(debug_assertions) {
403            $crate::assert_fn_eq_x!($($arg)*);
404        }
405    };
406}
407
408#[cfg(test)]
409mod test_debug_assert_fn_eq_x {
410    use std::panic;
411
412    mod arity_1 {
413        use super::*;
414
415        fn f(i: i8) -> i8 {
416            return i;
417        }
418
419        #[test]
420        fn eq() {
421            let a: i8 = 1;
422            let b: i8 = 1;
423            for _ in 0..1 {
424                let _actual = debug_assert_fn_eq_x!(f, a, b);
425                let _expect = 1;
426                // assert_eq!(actual, expect);
427            }
428        }
429
430        #[test]
431        fn failure() {
432            let result = panic::catch_unwind(|| {
433                let a: i8 = 1;
434                let b: i8 = 2;
435                let _actual = debug_assert_fn_eq_x!(f, a, b);
436            });
437            let message = concat!(
438                "assertion failed: `assert_fn_eq_x!(a_function, a_param, b_expr)`\n",
439                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
440                " a_function label: `f`,\n",
441                "    a_param label: `a`,\n",
442                "    a_param debug: `1`,\n",
443                "     b_expr label: `b`,\n",
444                "     b_expr debug: `2`,\n",
445                "                a: `1`,\n",
446                "                b: `2`"
447            );
448            assert_eq!(
449                result
450                    .unwrap_err()
451                    .downcast::<String>()
452                    .unwrap()
453                    .to_string(),
454                message
455            );
456        }
457    }
458
459    mod arity_0 {
460        use super::*;
461
462        fn f() -> i8 {
463            return 1;
464        }
465
466        #[test]
467        fn eq() {
468            let b: i8 = 1;
469            for _ in 0..1 {
470                let _actual = debug_assert_fn_eq_x!(f, b);
471                let _expect = 1;
472                // assert_eq!(actual, expect);
473            }
474        }
475
476        #[test]
477        fn ne() {
478            let result = panic::catch_unwind(|| {
479                let b: i8 = 2;
480                let _actual = debug_assert_fn_eq_x!(f, b);
481            });
482            let message = concat!(
483                "assertion failed: `assert_fn_eq_x!(a_function, b_expr)`\n",
484                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_fn_eq_x.html\n",
485                " a_function label: `f`,\n",
486                "     b_expr label: `b`,\n",
487                "     b_expr debug: `2`,\n",
488                "                a: `1`,\n",
489                "                b: `2`"
490            );
491            assert_eq!(
492                result
493                    .unwrap_err()
494                    .downcast::<String>()
495                    .unwrap()
496                    .to_string(),
497                message
498            );
499        }
500    }
501}