user10017511
user10017511

Reputation: 23

Is it possible to run code after all tests have finished?

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

Answers (2)

Akash Rawal
Akash Rawal

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.

  1. Start another process.
  2. Setup a pipe between parent and child process.
  3. The parent keeps the pipe open while the child tries to read from the pipe. You might serialize and send any additional info along the pipe that the after-all-tests logic might need.
  4. After all tests are finished, the pipe gets closed.
  5. The child carries out after-all-tests logic.

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

Shepmaster
Shepmaster

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

Related Questions