liveBook · Manning

Proptest

As explained in Code Like a Pro in Rust

proptest is a Rust property-testing crate that generates test cases from input strategies and shrinks failures to minimal examples.

proptest is a Rust property-testing crate that generates test inputs, checks assertions across many cases, and reports a minimal failing input. It complements tests for known values rather than replacing them. section 6.3

Use proptest to:

  • Generate typed inputs directly from a property-test function, such as arbitrary i64 operands. section 6.3
  • Shrink failures into actionable counterexamples; an overflowing adder reports a minimal failing pair. section 6.3
  • Compare a rewritten implementation with a trusted implementation across generated cases. section 6.7.4
  • Control generated ranges and collection sizes, while accounting for additional CPU cost and side effects. section 6.3 section 7.4.2

Finding overflow in a generic adder

A proptest test generates two i64 values and checks that add(a, b) equals a + b. The test exposes overflow and prints the failing operands; changing the implementation and assertion to wrapping addition makes the test pass. section 6.3

Listing 7.9 Proptest-based integration test with quicksort
use proptest::prelude::*;
 
proptest! {
    #[test]
    fn test_quicksort_proptest(
        vec in prop::collection::vec(prop::num::i64::ANY, 0..1000)
    ) {                                        #1
        use quicksort_proptest::Quicksort;
 
        let mut vec_sorted = vec.clone();
        vec_sorted.sort();                     #2
 
        let mut vec_quicksorted = vec.clone();
        vec_quicksorted.quicksort();           #3
 
        assert_eq!(vec_quicksorted, vec_sorted);
    }
}

The quicksort integration test generates vectors of arbitrary i64 values with lengths from 0 to 999, then compares quicksort against Rust sorting. section 7.4.2

How Code Like a Pro in Rust covers it

How deep it goes
Explains strategies, generated cases, shrinking, and trade-offs, but does not detail the crate’s internal shrinking algorithms.
Examples
Demonstrates generic addition, wrapping addition, FizzBuzz rewrites, and quicksort over generated integer vectors.
What it assumes
Assumes familiarity with Rust tests, assertions, and implementations being compared.
What you can do after
Diagnose/debug with it by generating edge cases, shrinking failures, and comparing alternate implementations.
How it connects
Connects property testing with QuickCheck, unit testing, integration testing, differential testing, and reference implementations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Code Like a Pro in Rust. The section links point to the parts of the book it draws on.