Skip to main content

proptest/test_runner/
config.rs

1//-
2// Copyright 2017, 2018, 2019 The proptest developers
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10use crate::std_facade::Box;
11use core::{fmt, str, u32};
12
13use crate::test_runner::result_cache::{noop_result_cache, ResultCache};
14use crate::test_runner::rng::RngAlgorithm;
15use crate::test_runner::FailurePersistence;
16
17/// Override the config fields from environment variables, if any are set.
18/// Without the `std` feature this function returns config unchanged.
19#[cfg(all(feature = "std", not(target_arch = "wasm32")))]
20pub fn contextualize_config(mut result: Config) -> Config {
21    use std::env;
22    use std::ffi::OsString;
23    use std::fmt;
24    use std::str::FromStr;
25
26    const CASES: &str = "PROPTEST_CASES";
27
28    const MAX_LOCAL_REJECTS: &str = "PROPTEST_MAX_LOCAL_REJECTS";
29    const MAX_GLOBAL_REJECTS: &str = "PROPTEST_MAX_GLOBAL_REJECTS";
30    const MAX_FLAT_MAP_REGENS: &str = "PROPTEST_MAX_FLAT_MAP_REGENS";
31    const MAX_SHRINK_TIME: &str = "PROPTEST_MAX_SHRINK_TIME";
32    const MAX_SHRINK_ITERS: &str = "PROPTEST_MAX_SHRINK_ITERS";
33    const MAX_DEFAULT_SIZE_RANGE: &str = "PROPTEST_MAX_DEFAULT_SIZE_RANGE";
34    #[cfg(feature = "fork")]
35    const FORK: &str = "PROPTEST_FORK";
36    #[cfg(feature = "timeout")]
37    const TIMEOUT: &str = "PROPTEST_TIMEOUT";
38    const VERBOSE: &str = "PROPTEST_VERBOSE";
39    const RNG_ALGORITHM: &str = "PROPTEST_RNG_ALGORITHM";
40    const RNG_SEED: &str = "PROPTEST_RNG_SEED";
41    const DISABLE_FAILURE_PERSISTENCE: &str =
42        "PROPTEST_DISABLE_FAILURE_PERSISTENCE";
43
44    fn parse_or_warn<T: FromStr + fmt::Display>(
45        src: &OsString,
46        dst: &mut T,
47        typ: &str,
48        var: &str,
49    ) {
50        if let Some(src) = src.to_str() {
51            if let Ok(value) = src.parse() {
52                *dst = value;
53            } else {
54                eprintln!(
55                    "proptest: The env-var {}={} can't be parsed as {}, \
56                     using default of {}.",
57                    var, src, typ, *dst
58                );
59            }
60        } else {
61            eprintln!(
62                "proptest: The env-var {} is not valid, using \
63                 default of {}.",
64                var, *dst
65            );
66        }
67    }
68
69    for (var, value) in
70        env::vars_os().filter_map(|(k, v)| k.into_string().ok().map(|k| (k, v)))
71    {
72        let var = var.as_str();
73
74        #[cfg(feature = "fork")]
75        if var == FORK {
76            parse_or_warn(&value, &mut result.fork, "bool", FORK);
77            continue;
78        }
79
80        #[cfg(feature = "timeout")]
81        if var == TIMEOUT {
82            parse_or_warn(&value, &mut result.timeout, "timeout", TIMEOUT);
83            continue;
84        }
85
86        if var == CASES {
87            parse_or_warn(&value, &mut result.cases, "u32", CASES);
88        } else if var == MAX_LOCAL_REJECTS {
89            parse_or_warn(
90                &value,
91                &mut result.max_local_rejects,
92                "u32",
93                MAX_LOCAL_REJECTS,
94            );
95        } else if var == MAX_GLOBAL_REJECTS {
96            parse_or_warn(
97                &value,
98                &mut result.max_global_rejects,
99                "u32",
100                MAX_GLOBAL_REJECTS,
101            );
102        } else if var == MAX_FLAT_MAP_REGENS {
103            parse_or_warn(
104                &value,
105                &mut result.max_flat_map_regens,
106                "u32",
107                MAX_FLAT_MAP_REGENS,
108            );
109        } else if var == MAX_SHRINK_TIME {
110            parse_or_warn(
111                &value,
112                &mut result.max_shrink_time,
113                "u32",
114                MAX_SHRINK_TIME,
115            );
116        } else if var == MAX_SHRINK_ITERS {
117            parse_or_warn(
118                &value,
119                &mut result.max_shrink_iters,
120                "u32",
121                MAX_SHRINK_ITERS,
122            );
123        } else if var == MAX_DEFAULT_SIZE_RANGE {
124            parse_or_warn(
125                &value,
126                &mut result.max_default_size_range,
127                "usize",
128                MAX_DEFAULT_SIZE_RANGE,
129            );
130        } else if var == VERBOSE {
131            parse_or_warn(&value, &mut result.verbose, "u32", VERBOSE);
132        } else if var == RNG_ALGORITHM {
133            parse_or_warn(
134                &value,
135                &mut result.rng_algorithm,
136                "RngAlgorithm",
137                RNG_ALGORITHM,
138            );
139        } else if var == RNG_SEED {
140            parse_or_warn(&value, &mut result.rng_seed, "u64", RNG_SEED);
141        } else if var == DISABLE_FAILURE_PERSISTENCE {
142            result.failure_persistence = None;
143        } else if var.starts_with("PROPTEST_") {
144            eprintln!("proptest: Ignoring unknown env-var {}.", var);
145        }
146    }
147
148    result
149}
150
151/// Without the `std` feature this function returns config unchanged.
152#[cfg(not(all(feature = "std", not(target_arch = "wasm32"))))]
153pub fn contextualize_config(result: Config) -> Config {
154    result
155}
156
157fn default_default_config() -> Config {
158    Config {
159        cases: 256,
160        max_local_rejects: 65_536,
161        max_global_rejects: 1024,
162        max_flat_map_regens: 1_000_000,
163        failure_persistence: None,
164        source_file: None,
165        test_name: None,
166        #[cfg(feature = "fork")]
167        fork: false,
168        #[cfg(feature = "timeout")]
169        timeout: 0,
170        #[cfg(feature = "std")]
171        max_shrink_time: 0,
172        max_shrink_iters: u32::MAX,
173        max_default_size_range: 100,
174        result_cache: noop_result_cache,
175        #[cfg(feature = "std")]
176        verbose: 0,
177        rng_algorithm: RngAlgorithm::default(),
178        rng_seed: RngSeed::Random,
179        _non_exhaustive: (),
180    }
181}
182
183// The default config, computed by combining environment variables and
184// defaults.
185#[cfg(feature = "std")]
186static DEFAULT_CONFIG: std::sync::LazyLock<Config> =
187    std::sync::LazyLock::new(|| {
188        let mut default_config = default_default_config();
189        default_config.failure_persistence = Some(Box::new(
190            crate::test_runner::FileFailurePersistence::default(),
191        ));
192        contextualize_config(default_config)
193    });
194
195/// The seed for the RNG, can either be random or specified as a u64.
196#[derive(Debug, Clone, Copy, PartialEq)]
197pub enum RngSeed {
198    /// Default case, use a random value
199    Random,
200    /// Use a specific value to generate a seed
201    Fixed(u64),
202}
203
204impl str::FromStr for RngSeed {
205    type Err = ();
206    fn from_str(s: &str) -> Result<Self, Self::Err> {
207        s.parse::<u64>().map(RngSeed::Fixed).map_err(|_| ())
208    }
209}
210
211impl fmt::Display for RngSeed {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        match self {
214            RngSeed::Random => write!(f, "random"),
215            RngSeed::Fixed(n) => write!(f, "{}", n),
216        }
217    }
218}
219
220/// Configuration for how a proptest test should be run.
221#[derive(Clone, Debug, PartialEq)]
222pub struct Config {
223    /// The number of successful test cases that must execute for the test as a
224    /// whole to pass.
225    ///
226    /// This does not include implicitly-replayed persisted failing cases.
227    ///
228    /// The default is 256, which can be overridden by setting the
229    /// `PROPTEST_CASES` environment variable. (The variable is only considered
230    /// when the `std` feature is enabled, which it is by default.)
231    pub cases: u32,
232
233    /// The maximum number of individual inputs that may be rejected before the
234    /// test as a whole aborts.
235    ///
236    /// The default is 65536, which can be overridden by setting the
237    /// `PROPTEST_MAX_LOCAL_REJECTS` environment variable. (The variable is only
238    /// considered when the `std` feature is enabled, which it is by default.)
239    pub max_local_rejects: u32,
240
241    /// The maximum number of combined inputs that may be rejected before the
242    /// test as a whole aborts.
243    ///
244    /// The default is 1024, which can be overridden by setting the
245    /// `PROPTEST_MAX_GLOBAL_REJECTS` environment variable. (The variable is
246    /// only considered when the `std` feature is enabled, which it is by
247    /// default.)
248    pub max_global_rejects: u32,
249
250    /// The maximum number of times all `Flatten` combinators will attempt to
251    /// regenerate values. This puts a limit on the worst-case exponential
252    /// explosion that can happen with nested `Flatten`s.
253    ///
254    /// The default is 1_000_000, which can be overridden by setting the
255    /// `PROPTEST_MAX_FLAT_MAP_REGENS` environment variable. (The variable is
256    /// only considered when the `std` feature is enabled, which it is by
257    /// default.)
258    pub max_flat_map_regens: u32,
259
260    /// Indicates whether and how to persist failed test results.
261    ///
262    /// When compiling with "std" feature (i.e. the standard library is available), the default
263    /// is `Some(Box::new(FileFailurePersistence::SourceParallel("proptest-regressions")))`.
264    ///
265    /// Without the standard library, the default is `None`, and no persistence occurs.
266    ///
267    /// See the docs of [`FileFailurePersistence`](enum.FileFailurePersistence.html)
268    /// and [`MapFailurePersistence`](struct.MapFailurePersistence.html) for more information.
269    ///
270    /// You can disable failure persistence with the `PROPTEST_DISABLE_FAILURE_PERSISTENCE`
271    /// environment variable but its not currently possible to set the persistence file
272    /// with an environment variable. (The variable is
273    /// only considered when the `std` feature is enabled, which it is by
274    /// default.)
275    pub failure_persistence: Option<Box<dyn FailurePersistence>>,
276
277    /// File location of the current test, relevant for persistence
278    /// and debugging.
279    ///
280    /// Note the use of `&str` rather than `Path` to be compatible with
281    /// `#![no_std]` use cases where `Path` is unavailable.
282    ///
283    /// See the docs of [`FileFailurePersistence`](enum.FileFailurePersistence.html)
284    /// for more information on how it may be used for persistence.
285    pub source_file: Option<&'static str>,
286
287    /// The fully-qualified name of the test being run, as would be passed to
288    /// the test executable to run just that test.
289    ///
290    /// This must be set if `fork` is `true`. Otherwise, it is unused. It is
291    /// automatically set by `proptest!`.
292    ///
293    /// This must include the crate name at the beginning, as produced by
294    /// `module_path!()`.
295    pub test_name: Option<&'static str>,
296
297    /// If true, tests are run in a subprocess.
298    ///
299    /// Forking allows proptest to work with tests which may fail by aborting
300    /// the process, causing a segmentation fault, etc, but can be a lot slower
301    /// in certain environments or when running a very large number of tests.
302    ///
303    /// For forking to work correctly, both the `Strategy` and the content of
304    /// the test case itself must be deterministic.
305    ///
306    /// This requires the "fork" feature, enabled by default.
307    ///
308    /// The default is `false`, which can be overridden by setting the
309    /// `PROPTEST_FORK` environment variable. (The variable is
310    /// only considered when the `std` feature is enabled, which it is by
311    /// default.)
312    #[cfg(feature = "fork")]
313    #[cfg_attr(docsrs, doc(cfg(feature = "fork")))]
314    pub fork: bool,
315
316    /// If non-zero, tests are run in a subprocess and each generated case
317    /// fails if it takes longer than this number of milliseconds.
318    ///
319    /// This implicitly enables forking, even if the `fork` field is `false`.
320    ///
321    /// The type here is plain `u32` (rather than
322    /// `Option<std::time::Duration>`) for the sake of ergonomics.
323    ///
324    /// This requires the "timeout" feature, enabled by default.
325    ///
326    /// Setting a timeout to less than the time it takes the process to start
327    /// up and initialise the first test case will cause the whole test to be
328    /// aborted.
329    ///
330    /// The default is `0` (i.e., no timeout), which can be overridden by
331    /// setting the `PROPTEST_TIMEOUT` environment variable. (The variable is
332    /// only considered when the `std` feature is enabled, which it is by
333    /// default.)
334    #[cfg(feature = "timeout")]
335    #[cfg_attr(docsrs, doc(cfg(feature = "timeout")))]
336    pub timeout: u32,
337
338    /// If non-zero, give up the shrinking process after this many milliseconds
339    /// have elapsed since the start of the shrinking process.
340    ///
341    /// This will not cause currently running test cases to be interrupted.
342    ///
343    /// This configuration is only available when the `std` feature is enabled
344    /// (which it is by default).
345    ///
346    /// The default is `0` (i.e., no limit), which can be overridden by setting
347    /// the `PROPTEST_MAX_SHRINK_TIME` environment variable. (The variable is
348    /// only considered when the `std` feature is enabled, which it is by
349    /// default.)
350    #[cfg(feature = "std")]
351    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
352    pub max_shrink_time: u32,
353
354    /// Give up on shrinking if more than this number of iterations of the test
355    /// code are run.
356    ///
357    /// Setting this to `u32::MAX` causes the actual limit to be four
358    /// times the number of test cases.
359    ///
360    /// Setting this value to `0` disables shrinking altogether.
361    ///
362    /// Note that the type of this field will change in a future version of
363    /// proptest to better accommodate its special values.
364    ///
365    /// The default is `u32::MAX`, which can be overridden by setting the
366    /// `PROPTEST_MAX_SHRINK_ITERS` environment variable. (The variable is only
367    /// considered when the `std` feature is enabled, which it is by default.)
368    pub max_shrink_iters: u32,
369
370    /// The default maximum size to `proptest::collection::SizeRange`. The default
371    /// strategy for collections (like `Vec`) use collections in the range of
372    /// `0..max_default_size_range`.
373    ///
374    /// The default is `100` which can be overridden by setting the
375    /// `PROPTEST_MAX_DEFAULT_SIZE_RANGE` environment variable. (The variable
376    /// is only considered when the `std` feature is enabled, which it is by
377    /// default.)
378    pub max_default_size_range: usize,
379
380    /// A function to create new result caches.
381    ///
382    /// The default is to do no caching. The easiest way to enable caching is
383    /// to set this field to `basic_result_cache` (though that is currently
384    /// only available with the `std` feature).
385    ///
386    /// This is useful for strategies which have a tendency to produce
387    /// duplicate values, or for tests where shrinking can take a very long
388    /// time due to exploring the same output multiple times.
389    ///
390    /// When caching is enabled, generated values themselves are not stored, so
391    /// this does not pose a risk of memory exhaustion for large test inputs
392    /// unless using extraordinarily large test case counts.
393    ///
394    /// Caching incurs its own overhead, and may very well make your test run
395    /// more slowly.
396    pub result_cache: fn() -> Box<dyn ResultCache>,
397
398    /// Set to non-zero values to cause proptest to emit human-targeted
399    /// messages to stderr as it runs.
400    ///
401    /// Greater values cause greater amounts of logs to be emitted. The exact
402    /// meaning of certain levels other than 0 is subject to change.
403    ///
404    /// - 0: No extra output.
405    /// - 1: Log test failure messages. In state machine tests, this level is
406    ///   used to print transitions.
407    /// - 2: Trace low-level details.
408    ///
409    /// This is only available with the `std` feature (enabled by default)
410    /// since on nostd proptest has no way to produce output.
411    ///
412    /// The default is `0`, which can be overridden by setting the
413    /// `PROPTEST_VERBOSE` environment variable. (The variable is only considered
414    /// when the `std` feature is enabled, which it is by default.)
415    #[cfg(feature = "std")]
416    #[cfg_attr(docsrs, doc(cfg(feature = "std")))]
417    pub verbose: u32,
418
419    /// The RNG algorithm to use when not using a user-provided RNG.
420    ///
421    /// The default is `RngAlgorithm::default()`, which can be overridden by
422    /// setting the `PROPTEST_RNG_ALGORITHM` environment variable to one of the following:
423    ///
424    /// - `xs` — `RngAlgorithm::XorShift`
425    /// - `cc` — `RngAlgorithm::ChaCha`
426    ///
427    /// (The variable is only considered when the `std` feature is enabled,
428    /// which it is by default.)
429    pub rng_algorithm: RngAlgorithm,
430
431    /// Seed used for the RNG. Set by using the PROPTEST_RNG_SEED environment variable
432    /// If the environment variable is undefined, a random seed is generated (this is the default option).
433    pub rng_seed: RngSeed,
434
435    // Needs to be public so FRU syntax can be used.
436    #[doc(hidden)]
437    pub _non_exhaustive: (),
438}
439
440impl Config {
441    /// Constructs a `Config` only differing from the `default()` in the
442    /// number of test cases required to pass the test successfully.
443    ///
444    /// This is simply a more concise alternative to using field-record update
445    /// syntax:
446    ///
447    /// ```
448    /// # use proptest::test_runner::Config;
449    /// assert_eq!(
450    ///     Config::with_cases(42),
451    ///     Config { cases: 42, .. Config::default() }
452    /// );
453    /// ```
454    pub fn with_cases(cases: u32) -> Self {
455        Self {
456            cases,
457            ..Config::default()
458        }
459    }
460
461    /// Constructs a `Config` only differing from the `default()` in the
462    /// source_file of the present test.
463    ///
464    /// This is simply a more concise alternative to using field-record update
465    /// syntax:
466    ///
467    /// ```
468    /// # use proptest::test_runner::Config;
469    /// assert_eq!(
470    ///     Config::with_source_file("computer/question"),
471    ///     Config { source_file: Some("computer/question"), .. Config::default() }
472    /// );
473    /// ```
474    pub fn with_source_file(source_file: &'static str) -> Self {
475        Self {
476            source_file: Some(source_file),
477            ..Config::default()
478        }
479    }
480
481    /// Constructs a `Config` only differing from the provided Config instance, `self`,
482    /// in the source_file of the present test.
483    ///
484    /// This is simply a more concise alternative to using field-record update
485    /// syntax:
486    ///
487    /// ```
488    /// # use proptest::test_runner::Config;
489    /// let a = Config::with_source_file("computer/question");
490    /// let b = a.clone_with_source_file("answer/42");
491    /// assert_eq!(
492    ///     a,
493    ///     Config { source_file: Some("computer/question"), .. Config::default() }
494    /// );
495    /// assert_eq!(
496    ///     b,
497    ///     Config { source_file: Some("answer/42"), .. Config::default() }
498    /// );
499    /// ```
500    pub fn clone_with_source_file(&self, source_file: &'static str) -> Self {
501        let mut result = self.clone();
502        result.source_file = Some(source_file);
503        result
504    }
505
506    /// Constructs a `Config` only differing from the `default()` in the
507    /// failure_persistence member.
508    ///
509    /// This is simply a more concise alternative to using field-record update
510    /// syntax:
511    ///
512    /// ```
513    /// # use proptest::test_runner::{Config, FileFailurePersistence};
514    /// assert_eq!(
515    ///     Config::with_failure_persistence(FileFailurePersistence::WithSource("regressions")),
516    ///     Config {
517    ///         failure_persistence: Some(Box::new(FileFailurePersistence::WithSource("regressions"))),
518    ///         .. Config::default()
519    ///     }
520    /// );
521    /// ```
522    pub fn with_failure_persistence<T>(failure_persistence: T) -> Self
523    where
524        T: FailurePersistence + 'static,
525    {
526        Self {
527            failure_persistence: Some(Box::new(failure_persistence)),
528            ..Default::default()
529        }
530    }
531
532    /// Return whether this configuration implies forking.
533    ///
534    /// This method exists even if the "fork" feature is disabled, in which
535    /// case it simply returns false.
536    pub fn fork(&self) -> bool {
537        self._fork() || self.timeout() > 0
538    }
539
540    #[cfg(feature = "fork")]
541    fn _fork(&self) -> bool {
542        self.fork
543    }
544
545    #[cfg(not(feature = "fork"))]
546    fn _fork(&self) -> bool {
547        false
548    }
549
550    /// Returns the configured timeout.
551    ///
552    /// This method exists even if the "timeout" feature is disabled, in which
553    /// case it simply returns 0.
554    #[cfg(feature = "timeout")]
555    pub fn timeout(&self) -> u32 {
556        self.timeout
557    }
558
559    /// Returns the configured timeout.
560    ///
561    /// This method exists even if the "timeout" feature is disabled, in which
562    /// case it simply returns 0.
563    #[cfg(not(feature = "timeout"))]
564    pub fn timeout(&self) -> u32 {
565        0
566    }
567
568    /// Returns the configured limit on shrinking iterations.
569    ///
570    /// This takes into account the special "automatic" behaviour.
571    pub fn max_shrink_iters(&self) -> u32 {
572        if u32::MAX == self.max_shrink_iters {
573            self.cases.saturating_mul(4)
574        } else {
575            self.max_shrink_iters
576        }
577    }
578
579    // Used by macros to force the config to be owned without depending on
580    // certain traits being `use`d.
581    #[allow(missing_docs)]
582    #[doc(hidden)]
583    pub fn __sugar_to_owned(&self) -> Self {
584        self.clone()
585    }
586}
587
588#[cfg(feature = "std")]
589impl Default for Config {
590    fn default() -> Self {
591        DEFAULT_CONFIG.clone()
592    }
593}
594
595#[cfg(not(feature = "std"))]
596impl Default for Config {
597    fn default() -> Self {
598        default_default_config()
599    }
600}