assertables/assert_ne.rs
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 not equal to another.
//!
//! Pseudocode:<br>
//! a ≠ b
//!
//! # Module macro
//!
//! * [`assert_ne_as_result`](macro@crate::assert_ne_as_result)
//!
//! # Rust standard macros
//!
//! * [`assert_ne`](https://doc.rust-lang.org/std/macro.assert_ne.html)
//! * [`debug_assert_ne`](https://doc.rust-lang.org/std/macro.debug_assert_ne.html)
/// Assert an expression is not equal to another.
///
/// Pseudocode:<br>
/// a ≠ b
///
/// * If true, return Result `Ok(())`.
///
/// * When false, return [`Err`] with a message and the values of the
/// expressions with their debug representations.
///
/// 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 macro
///
/// * [`assert_ne_as_result`](macro@crate::assert_ne_as_result)
///
/// # Rust standard macros
///
/// * [`assert_ne`](https://doc.rust-lang.org/std/macro.assert_ne.html)
/// * [`debug_assert_ne`](https://doc.rust-lang.org/std/macro.debug_assert_ne.html)
///
#[macro_export]
macro_rules! assert_ne_as_result {
($a:expr, $b:expr $(,)?) => {{
match (&$a, &$b) {
(a, b) => {
if a != b {
Ok(())
} else {
Err(format!(
concat!(
"assertion failed: `assert_ne!(a, b)`\n",
"https://docs.rs/assertables/9.4.0/assertables/macro.assert_ne.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_ne_as_result_success() {
let a: i32 = 1;
let b: i32 = 2;
let result = assert_ne_as_result!(a, b);
assert_eq!(result, Ok(()));
}
#[test]
fn test_assert_ne_as_result_failure() {
let a: i32 = 1;
let b: i32 = 1;
let result = assert_ne_as_result!(a, b);
assert_eq!(
result.unwrap_err(),
concat!(
"assertion failed: `assert_ne!(a, b)`\n",
"https://docs.rs/assertables/9.4.0/assertables/macro.assert_ne.html\n",
" a label: `a`,\n",
" a debug: `1`,\n",
" b label: `b`,\n",
" b debug: `1`",
)
);
}
}