Setting a panic hook in tests

Hey @matklad!

Could you figure out a proper way to solve your issue?

I have already a solution in place but I am struggling with concurrency, resulting in non-deterministic tests.

Thanks in advance!

I've broken out your post into a new topic. In the future, rather than replying to a years-old thread, please open a new topic and link to the old one.


Thanks for breaking it into a new topic! I am new here, but next time I will behave as you mentioned!


My understanding is that this is still not really possible. In a similar situation, I even ended up running a single test in a different problem (via cargo run —example).

1 Like

Thanks for the info, @matklad!

I ended up using a static Mutex which is locked by a function that uses take_hook and set_hook.

lazy_static! {
    static ref PANIC_HOOK_LOCK: std::sync::Mutex<()> = Mutex::new(());

fn check_panic() {
    let _guard = PANIC_HOOK_LOCK.lock();

    //Logic to verify the panic message by using panic::take_hook() and panic::set_hook(...)

But I am not 100% pleased with this solution, as it can be accessed by only one thread at a time.

I still wonder how it could be achieved for a multi-threaded environment. Below your original question, there was the following reply:

One option could be to make a panic hook that delegates to some thread-local state. 
Have all of your tests install that hook and then setup the thread local hook to what they want.

But to be honest I still could not wrap my head around this. The problem is that anytime we use set_hook, it is globally set and it affects all the threads.

I wonder how it could be solved in an elegant way. If anyone has some idea, I would appreciate that, thank you!

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.