没有直接的方法来调整行号panic!
prints.
有一个原始 RFC https://github.com/rust-lang/rfcs/issues/1744添加一个属性,允许某些方法从回溯中“隐藏”。这样的属性也可能会影响行号,但尚不清楚。
恐慌怎么写啊!就像 Rust 中的宏一样? https://stackoverflow.com/q/43254340/155423描述了如何编写自己的panic!
宏,但它选择拆除整个进程,而不仅仅是当前线程。
重要的是你只想控制消息,这可以通过panic::set_hook https://doc.rust-lang.org/std/panic/fn.set_hook.html。您可以通过线程局部变量将侧通道信息从测试传递到恐慌处理程序。
use std::cell::Cell;
thread_local! {
static ASSERT_LOCATION: Cell<Option<(&'static str, u32)>> = Cell::new(None)
}
fn report_my_error(info: &std::panic::PanicInfo) {
match info.location() {
Some(location) => {
let file = location.file();
let line = location.line();
println!("The panic actually happened at: {}, {}", file, line);
}
None => println!("I don't know where the panic actually happened"),
}
ASSERT_LOCATION.with(|location| if let Some((file, line)) = location.get() {
println!(
"But I'm going to tell you it happened at {}, {}",
file,
line
);
});
if let Some(msg) = info.payload().downcast_ref::<&str>() {
println!("The error message was: {}", msg);
}
}
#[test]
fn alpha() {
std::panic::set_hook(Box::new(report_my_error));
ASSERT_LOCATION.with(|location| {
location.set(Some((file!(), line!())));
});
panic!("This was only a test")
}
您需要确保在每个测试中设置紧急处理程序,然后设置位置信息。您可能还想更新紧急处理程序以将位置信息设置回None
以避免线程之间泄漏位置信息。
您可能需要编写自己的宏,用户可以在测试中使用该宏来隐式设置行号。与此类似的语法可以为该设置代码提供一个位置:
assert_that!(42, is.equal_to(0));
可以扩展到:
assert_that(file!(), line!(), 42, is.equal_to(0));
我可能会在里面设置恐慌处理程序assert_that
.