Cleaning up after test failure

Suppose I have a test which creates a bunch of temporary files (and may even spawn a database server process to interact with). If this test encounters an assertion failure or other kind of panic, these temporary files are left behind.

Is there a way to perform the cleanup, other than treating panics as exceptions and recover from them to run the cleanup myself? I usually compile with panic="abort".


I had this problem once and solved it by defining a struct TestResources which creates all the resources you need. Then I implemented the Drop trait on that struct to remove all the resources. I have no idea if it will work with panic="abort". If it doesn't, you could probably disable panic="abort" for the tests.

This is the code if you're interested.

hook still runs with abort. A more (overly) complex second process gets some cases but best to check and clean at start since can't solve a power cut making "temporary files" persistent if they are backed on non-temporary storage.

Given that the test framework relies on panics, does it even work at all with panic=abort? I didn't think it did, but could be wrong.

Indeed. Cargo seems to silently ignore this:

panic = "abort"

Odd. I wonder now how realistic testing for panic = "abort" builds is …

Would setting a panic hook work in this case?

std::panic::set_hook(Box::new(|_| {
    let _ = std::panic::take_hook();
1 Like