diem_proptest_helpers/
value_generator.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8use proptest::{
9    strategy::{Strategy, ValueTree},
10    test_runner::{Config, TestRng, TestRunner},
11};
12
13/// Context for generating single values out of strategies.
14///
15/// Proptest is designed to be built around "value trees", which represent a
16/// spectrum from complex values to simpler ones. But in some contexts, like
17/// benchmarking or generating corpuses, one just wants a single value. This is
18/// a convenience struct for that.
19#[derive(Default)]
20pub struct ValueGenerator {
21    runner: TestRunner,
22}
23
24impl ValueGenerator {
25    /// Creates a new value generator with the default RNG.
26    pub fn new() -> Self { Default::default() }
27
28    /// Creates a new value generator with provided RNG
29    pub fn new_with_rng(rng: TestRng) -> Self {
30        Self {
31            runner: TestRunner::new_with_rng(Config::default(), rng),
32        }
33    }
34
35    /// Creates a new value generator with a deterministic RNG.
36    ///
37    /// This generator has a hardcoded seed, so its results are predictable
38    /// across test runs. However, a new proptest version may change the
39    /// seed.
40    pub fn deterministic() -> Self {
41        Self {
42            runner: TestRunner::deterministic(),
43        }
44    }
45
46    /// Generates a single value for this strategy.
47    ///
48    /// Panics if generating the new value fails. The only situation in which
49    /// this can happen is if generating the value causes too many internal
50    /// rejects.
51    pub fn generate<S: Strategy>(&mut self, strategy: S) -> S::Value {
52        strategy
53            .new_tree(&mut self.runner)
54            .expect("creating a new value should succeed")
55            .current()
56    }
57}