Reputation: 2249
In Rust, is there any way to execute a teardown function after all tests have been run (i.e. at the end of cargo test
) using the standard testing library?
I'm not looking to run a teardown function after each test, as they've been discussed in these related posts:
These discuss ideas to run:
std::panic::catch_unwind
)std::sync::Once
)One workaround is a shell script that wraps around the cargo test
call, but I'm still curious if the above is possible.
Upvotes: 33
Views: 6563
Reputation: 472
Here is an example implementation of the custom test framework solution mentioned by Masklinn:
#![feature(custom_test_frameworks)]
#![feature(test)]
#![test_runner(custom_test_runner)]
extern crate test;
use test::{test_main_static, TestDescAndFn};
fn main() {}
pub fn custom_test_runner(tests: &[&TestDescAndFn]) {
println!("Setup");
test_main_static(tests);
println!("Teardown");
}
#[cfg(test)]
mod tests {
#[test]
fn test1() {
println!("Test 1")
}
#[test]
fn test2() {
println!("Test 2")
}
}
This will print:
Setup
Test 1
Test 2
Teardown
Upvotes: 5
Reputation: 42197
I'm not sure there's a way to have a global ("session") teardown with Rust's built-in testing features, previous inquiries seem to have yielded little, aside from "maybe a build script". Third-party testing systems (e.g. shiny or stainless) might have that option though, might be worth looking into their exact capabilities
Alternatively, if nightly is suitable there's a custom test frameworks feature being implemented, which you might be able to use for that purpose.
That aside, you may want to look at macro_rules!
to cleanup some boilerplate, that's what folks like burntsushi do e.g. in the regex package.
Upvotes: 3