Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run setup code before any tests run in Rust?

I have a Rust app (a simple interpreter) that needs some setup (initialize a repo) before the environment is usable.

I understand that Rust runs its tests (via cargo test) in a multithreaded manner, so I need to initialize the repo before any tests run. I also need to do this only once per run, not before each test.

In Java's JUnit this would be done with a @BeforeClass (or @BeforeAll in JUnit 5) method. How can I acheive the same thing in Rust?

like image 361
kittylyst Avatar asked Sep 19 '19 07:09

kittylyst


People also ask

How do you ignore a test in Rust?

Ignoring Some Tests Unless Specifically Requested If you want to run all tests whether they're ignored or not, you can run cargo test -- --include-ignored .

What is CFG test?

The #[cfg(test)] annotation on the tests module tells Rust to compile and run the test code only when you run cargo test , not when you run cargo build .

How do you write test cases in Rust?

At its simplest, a test in Rust is a function that's annotated with the test attribute. Attributes are metadata about pieces of Rust code; one example is the derive attribute we used with structs in Chapter 5. To change a function into a test function, add #[test] on the line before fn .


2 Answers

There's nothing built-in that would do this but this should help (you will need to call initialize() in the beginning of every test):

use std::sync::Once;  static INIT: Once = Once::new();  pub fn initialize() {     INIT.call_once(|| {         // initialization code here     }); } 
like image 91
Jussi Kukkonen Avatar answered Sep 17 '22 21:09

Jussi Kukkonen


If you use the ctor crate, you can take advantage of a global constructor function that will run before any of your tests are run.

Here's an example initialising the popular env_logger crate (assuming you have added ctor to your [dev-dependencies] section in your Cargo.toml file):

#[cfg(test)]
#[ctor::ctor]
fn init() {
    env_logger::init();
}

The function name is unimportant and you may name it anything.

like image 36
Brendan Molloy Avatar answered Sep 18 '22 21:09

Brendan Molloy