| 1 | # Proptest |
| 2 | |
| 3 | [](https://github.com/proptest-rs/proptest/actions) |
| 4 | [](https://crates.io/crates/proptest) |
| 5 | [][book] |
| 6 | [][api-docs] |
| 7 | |
| 8 | [book]: https://proptest-rs.github.io/proptest/intro.html |
| 9 | [api-docs]: https://docs.rs/proptest/latest/proptest/ |
| 10 | |
| 11 | ## Book |
| 12 | |
| 13 | A detailed introduction to proptest can be found in the [book](https://proptest-rs.github.io/proptest/) |
| 14 | |
| 15 | ## Introduction |
| 16 | |
| 17 | Proptest is a property testing framework (i.e., the QuickCheck family) |
| 18 | inspired by the [Hypothesis](https://hypothesis.works/) framework for |
| 19 | Python. It allows to test that certain properties of your code hold for |
| 20 | arbitrary inputs, and if a failure is found, automatically finds the |
| 21 | minimal test case to reproduce the problem. Unlike QuickCheck, generation |
| 22 | and shrinking is defined on a per-value basis instead of per-type, which |
| 23 | makes it more flexible and simplifies composition. |
| 24 | |
| 25 | ### Status of this crate |
| 26 | |
| 27 | The crate is fairly close to being feature-complete and has not seen |
| 28 | substantial architectural changes in quite some time. At this point, it mainly |
| 29 | sees passive maintenance. |
| 30 | |
| 31 | See the [changelog](https://github.com/proptest-rs/proptest/blob/main/proptest/CHANGELOG.md) |
| 32 | for a full list of substantial historical changes, breaking and otherwise. |
| 33 | |
| 34 | ### MSRV |
| 35 | |
| 36 | The current MSRV of this crate is 1.82. |
| 37 | The MSRV is guaranteed to not exceed `<current stable release> - 7`, though in practice it may be lower than this - your mileage may vary. |
| 38 | If we change this policy in a backwards incompatible way (e.g. changing it to `<current stable release> - 1`), this constitutes a breaking change, and would be a major version bump (e.g. 1.1 -> 2.0). |
| 39 | |
| 40 | ### What is property testing? |
| 41 | |
| 42 | _Property testing_ is a system of testing code by checking that certain |
| 43 | properties of its output or behaviour are fulfilled for all inputs. These |
| 44 | inputs are generated automatically, and, critically, when a failing input |
| 45 | is found, the input is automatically reduced to a _minimal_ test case. |
| 46 | |
| 47 | Property testing is best used to complement traditional unit testing (i.e., |
| 48 | using specific inputs chosen by hand). Traditional tests can test specific |
| 49 | known edge cases, simple inputs, and inputs that were known in the past to |
| 50 | reveal bugs, whereas property tests will search for more complicated inputs |
| 51 | that cause problems. |
| 52 | |
| 53 | ## Getting Started |
| 54 | |
| 55 | Let's say we want to make a function that parses dates of the form |
| 56 | `YYYY-MM-DD`. We're not going to worry about _validating_ the date, any |
| 57 | triple of integers is fine. So let's bang something out real quick. |
| 58 | |
| 59 | ```rust,no_run |
| 60 | fn parse_date(s: &str) -> Option<(u32, u32, u32)> { |
| 61 | if 10 != s.len() { return None; } |
| 62 | if "-" != &s[4..5] || "-" != &s[7..8] { return None; } |
| 63 | |
| 64 | let year = &s[0..4]; |
| 65 | let month = &s[6..7]; |
| 66 | let day = &s[8..10]; |
| 67 | |
| 68 | year.parse::<u32>().ok().and_then( |
| 69 | |y| month.parse::<u32>().ok().and_then( |
| 70 | |m| day.parse::<u32>().ok().map( |
| 71 | |d| (y, m, d)))) |
| 72 | } |
| 73 | ``` |
| 74 | |
| 75 | It compiles, that means it works, right? Maybe not, let's add some tests. |
| 76 | |
| 77 | ```rust,ignore |
| 78 | #[test] |
| 79 | fn test_parse_date() { |
| 80 | assert_eq!(None, parse_date("2017-06-1")); |
| 81 | assert_eq!(None, parse_date("2017-06-170")); |
| 82 | assert_eq!(None, parse_date("2017006-17")); |
| 83 | assert_eq!(None, parse_date("2017-06017")); |
| 84 | assert_eq!(Some((2017, 06, 17)), parse_date("2017-06-17")); |
| 85 | } |
| 86 | ``` |
| 87 | |
| 88 | Tests pass, deploy to production! But now your application starts crashing, |
| 89 | and people are upset that you moved Christmas to February. Maybe we need to |
| 90 | be a bit more thorough. |
| 91 | |
| 92 | In `Cargo.toml`, add |
| 93 | |
| 94 | ```toml |
| 95 | [dev-dependencies] |
| 96 | proptest = "1.6.0" |
| 97 | ``` |
| 98 | |
| 99 | Now we can add some property tests to our date parser. But how do we test |
| 100 | the date parser for arbitrary inputs, without making another date parser in |
| 101 | the test to validate it? We won't need to as long as we choose our inputs |
| 102 | and properties correctly. But before correctness, there's actually an even |
| 103 | simpler property to test: _The function should not crash._ Let's start |
| 104 | there. |
| 105 | |
| 106 | ```rust,ignore |
| 107 | // Bring the macros and other important things into scope. |
| 108 | use proptest::prelude::*; |
| 109 | |
| 110 | proptest! { |
| 111 | #[test] |
| 112 | fn doesnt_crash(s in "\\PC*") { |
| 113 | parse_date(&s); |
| 114 | } |
| 115 | } |
| 116 | ``` |
| 117 | |
| 118 | What this does is take a literally random `&String` (ignore `\\PC*` for the |
| 119 | moment, we'll get back to that — if you've already figured it out, contain |
| 120 | your excitement for a bit) and give it to `parse_date()` and then throw the |
| 121 | output away. |
| 122 | |
| 123 | When we run this, we get a bunch of scary-looking output, eventually ending |
| 124 | with |
| 125 | |
| 126 | ```text |
| 127 | thread 'main' panicked at 'Test failed: byte index 4 is not a char boundary; it is inside 'ௗ' (bytes 2..5) of `aAௗ0㌀0`; minimal failing input: s = "aAௗ0㌀0" |
| 128 | successes: 102 |
| 129 | local rejects: 0 |
| 130 | global rejects: 0 |
| 131 | ' |
| 132 | ``` |
| 133 | |
| 134 | If we look at the top directory after the test fails, we'll see a new |
| 135 | `proptest-regressions` directory, which contains some files corresponding to |
| 136 | source files containing failing test cases. These are [_failure |
| 137 | persistence_](https://proptest-rs.github.io/proptest/proptest/failure-persistence.html) |
| 138 | files. The first thing we should do is add these to source control. |
| 139 | |
| 140 | ```text |
| 141 | $ git add proptest-regressions |
| 142 | ``` |
| 143 | |
| 144 | The next thing we should do is copy the failing case to a traditional unit |
| 145 | test since it has exposed a bug not similar to what we've tested in the |
| 146 | past. |
| 147 | |
| 148 | ```rust,ignore |
| 149 | #[test] |
| 150 | fn test_unicode_gibberish() { |
| 151 | assert_eq!(None, parse_date("aAௗ0㌀0")); |
| 152 | } |
| 153 | ``` |
| 154 | |
| 155 | Now, let's see what happened... we forgot about UTF-8! You can't just |
| 156 | blindly slice strings since you could split a character, in this case that |
| 157 | Tamil diacritic placed atop other characters in the string. |
| 158 | |
| 159 | In the interest of making the code changes as small as possible, we'll just |
| 160 | check that the string is ASCII and reject anything that isn't. |
| 161 | |
| 162 | ```rust,no_run |
| 163 | fn parse_date(s: &str) -> Option<(u32, u32, u32)> { |
| 164 | if 10 != s.len() { return None; } |
| 165 | |
| 166 | // NEW: Ignore non-ASCII strings so we don't need to deal with Unicode. |
| 167 | if !s.is_ascii() { return None; } |
| 168 | |
| 169 | if "-" != &s[4..5] || "-" != &s[7..8] { return None; } |
| 170 | |
| 171 | let year = &s[0..4]; |
| 172 | let month = &s[6..7]; |
| 173 | let day = &s[8..10]; |
| 174 | |
| 175 | year.parse::<u32>().ok().and_then( |
| 176 | |y| month.parse::<u32>().ok().and_then( |
| 177 | |m| day.parse::<u32>().ok().map( |
| 178 | |d| (y, m, d)))) |
| 179 | } |
| 180 | ``` |
| 181 | |
| 182 | The tests pass now! But we know there are still more problems, so let's |
| 183 | test more properties. |
| 184 | |
| 185 | Another property we want from our code is that it parses every valid date. |
| 186 | We can add another test to the `proptest!` section: |
| 187 | |
| 188 | ```rust,ignore |
| 189 | proptest! { |
| 190 | // snip... |
| 191 | |
| 192 | #[test] |
| 193 | fn parses_all_valid_dates(s in "[0-9]{4}-[0-9]{2}-[0-9]{2}") { |
| 194 | parse_date(&s).unwrap(); |
| 195 | } |
| 196 | } |
| 197 | ``` |
| 198 | |
| 199 | The thing to the right-hand side of `in` is actually a _regular |
| 200 | expression_, and `s` is chosen from strings which match it. So in our |
| 201 | previous test, `"\\PC*"` was generating arbitrary strings composed of |
| 202 | arbitrary non-control characters. Now, we generate things in the YYYY-MM-DD |
| 203 | format. |
| 204 | |
| 205 | The new test passes, so let's move on to something else. |
| 206 | |
| 207 | The final property we want to check is that the dates are actually parsed |
| 208 | _correctly_. Now, we can't do this by generating strings — we'd end up just |
| 209 | reimplementing the date parser in the test! Instead, we start from the |
| 210 | expected output, generate the string, and check that it gets parsed back. |
| 211 | |
| 212 | ```rust,ignore |
| 213 | proptest! { |
| 214 | // snip... |
| 215 | |
| 216 | #[test] |
| 217 | fn parses_date_back_to_original(y in 0u32..10000, |
| 218 | m in 1u32..13, d in 1u32..32) { |
| 219 | let (y2, m2, d2) = parse_date( |
| 220 | &format!("{:04}-{:02}-{:02}", y, m, d)).unwrap(); |
| 221 | // prop_assert_eq! is basically the same as assert_eq!, but doesn't |
| 222 | // cause a bunch of panic messages to be printed on intermediate |
| 223 | // test failures. Which one to use is largely a matter of taste. |
| 224 | prop_assert_eq!((y, m, d), (y2, m2, d2)); |
| 225 | } |
| 226 | } |
| 227 | ``` |
| 228 | |
| 229 | Here, we see that besides regexes, we can use any expression which is a |
| 230 | `proptest::strategy::Strategy`, in this case, integer ranges. |
| 231 | |
| 232 | The test fails when we run it. Though there's not much output this time. |
| 233 | |
| 234 | ```text |
| 235 | thread 'main' panicked at 'Test failed: assertion failed: `(left == right)` (left: `(0, 10, 1)`, right: `(0, 0, 1)`) at examples/dateparser_v2.rs:46; minimal failing input: y = 0, m = 10, d = 1 |
| 236 | successes: 2 |
| 237 | local rejects: 0 |
| 238 | global rejects: 0 |
| 239 | ', examples/dateparser_v2.rs:33 |
| 240 | note: Run with `RUST_BACKTRACE=1` for a backtrace. |
| 241 | ``` |
| 242 | |
| 243 | The failing input is `(y, m, d) = (0, 10, 1)`, which is a rather specific |
| 244 | output. Before thinking about why this breaks the code, let's look at what |
| 245 | proptest did to arrive at this value. At the start of our test function, |
| 246 | insert |
| 247 | |
| 248 | ```rust,ignore |
| 249 | println!("y = {}, m = {}, d = {}", y, m, d); |
| 250 | ``` |
| 251 | |
| 252 | Running the test again, we get something like this: |
| 253 | |
| 254 | ```text |
| 255 | y = 2497, m = 8, d = 27 |
| 256 | y = 9641, m = 8, d = 18 |
| 257 | y = 7360, m = 12, d = 20 |
| 258 | y = 3680, m = 12, d = 20 |
| 259 | y = 1840, m = 12, d = 20 |
| 260 | y = 920, m = 12, d = 20 |
| 261 | y = 460, m = 12, d = 20 |
| 262 | y = 230, m = 12, d = 20 |
| 263 | y = 115, m = 12, d = 20 |
| 264 | y = 57, m = 12, d = 20 |
| 265 | y = 28, m = 12, d = 20 |
| 266 | y = 14, m = 12, d = 20 |
| 267 | y = 7, m = 12, d = 20 |
| 268 | y = 3, m = 12, d = 20 |
| 269 | y = 1, m = 12, d = 20 |
| 270 | y = 0, m = 12, d = 20 |
| 271 | y = 0, m = 6, d = 20 |
| 272 | y = 0, m = 9, d = 20 |
| 273 | y = 0, m = 11, d = 20 |
| 274 | y = 0, m = 10, d = 20 |
| 275 | y = 0, m = 10, d = 10 |
| 276 | y = 0, m = 10, d = 5 |
| 277 | y = 0, m = 10, d = 3 |
| 278 | y = 0, m = 10, d = 2 |
| 279 | y = 0, m = 10, d = 1 |
| 280 | ``` |
| 281 | |
| 282 | The test failure message said there were two successful cases; we see these |
| 283 | at the very top, `2497-08-27` and `9641-08-18`. The next case, |
| 284 | `7360-12-20`, failed. There's nothing immediately obviously special about |
| 285 | this date. Fortunately, proptest reduced it to a much simpler case. First, |
| 286 | it rapidly reduced the `y` input to `0` at the beginning, and similarly |
| 287 | reduced the `d` input to the minimum allowable value of `1` at the end. |
| 288 | Between those two, though, we see something different: it tried to shrink |
| 289 | `12` to `6`, but then ended up raising it back up to `10`. This is because |
| 290 | the `0000-06-20` and `0000-09-20` test cases _passed_. |
| 291 | |
| 292 | In the end, we get the date `0000-10-01`, which apparently gets parsed as |
| 293 | `0000-00-01`. Again, this failing case was added to the failure persistence |
| 294 | file, and we should add this as its own unit test: |
| 295 | |
| 296 | ```text |
| 297 | $ git add proptest-regressions |
| 298 | ``` |
| 299 | |
| 300 | ```rust,ignore |
| 301 | #[test] |
| 302 | fn test_october_first() { |
| 303 | assert_eq!(Some((0, 10, 1)), parse_date("0000-10-01")); |
| 304 | } |
| 305 | ``` |
| 306 | |
| 307 | Now to figure out what's broken in the code. Even without the intermediate |
| 308 | input, we can say with reasonable confidence that the year and day parts |
| 309 | don't come into the picture since both were reduced to the minimum |
| 310 | allowable input. The month input was _not_, but was reduced to `10`. This |
| 311 | means we can infer that there's something special about `10` that doesn't |
| 312 | hold for `9`. In this case, that "special something" is being two digits |
| 313 | wide. In our code: |
| 314 | |
| 315 | ```rust,ignore |
| 316 | let month = &s[6..7]; |
| 317 | ``` |
| 318 | |
| 319 | We were off by one, and need to use the range `5..7`. After fixing this, |
| 320 | the test passes. |
| 321 | |
| 322 | The `proptest!` macro has some additional syntax, including for setting |
| 323 | configuration for things like the number of test cases to generate. See its |
| 324 | [documentation](https://docs.rs/proptest/latest/proptest/macro.proptest.html) |
| 325 | for more details. |
| 326 | |
| 327 | ## Differences between QuickCheck and Proptest |
| 328 | |
| 329 | QuickCheck and Proptest are similar in many ways: both generate random |
| 330 | inputs for a function to check certain properties, and automatically shrink |
| 331 | inputs to minimal failing cases. |
| 332 | |
| 333 | The one big difference is that QuickCheck generates and shrinks values |
| 334 | based on type alone, whereas Proptest uses explicit `Strategy` objects. The |
| 335 | QuickCheck approach has a lot of disadvantages in comparison: |
| 336 | |
| 337 | - QuickCheck can only define one generator and shrinker per type. If you need a |
| 338 | custom generation strategy, you need to wrap it in a newtype and implement |
| 339 | traits on that by hand. In Proptest, you can define arbitrarily many |
| 340 | different strategies for the same type, and there are plenty built-in. |
| 341 | |
| 342 | - For the same reason, QuickCheck has a single "size" configuration that tries |
| 343 | to define the range of values generated. If you need an integer between 0 and |
| 344 | 100 and another between 0 and 1000, you probably need to do another newtype. |
| 345 | In Proptest, you can directly just express that you want a `0..100` integer |
| 346 | and a `0..1000` integer. |
| 347 | |
| 348 | - Types in QuickCheck are not easily composable. Defining `Arbitrary` and |
| 349 | `Shrink` for a new struct which is simply produced by the composition of its |
| 350 | fields requires implementing both by hand, including a bidirectional mapping |
| 351 | between the struct and a tuple of its fields. In Proptest, you can make a |
| 352 | tuple of the desired components and then `prop_map` it into the desired form. |
| 353 | Shrinking happens automatically in terms of the input types. |
| 354 | |
| 355 | - Because constraints on values cannot be expressed in QuickCheck, generation |
| 356 | and shrinking may lead to a lot of input rejections. Strategies in Proptest |
| 357 | are aware of simple constraints and do not generate or shrink to values that |
| 358 | violate them. |
| 359 | |
| 360 | The author of Hypothesis also has an [article on this |
| 361 | topic](https://hypothesis.works/articles/integrated-shrinking/). |
| 362 | |
| 363 | Of course, there's also some relative downsides that fall out of what |
| 364 | Proptest does differently: |
| 365 | |
| 366 | - Generating complex values in Proptest can be up to an order of magnitude |
| 367 | slower than in QuickCheck. This is because QuickCheck performs stateless |
| 368 | shrinking based on the output value, whereas Proptest must hold on to all the |
| 369 | intermediate states and relationships in order for its richer shrinking model |
| 370 | to work. |
| 371 | |
| 372 | ## Limitations of Property Testing |
| 373 | |
| 374 | Given infinite time, property testing will eventually explore the whole |
| 375 | input space to a test. However, time is not infinite, so only a randomly |
| 376 | sampled portion of the input space can be explored. This means that |
| 377 | property testing is extremely unlikely to find single-value edge cases in a |
| 378 | large space. For example, the following test will virtually always pass: |
| 379 | |
| 380 | ```rust |
| 381 | use proptest::prelude::*; |
| 382 | |
| 383 | proptest! { |
| 384 | #[test] |
| 385 | fn i64_abs_is_never_negative(a: i64) { |
| 386 | // This actually fails if a == i64::MIN, but randomly picking one |
| 387 | // specific value out of 2⁶⁴ is overwhelmingly unlikely. |
| 388 | assert!(a.abs() >= 0); |
| 389 | } |
| 390 | } |
| 391 | ``` |
| 392 | |
| 393 | Because of this, traditional unit testing with intelligently selected cases |
| 394 | is still necessary for many kinds of problems. |
| 395 | |
| 396 | Similarly, in some cases it can be hard or impossible to define a strategy |
| 397 | which actually produces useful inputs. A strategy of `.{1,4096}` may be |
| 398 | great to fuzz a C parser, but is highly unlikely to produce anything that |
| 399 | makes it to a code generator. |
| 400 | |
| 401 | # Acknowledgements |
| 402 | |
| 403 | This crate wouldn't have come into existence had it not been for the [Rust port |
| 404 | of QuickCheck](https://github.com/BurntSushi/quickcheck) and the |
| 405 | [`regex_generate`](https://github.com/CryptArchy/regex_generate) crate which |
| 406 | gave wonderful examples of what is possible. |
| 407 | |
| 408 | ## Contribution |
| 409 | |
| 410 | Unless you explicitly state otherwise, any contribution intentionally submitted |
| 411 | for inclusion in the work by you, as defined in the Apache-2.0 license, shall |
| 412 | be dual licensed as above, without any additional terms or conditions. |