assertables 9.9.0

Assertables: assert macros for better testing, debugging, quality assurance, and runtime reliability.
Documentation
//! Assert all elements of an iteratable are greater than or equal to a value.
//!
//! Pseudocode:<br>
//! iter ∀ ≥ x
//!
//! # Example
//!
//! ```rust
//! use assertables::*;
//!
//! let a = [1, 2];
//! let b = 1;
//! assert_all_ge_x!(a.iter(), b);
//! ```
//!
//! This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
//!
//! # Module macros
//!
//! * [`assert_all_ge_x`](macro@crate::assert_all_ge_x)
//! * [`assert_all_ge_x_as_result`](macro@crate::assert_all_ge_x_as_result)
//! * [`debug_assert_all_ge_x`](macro@crate::debug_assert_all_ge_x)

/// Assert all elements of an iteratable are greater than or equal to a value.
///
/// Pseudocode:<br>
/// iter ∀ ≥ x
///
/// * If true, return Result `Ok(())`.
///
/// * Otherwise, return Result `Err(message)`.
///
/// This macro is useful for runtime checks, such as checking parameters,
/// or sanitizing inputs, or handling different results in different ways.
///
/// This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
///
/// # Module macros
///
/// * [`assert_all_ge_x`](macro@crate::assert_all_ge_x)
/// * [`assert_all_ge_x_as_result`](macro@crate::assert_all_ge_x_as_result)
/// * [`debug_assert_all_ge_x`](macro@crate::debug_assert_all_ge_x)
///
#[macro_export]
macro_rules! assert_all_ge_x_as_result {
    ($iter:expr, $x:expr $(,)?) => {
        match ($iter, &$x) {
            (mut iter, x) => {
                if iter.all(|e| e >= x) {
                    Ok(())
                } else {
                    Err(format!(
                        concat!(
                            "assertion failed: `assert_all_ge_x!(iter, x)`\n",
                            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
                            " iter label: `{}`,\n",
                            " iter debug: `{:?}`,\n",
                            " x label: `{}`,\n",
                            " x debug: `{:?}`"
                        ),
                        stringify!($iter),
                        $iter,
                        stringify!($x),
                        x
                    ))
                }
            }
        }
    };
}

#[cfg(test)]
mod test_assert_all_ge_x_as_result {

    mod test_int {

        #[test]
        fn all_ge() {
            let a = [1, 2];
            let b = 1;
            for _ in 0..1 {
                let actual = assert_all_ge_x_as_result!(a.iter(), b);
                assert_eq!(actual.unwrap(), ());
            }
        }
        #[test]
        fn all_ge_once() {
            use std::sync::Once;
            static A: Once = Once::new();
            fn a() -> [i8; 2] {
                if A.is_completed() {
                    panic!("A.is_completed()")
                } else {
                    A.call_once(|| {})
                }
                [1, 2]
            }
            let b = 1;
            assert_eq!(A.is_completed(), false);
            let result = assert_all_ge_x_as_result!(a().iter(), b);
            assert!(result.is_ok());
            assert_eq!(A.is_completed(), true);
        }

        #[test]
        fn some_not_ge() {
            let a = [1, 2];
            let b = 2;
            let actual = assert_all_ge_x_as_result!(a.iter(), b);
            let message = concat!(
                "assertion failed: `assert_all_ge_x!(iter, x)`\n",
                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
                " iter label: `a.iter()`,\n",
                " iter debug: `Iter([1, 2])`,\n",
                " x label: `b`,\n",
                " x debug: `2`"
            );
            assert_eq!(actual.unwrap_err(), message);
        }
    }

    mod test_struct {
        use std::cmp::Ordering;

        #[derive(Debug, PartialEq)]
        struct S {
            i: i32,
        }

        impl PartialOrd for S {
            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
                // Reuses the implementation of the field's type (u32)
                self.i.partial_cmp(&other.i)
            }
        }

        #[test]
        fn all_ge() {
            let a: [S; 2] = [S { i: 1 }, S { i: 2 }];
            let b = S { i: 1 };
            for _ in 0..1 {
                let actual = assert_all_ge_x_as_result!(a.iter(), b);
                assert_eq!(actual.unwrap(), ());
            }
        }

        #[test]
        fn some_not_ge() {
            let a: [S; 2] = [S { i: 1 }, S { i: 2 }];
            let b = S { i: 3 };
            let actual = assert_all_ge_x_as_result!(a.iter(), b);
            let message = concat!(
                "assertion failed: `assert_all_ge_x!(iter, x)`\n",
                "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
                " iter label: `a.iter()`,\n",
                " iter debug: `Iter([S { i: 1 }, S { i: 2 }])`,\n",
                " x label: `b`,\n",
                " x debug: `S { i: 3 }`"
            );
            assert_eq!(actual.unwrap_err(), message);
        }
    }
}

