Keep Re-running Unit Test until getting `Failed`

Viewed 30

I am having an inconsistent output when running a unit test. Most of the times the unit test passes without any issue, it's rare to have it failed.

Is there any cargo test parameter that might help to keep re-running the unit test until an error is encountered?

1 Answers

Before anyone copies this, please note: this is code for bug hunting and not a general suggestion to write tests!


You can use loop to create endless loops (read the docs) that will only stop on panic, break etc.

This way you can run your test via cargo test and it will only stop on assertion fail or manually via interrupt (ctrl+C).

Example

use rand::Rng;

#[test]
fn loop_inconsistent_test() {
    loop {
        inconsistent_test();
    }
}

fn inconsistent_test() {
    let mut rng = rand::thread_rng();
    let num = rng.gen_range(0..1_000_000);
    assert_eq!(num, 0); // if this fails, loop will stop
}
Related