skip to content

In Rust's proptest crate, what does a `proptest!` test over strategies like `1u32..=20` and `prop::collection::vec` run, and why use `prop_assert!`?

level: middleimportance: should knowfreq 32%

answer

  1. strategies are values, not types
  2. the macro rewrites the signature
  3. 256 passing cases by default
  4. an early return instead of a panic

basics

~20 s

proptest! rewrites each fn name(x in strategy) into a zero-argument test that draws inputs from the strategies, runs the body until 256 cases pass by default and shrinks any failure; prop_assert! fails a case by returning an error, not panicking.

solid answer

~40 s

Inside `proptest! { ... }` each function keeps the attributes you wrote, so you still put `#[test]` on it, but its parameters are `pattern in strategy` pairs: `1u32..=20` is a strategy, and so are `any::<u16>()`, `prop::collection::vec(0u64..5_000, 1..50)` and anything built with `prop_map`. The macro turns the function into a zero-argument test whose body runs as a closure returning `Result<(), TestCaseError>`, and a `TestRunner` calls it with fresh inputs until 256 cases pass (the `cases` field of `ProptestConfig`, or the `PROPTEST_CASES` environment variable). `prop_assert!` returns `Err(TestCaseError::fail(..))` instead of panicking. A plain `assert!` panic is caught and shrunk too, but every panicking attempt prints to stderr, so `prop_assert!` keeps the report down to the final minimal case.

code

rust · 30 lines
rust
use super::*;
use proptest::prelude::*;

#[derive(Debug, Clone)]
struct Limits {
    capacity: u32,
    refill_ms: u64,
}

fn limits() -> impl Strategy<Value = Limits> {
    (1u32..=20, 1u64..=1_000).prop_map(|(capacity, refill_ms)| Limits { capacity, refill_ms })
}

proptest! {
    #[test]
    fn never_grants_more_than_refilled(
        l in limits(),
        gaps in prop::collection::vec(0u64..5_000, 1..50),
    ) {
        let clock = FakeClock::default();
        let mut bucket = TokenBucket::new(&clock, l.capacity, l.refill_ms);
        let mut granted = 0u64;
        for gap in &gaps {
            clock.sleep_ms(*gap);
            granted += u64::from(bucket.try_acquire());
        }
        let elapsed: u64 = gaps.iter().sum();
        prop_assert!(granted <= u64::from(l.capacity) + elapsed / l.refill_ms);
    }
}

go deeper

for a junior

Recall that proptest generates many inputs from ranges and collection strategies and checks a property on each, and that #[test] still goes on every function inside the block.

for a middle

Explain that the macro rewrites the function, runs 256 cases by default, and that prop_assert! returns an error instead of panicking; build a domain value with prop_map.

for a senior

Show judgment on strategy design: construct valid inputs instead of filtering, keep cases independent, raise the case count per block, and pick a property the code cannot satisfy by accident.

for a principal

Weigh where generated inputs pay off against example tests, and how case counts and nightly runs trade CI time for exploration depth across a large suite.

