Non-panicking assertions

Are there any crates that offer the equivalent of assert_eq!, assert_ne!, etc. macros, which return Result::Errs instead of panicking when they fail?

The context is a test runner which would not let me run needed cleanup code if it panicked on error.

(Not exactly that, but still).

You could also use scopeguard to run cleanup code even after a panic

2 Likes

You could use catch_unwind, ideally as part of the actual test harness, or just write a Drop, which get run on unwind (but not if you have panic = "abort" set.

I would use anyhow::ensure!() to do something like this:

#[cfg(test)]
mod tests {
  use anyhow::Error;

  #[test]
  fn one_plus_one() -> Result<(), Error> {
    let sum = 1 + 1;

    anyhow::ensure!(sum == 2);

    Ok(())
  }
}

The error message will contain a backtrace and the sum == 2 expression, which is normally enough to figure out what went wrong. You could always wrap it with your own assert_eq!() or assert_ne!() macro that does anyhow::ensure!($actual == $expected, "{:?} != {:?}", $actual, $expected).

This is exactly what I was looking for. I had come across it before but had forgotten which crate offered it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.