When I run the following program with cargo test
:
use std::panic;
fn assert_panic_func(f: fn() -> (), msg: String) {
let result = panic::catch_unwind(|| {
f();
});
assert!(result.is_err(), msg);
}
macro_rules! assert_panic {
($test:expr , $msg:tt) => {{
fn wrapper() {
$test;
}
assert_panic_func(wrapper, $msg.to_string())
}};
}
fn main() {
println!("running main()");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_1() {
assert_panic!(
panic!("We are forcing a panic"),
"This is asserted within function (raw panic)."
);
// assert_panic!(true, "This is asserted within function (raw true).");
}
}
I get the expected output:
running 1 test
test tests::t_1 ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
If I uncomment the second assert_panic!(...) line, and rerun cargo test
, I get the following output:
running 1 test
test tests::t_1 ... FAILED
failures:
---- tests::t_1 stdout ----
thread 'tests::t_1' panicked at 'We are forcing a panic', src/lib.rs:29:13
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread 'tests::t_1' panicked at 'This is asserted within function (raw true).', src/lib.rs:7:5
failures:
tests::t_1
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
The second panic is legitimate, and that is what I am looking for, but the first panic seems to be being triggered by the line that was not triggering a panic in the first invocation.
What is going on, and how do I fix it?