#rand #random #reproducibility

dev rand_dev

Reproducible randomness source for tests

2 releases

0.1.1 Feb 28, 2023
0.1.0 Aug 19, 2022

#493 in Debugging

Download history 15/week @ 2023-12-05 18/week @ 2023-12-12 20/week @ 2023-12-19 1/week @ 2023-12-26 18/week @ 2024-01-02 48/week @ 2024-01-09 45/week @ 2024-01-16 39/week @ 2024-01-23 41/week @ 2024-01-30 24/week @ 2024-02-06 72/week @ 2024-02-13 52/week @ 2024-02-20 213/week @ 2024-02-27 58/week @ 2024-03-05 90/week @ 2024-03-12 117/week @ 2024-03-19

495 downloads per month
Used in 5 crates

MIT/Apache

8KB
65 lines

License Docs Crates io

Reproducible randomness source for tests

Having reproducible tests helps debugging problems that have probabilistic nature. This library provides a random numbers generator DevRng compatible with rand crate (it implements Rng, RngCore, SeedableRng traits). When generator is constructed, its seed is printed to stdout. You can override a seed by setting RUST_TESTS_SEED env variable. Same seed leads to same randomness generated across all platforms.

Usage

Reproducible source of randomness can be added in one line:

use rand::Rng;
use rand_dev::DevRng;

#[test]
fn it_works() {
    let mut rng = DevRng::new();
    assert!(rng.gen_range(0..=10) < 10);
}

Then if test fails, you can observe seed of randomness generator in stdout:

$ cargo test
    Finished test [unoptimized + debuginfo] target(s) in 0.00s
     Running unittests (target/debug/deps/simple_usage-592d47155d40d1f7)

running 1 test
test tests::it_works ... FAILED

failures:

---- tests::it_works stdout ----
RUST_TESTS_SEED=cab4ab5c8471fa03691bb86d96c2febeb9b1099a78d164e8addbe7f83d107c78
thread 'tests::it_works' panicked at 'assertion failed: rng.gen_range(0..=10) < 10', src/lib.rs:9:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    tests::it_works

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

Now you can fix the seed by setting env variable to reproduce and debug a failing test:

$ export RUST_TESTS_SEED=cab4ab5c8471fa03691bb86d96c2febeb9b1099a78d164e8addbe7f83d107c78
$ cargo test

License

Licensed under either of

  • Apache License, Version 2.0
  • MIT license

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~240–420KB