## What the macro does with your function `proptest!` is a `macro_rules!` macro from the **proptest** crate. Each item inside the block looks like a function whose parameters are `pattern in strategy` pairs, or `name: Type`, which means `any::<Type>()`. The macro rewrites each item into an ordinary **zero-argument function** that keeps every attribute you wrote, builds a `ProptestConfig`, and hands your body to a `TestRunner` as a closure returning `Result<(), TestCaseError>`. Two consequences follow: - You still write `#[test]` on each function. The macro copies attributes; it never adds one. Without `#[test]` the function still compiles, and the harness never runs it. - Because the body returns a `Result`, helpers that return `Result<(), TestCaseError>` can be called with `?`, and proptest's assertion macros can fail a case with an early `return`. ## Strategies are values, not types A **strategy** is a value implementing proptest's `Strategy` trait: it knows how to generate a value *and* how to simplify that value later. That is why one test can ask for a `u32` in `1..=20` and another for a `u32` in `0..5_000` without inventing a wrapper type for each. | Strategy | Generates | Shrinks toward | |---|---|---| | `1u32..=20` | integers in the range | the low end of the range | | `any::<u16>()` | any `u16`, through proptest's own `Arbitrary` trait | zero | | `prop::collection::vec(0u64..5_000, 1..50)` | a `Vec` of 1 to 49 elements | fewer elements (never below 1), then smaller ones | | `(a, b).prop_map(f)` | whatever `f` builds from the tuple | simpler `a` and `b`, re-mapped by `f` | | `s.prop_filter(reason, pred)` | values of `s` that pass `pred` | simpler values that still pass | `prop_map` is how you build domain types: the rate limiter's `Limits { capacity, refill_ms }` comes from a tuple of two ranges, so it shrinks field by field with no extra code. Filtering is the expensive route. Each value `prop_filter` throws away is a **local reject** (the default limit is 65,536, then the run aborts with "Too many local rejects"), and each case `prop_assume!` rejects inside the body is a **global reject** (default limit 1024, "Too many global rejects"). Build valid values rather than filtering invalid ones. ## How one run proceeds 1. The runner replays any seeds saved in the test's regression file by earlier failures. 2. It generates fresh inputs and runs the body until `cases` cases pass: 256 by default, changed with `#![proptest_config(ProptestConfig::with_cases(1000))]` as the block's first line or with the `PROPTEST_CASES` environment variable, which wins when both are set because the macro passes every config through proptest's environment overrides. 3. At the first failing case it **shrinks**: it simplifies the inputs step by step and keeps each simpler version only while the body still fails. 4. It panics with your message, the `minimal failing input` and counts of successes and rejects, and that panic fails the `#[test]`. ## `prop_assert!` versus `assert!` `prop_assert!(cond)` expands to `if !cond { return Err(TestCaseError::fail(..)) }`, with the file and line appended to the message. `prop_assert_eq!` and `prop_assert_ne!` follow the same pattern. - **Both routes shrink.** proptest catches a panic from `assert!`, `unwrap()` or a debug-build overflow and treats it as a failed case, exactly as it treats an `Err`. - **The difference is noise.** The default panic hook prints every panic, and shrinking runs the body many times. In one shrinking run of a planted bug, the `assert!` version printed 32 "panicked at" lines, the final report included; the `prop_assert!` version printed only that final one. - **Composition.** `prop_assert!` works in any helper returning `Result<_, TestCaseError>`, so shared invariant checks chain with `?`. ## The rate limiter's property The token bucket holds at most `capacity` tokens and earns one back every `refill_ms` milliseconds. Whatever gaps separate the calls, the number of granted calls can never exceed `capacity + elapsed / refill_ms`. That sentence is the **property**: a claim true for every input, checked against hundreds of generated gap sequences instead of three hand-picked ones. The test drives time with a hand-written fake clock, a struct whose `sleep_ms` adds to a `Cell<u64>`, lent to the bucket by reference so the test keeps advancing it between calls. Each case builds a fresh bucket and a fresh clock, because cases must not share state: shrinking re-runs the body with new inputs and expects the same verdict for the same input. When several properties need one expensive fixture, the closure form `proptest!(|(x in 0u32..42)| { ... })` runs inside an ordinary `#[test]` after the setup; it takes a config as an optional first argument, but proptest's fork and timeout features do not work in that form.

  • Why does this property use a hand-written fake clock rather than a mockall mock?
    Each case must advance time by generated gaps. A fake whose `sleep_ms` adds to a `Cell<u64>` does that in a few lines and carries no opinion about call counts. A mock would need a new `returning` closure per case and would check interactions the property does not care about, so any refactor of how often the bucket reads the clock would break it.
  • How do you give one property 5,000 cases without slowing every other proptest test?
    Put `#![proptest_config(ProptestConfig::with_cases(5_000))]` as the first line of that `proptest!` block; it applies to the functions in that block only. Setting `PROPTEST_CASES` overrides the count for every test in the run, that block included: in a check, a block configured for 5,000 cases ran three under `PROPTEST_CASES=3`. That suits a nightly job that wants deeper exploration everywhere.
  • What happens when a strategy uses prop_filter to reject most generated values?
    Every discarded value is a local reject. After 65,536 of them, the default `max_local_rejects`, the run aborts with "Too many local rejects" instead of passing or failing, and even before that the test slows down. Rewrite the strategy to construct valid values, for example with a narrower range or `prop_map`.

  • proptest reads the parameter types, so the ranges are only hints
  • Inside proptest! you can drop #[test] because the macro registers the test
  • A plain assert! inside proptest! turns shrinking off
  • proptest runs 100 cases by default
  • prop_assert! panics like assert! with a nicer message