Mohamad-Jaafar NEHME
Mohamad-Jaafar NEHME

Reputation: 1215

Keep Re-running Unit Test until getting `Failed`

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?

Upvotes: 2

Views: 673

Answers (1)

leun4m
leun4m

Reputation: 590

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
}

Upvotes: 1

Related Questions