#testing #data #sample #sampling #strategies #machinery #counterexamples

dev sample-test

Sampling strategies and machinery for testing arbitrary data

4 releases

0.2.1 Mar 1, 2024
0.2.0 Mar 1, 2024
0.1.1 Jun 26, 2023
0.1.0 Jun 26, 2023

#81 in Procedural macros

Download history 1965/week @ 2024-07-23 2337/week @ 2024-07-30 1974/week @ 2024-08-06 2318/week @ 2024-08-13 1709/week @ 2024-08-20 1741/week @ 2024-08-27 1333/week @ 2024-09-03 2096/week @ 2024-09-10 1954/week @ 2024-09-17 2534/week @ 2024-09-24 1876/week @ 2024-10-01 1535/week @ 2024-10-08 1997/week @ 2024-10-15 2038/week @ 2024-10-22 1718/week @ 2024-10-29 1423/week @ 2024-11-05

7,513 downloads per month
Used in 6 crates

Apache-2.0

20KB
350 lines

sample-test: utilities for sample testing

Create tests that sample arbitrary data to produce counterexamples for a given proposition:

use sample_std::VecSampler;
use sample_test::{sample_test, TestResult};

#[sample_test]
fn age_range(#[sample(VecSampler { el: 1..25, length: 0..50 })] ages: Vec<u8>) -> TestResult {
    if ages.iter().all(|a| *a < 5) {
        TestResult::discard()
    } else {
        TestResult::from_bool(ages.iter().all(|a| *a < 25))
    }
}

Prior Work

This library was heavily inspired by quickcheck and proptest.

Here's where it differs:

  • quickcheck works at the type level, and thus creating a new sampling strategy requires an entirely new type. This gets painfully verbose with complex types and many different sampling strategies.
  • proptest uses macros to create strategies, and creates a tree of seed values to shrink data. This tree can get very large for recursive data, and macros can be a pain to work with.

This library attempts to split the difference. It allows user-defined Sample strategies which are fed into tests. Shrinking, like with quickcheck, operates directly on generated values. This avoids the need to create and maintain the seed tree used by proptest, and allows this library to scale up to larger generated data sizes.

Instead of macros, this library and any downstream users rely heavily on Sample combinators. This is inspired by Iterator composition which is very performant and concise, all without the need for any macros.

The tradeoffs are:

  • sample-test is slightly more complicated than quickcheck, with the benefit of easier definition of sampling strategies.
  • sample-test is not as good at shrinking as proptest as it does not record the seed values that were used to generate a given output.

Dependencies

~4–5.5MB
~106K SLoC