Is there any way to set panic hook reliably in the test?


I am writing a test for a function which should panic. I am aware of #[should_panic], but it does not fit me for two reasons:

  • I want to suppress printing the panic message to the console
  • I want to make additional checks after the panic

I think the solution here is to use std::panic: set_hook to suppress printing, catch_unwind to do additional checks, set_hook back to the old value.

However, this does not work reliably, because (IIRC) the test infra calls set_hook concurrently from other threads, so sometimes the panic message is printed to console, which is very confusing.

Are there any solutions for this problem except for using --test-threads 1?

1 Like

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.

1 Like

A post was split to a new topic: Setting a panic hook in tests