/// Assert all elements of an iteratable are greater than or equal to a value.
///
/// Pseudocode:<br>
/// iter ∀ ≥ x
///
/// * If true, return `()`.
///
/// * Otherwise, call [`panic!`] with a message and the values of the
///   expressions with their debug representations.
///
/// # Examples
///
/// ```rust
/// use assertables::*;
/// # use std::panic;
///
/// # fn main() {
/// let a = [1, 2];
/// let b = 1;
/// assert_all_ge_x!(a.iter(), b);
///
/// # let result = panic::catch_unwind(|| {
/// // This will panic
/// let a = [1, 2];
/// let b = 2;
/// assert_all_ge_x!(a.iter(), b);
/// # });
/// // assertion failed: `assert_all_ge_x!(iter, x)`
/// // https://docs.rs/assertables/…/assertables/macro.assert_all_ge_x.html
/// //  iter label: `a.iter()`,
/// //  iter debug: `Iter([1, 2])`,
/// //  x label: `b`,\n",
/// //  x debug: `2`"
/// # let actual = result.unwrap_err().downcast::<String>().unwrap().to_string();
/// # let message = concat!(
/// #     "assertion failed: `assert_all_ge_x!(iter, x)`\n",
/// #     "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
/// #     " iter label: `a.iter()`,\n",
/// #     " iter debug: `Iter([1, 2])`,\n",
/// #     " x label: `b`,\n",
/// #     " x debug: `2`"
/// # );
/// # assert_eq!(actual, message);
/// # }
/// ```
///
/// This implementation uses [`::std::iter::Iterator`](https://doc.rust-lang.org/std/iter/trait.Iterator.html).
///
/// # Module macros
///
/// * [`assert_all_ge_x`](macro@crate::assert_all_ge_x)
/// * [`assert_all_ge_x_as_result`](macro@crate::assert_all_ge_x_as_result)
/// * [`debug_assert_all_ge_x`](macro@crate::debug_assert_all_ge_x)
///
#[macro_export]
macro_rules! assert_all_ge_x {
    ($iter:expr, $x:expr $(,)?) => {
        match $crate::assert_all_ge_x_as_result!($iter, $x) {
            Ok(()) => (),
            Err(err) => panic!("{}", err),
        }
    };
    ($iter:expr, $x:expr, $($message:tt)+) => {
        match $crate::assert_all_ge_x_as_result!($iter, $x) {
            Ok(()) => (),
            Err(err) => panic!("{}\n{}", format_args!($($message)+), err),
        }
    };
}

#[cfg(test)]
mod test_assert_all_ge_x {
    use std::panic;

    #[test]
    fn success() {
        let a = [1, 2];
        let b = 1;
        for _ in 0..1 {
            let actual = assert_all_ge_x!(a.iter(), b);
            assert_eq!(actual, ());
        }
    }

    #[test]
    fn failure() {
        let a = [1, 2];
        let b = 2;
        let result = panic::catch_unwind(|| {
            let _actual = assert_all_ge_x!(a.iter(), b);
        });
        let message = concat!(
            "assertion failed: `assert_all_ge_x!(iter, x)`\n",
            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
            " iter label: `a.iter()`,\n",
            " iter debug: `Iter([1, 2])`,\n",
            " x label: `b`,\n",
            " x debug: `2`"
        );
        assert_eq!(
            result
                .unwrap_err()
                .downcast::<String>()
                .unwrap()
                .to_string(),
            message
        );
    }
}

/// Assert all elements of an iteratable are greater than or equal to a value.
///
/// Pseudocode:<br>
/// iter ∀ ≥ x
///
/// This macro provides the same statements as [`assert_all_ge_x`](macro.assert_all_ge_x.html),
/// except this macro's statements are only enabled in non-optimized
/// builds by default. An optimized build will not execute this macro's
/// statements unless `-C debug-assertions` is passed to the compiler.
///
/// This macro is useful for checks that are too expensive to be present
/// in a release build but may be helpful during development.
///
/// The result of expanding this macro is always type checked.
///
/// An unchecked assertion allows a program in an inconsistent state to
/// keep running, which might have unexpected consequences but does not
/// introduce unsafety as long as this only happens in safe code. The
/// performance cost of assertions, however, is not measurable in general.
/// Replacing `assert*!` with `debug_assert*!` is thus only encouraged
/// after thorough profiling, and more importantly, only in safe code!
///
/// This macro is intended to work in a similar way to
/// [`::std::debug_assert`](https://doc.rust-lang.org/std/macro.debug_assert.html).
///
/// # Module macros
///
/// * [`assert_all_ge_x`](macro@crate::assert_all_ge_x)
/// * [`assert_all_ge_x`](macro@crate::assert_all_ge_x)
/// * [`debug_assert_all_ge_x`](macro@crate::debug_assert_all_ge_x)
///
#[macro_export]
macro_rules! debug_assert_all_ge_x {
    ($($arg:tt)*) => {
        if cfg!(debug_assertions) {
            $crate::assert_all_ge_x!($($arg)*);
        }
    };
}

#[cfg(test)]
mod test_debug_assert_all_ge_x {
    use std::panic;

    #[test]
    fn success() {
        let a = [1, 2];
        let b = 1;
        for _ in 0..1 {
            let _actual = debug_assert_all_ge_x!(a.iter(), b);
            // assert_eq!(actual, ());
        }
    }

    #[test]
    fn failure() {
        let a = [1, 2];
        let b = 2;
        let result = panic::catch_unwind(|| {
            let _actual = debug_assert_all_ge_x!(a.iter(), b);
        });
        let message = concat!(
            "assertion failed: `assert_all_ge_x!(iter, x)`\n",
            "https://docs.rs/assertables/9.9.0/assertables/macro.assert_all_ge_x.html\n",
            " iter label: `a.iter()`,\n",
            " iter debug: `Iter([1, 2])`,\n",
            " x label: `b`,\n",
            " x debug: `2`"
        );
        assert_eq!(
            result
                .unwrap_err()
                .downcast::<String>()
                .unwrap()
                .to_string(),
            message
        );
    }
}