Reputation: 23
I would like to run a teardown function (i.e. write a log to a file) when all of my tests have finished. In this example, the function would run after both it_works_foo
and it_works_bar
are complete:
#[test]
fn it_works_foo() {
assert_eq!(1, 1);
}
#[test]
fn it_works_bar() {
assert_eq!(2, 2);
}
I'm looking for something like Mocha's after
behavior:
describe('hooks', function() {
after(function() {
// runs after all tests in this block
});
it('it_works_foo', () => {});
it('it_works_bar', () => {});
});
Is this possible?
Upvotes: 2
Views: 2277
Reputation: 144
I have a lateral-thinking solution to this. A notable disadvantage is that your after-all-tests code has to run in a separate process.
Parent side logic example:
//Start database stopping script
let stop_postgres = Command::new(&format!("{}/stop_postgres.sh",
env!("CARGO_MANIFEST_DIR")))
.args([&pid.to_string()])
.stdin(Stdio::piped())
.spawn().expect("Cannot run stop_postgres.sh");
//Keep the pipe open till the end of all tests
Box::leak(Box::new(stop_postgres.stdin.unwrap()));
Child process example:
#!/bin/bash
#Read from the pipe
read discard
#Pipe is closed now, that means all tests have finished.
kill -SIGKILL "$1"
echo "stop_postgres.sh: Killed postgres"
Upvotes: 0
Reputation: 430673
No, the built-in testing framework does not have support for anything like this.
RFC 2318, custom test frameworks, has been accepted and is being worked on. Once available, I expect there to be a small explosion in alternate frameworks, many of which are likely to include before
/ after
/ around
type functionality.
See also:
Upvotes: 2