1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
//! Assert an expression is equal to another.
//!
//! Pseudocode:<br>
//! a = b
//!
//! # Module macro
//!
//! * [`assert_eq_as_result`](macro@crate::assert_eq_as_result)
//!
//! # Rust standard macros
//!
//! * [`assert_eq`](https://doc.rust-lang.org/std/macro.assert_eq.html)
//! * [`debug_assert_eq`](https://doc.rust-lang.org/std/macro.debug_assert_eq.html)
/// Assert an expression is equal to another.
///
/// Pseudocode:<br>
/// a = b
///
/// * If true, return Result `Ok(())`.
///
/// * Otherwise, return Result `Err` with a diagnostic message.
///
/// This macro provides the same statements as [`assert_`](macro.assert_.html),
/// except this macro returns a Result, rather than doing a panic.
///
/// This macro is useful for runtime checks, such as checking parameters,
/// or sanitizing inputs, or handling different results in different ways.
///
/// # Module macros
///
/// * [`assert_eq_as_result`](macro@crate::assert_eq_as_result)
///
/// # Rust standard macros
///
/// * [`assert_eq`](https://doc.rust-lang.org/std/macro.assert_eq.html)
/// * [`debug_assert_eq`](https://doc.rust-lang.org/std/macro.debug_assert_eq.html)
///
#[macro_export]
macro_rules! assert_eq_as_result {
($a:expr, $b:expr $(,)?) => ({
match (&$a, &$b) {
(a, b) => {
if a == b {
Ok(())
} else {
Err(format!(
concat!(
"assertion failed: `assert_eq!(a, b)`\n",
"https://docs.rs/assertables/8.7.0/assertables/macro.assert_eq.html\n",
" a label: `{}`,\n",
" a debug: `{:?}`,\n",
" b label: `{}`,\n",
" b debug: `{:?}`",
),
stringify!($a),
a,
stringify!($b),
b
))
}
}
}
});
}
#[cfg(test)]
mod tests {
#[test]
fn test_assert_eq_as_result_x_success() {
let a: i32 = 1;
let b: i32 = 1;
let result = assert_eq_as_result!(a, b);
assert_eq!(result, Ok(()));
}
#[test]
fn test_assert_eq_as_result_x_failure() {
let a: i32 = 1;
let b: i32 = 2;
let result = assert_eq_as_result!(a, b);
assert!(result.is_err());
assert_eq!(
result.unwrap_err(),
concat!(
"assertion failed: `assert_eq!(a, b)`\n",
"https://docs.rs/assertables/8.7.0/assertables/macro.assert_eq.html\n",
" a label: `a`,\n",
" a debug: `1`,\n",
" b label: `b`,\n",
" b debug: `2`",
)
);
}
}