Debian Codegraph @

README.md

raw symbols SCIP
1 # quickcheck
2
3 QuickCheck is a way to do property based testing using randomly generated
4 input. This crate comes with the ability to randomly generate and shrink
5 integers, floats, tuples, booleans, lists, strings, options and results.
6 All QuickCheck needs is a property function—it will then randomly generate
7 inputs to that function and call the property for each set of inputs. If the
8 property fails (whether by a runtime error like index out-of-bounds or by not
9 satisfying your property), the inputs are "shrunk" to find a smaller
10 counter-example.
11
12 The shrinking strategies for lists and numbers use a binary search to cover
13 the input space quickly. (It should be the same strategy used in
14 [Koen Claessen's QuickCheck for
15 Haskell](https://hackage.haskell.org/package/QuickCheck).)
16
17 [![Build status](https://github.com/BurntSushi/quickcheck/workflows/ci/badge.svg)](https://github.com/BurntSushi/quickcheck/actions)
18 [![crates.io](https://img.shields.io/crates/v/quickcheck.svg)](https://crates.io/crates/quickcheck)
19
20 Dual-licensed under MIT or the [UNLICENSE](https://unlicense.org/).
21
22 ## Documentation
23
24 The API is fully documented:
25 [https://docs.rs/quickcheck](https://docs.rs/quickcheck).
26
27 ## Simple example
28
29 Here's an example that tests a function that reverses a vector:
30
31 ```rust
32 fn reverse<T: Clone>(xs: &[T]) -> Vec<T> {
33 let mut rev = vec![];
34 for x in xs.iter() {
35 rev.insert(0, x.clone())
36 }
37 rev
38 }
39
40 #[cfg(test)]
41 mod tests {
42 use quickcheck::quickcheck;
43 use super::reverse;
44
45 quickcheck! {
46 fn prop(xs: Vec<u32>) -> bool {
47 xs == reverse(&reverse(&xs))
48 }
49 }
50 }
51 ```
52
53 This example uses the `quickcheck!` macro, which is backwards compatible with
54 old versions of Rust.
55
56 ## The `#[quickcheck]` attribute
57
58 To make it easier to write QuickCheck tests, the `#[quickcheck]` attribute
59 will convert a property function into a `#[test]` function.
60
61 To use the `#[quickcheck]` attribute, you must import the `quickcheck` macro
62 from the `quickcheck_macros` crate:
63
64 ```rust
65 fn reverse<T: Clone>(xs: &[T]) -> Vec<T> {
66 let mut rev = vec![];
67 for x in xs {
68 rev.insert(0, x.clone())
69 }
70 rev
71 }
72
73 #[cfg(test)]
74 mod tests {
75 use quickcheck_macros::quickcheck;
76 use super::reverse;
77
78 #[quickcheck]
79 fn double_reversal_is_identity(xs: Vec<isize>) -> bool {
80 xs == reverse(&reverse(&xs))
81 }
82 }
83 ```
84
85 ## Installation
86
87 `quickcheck` is on `crates.io`, so you can include it in your project like so:
88
89 ```toml
90 [dependencies]
91 quickcheck = "1"
92 ```
93
94 If you're only using `quickcheck` in your test code, then you can add it as a
95 development dependency instead:
96
97 ```toml
98 [dev-dependencies]
99 quickcheck = "1"
100 ```
101
102 If you want to use the `#[quickcheck]` attribute, then add `quickcheck_macros`
103
104 ```toml
105 [dev-dependencies]
106 quickcheck = "1"
107 quickcheck_macros = "1"
108 ```
109
110 N.B. When using `quickcheck` (either directly or via the attributes),
111 `RUST_LOG=quickcheck` enables `info!` so that it shows useful output
112 (like the number of tests passed). This is **not** needed to show
113 witnesses for failures.
114
115 Crate features:
116
117 - `"use_logging"`: (Enabled by default.) Enables the log messages governed
118 `RUST_LOG`.
119 - `"regex"`: (Enabled by default.) Enables the use of regexes with
120 `env_logger`.
121
122 ## Minimum Rust version policy
123
124 This crate's minimum supported `rustc` version is `1.85.0`.
125
126 The current policy is that the minimum Rust version required to use this crate
127 can be increased in minor version updates. For example, if `crate 1.0` requires
128 Rust 1.20.0, then `crate 1.0.z` for all values of `z` will also require Rust
129 1.20.0 or newer. However, `crate 1.y` for `y > 0` may require a newer minimum
130 version of Rust.
131
132 In general, this crate will be conservative with respect to the minimum
133 supported version of Rust.
134
135 With all of that said, currently, `rand` is a public dependency of
136 `quickcheck`. Therefore, the MSRV policy above only applies when it is more
137 aggressive than `rand`'s MSRV policy. Otherwise, `quickcheck` will defer to
138 `rand`'s MSRV policy.
139
140 ## Compatibility
141
142 In general, this crate considers the `Arbitrary` implementations provided as
143 implementation details. Strategies may or may not change over time, which may
144 cause new test failures, presumably due to the discovery of new bugs due to a
145 new kind of witness being generated. These sorts of changes may happen in
146 semver compatible releases.
147
148 ## Alternative Rust crates for property testing
149
150 The [`proptest`](https://docs.rs/proptest) crate is inspired by the
151 [Hypothesis](https://hypothesis.works/) framework for Python.
152 You can read a comparison between `proptest` and `quickcheck`
153 [here](https://github.com/proptest-rs/proptest/blob/main/proptest/README.md#differences-between-quickcheck-and-proptest)
154 and
155 [here](https://github.com/proptest-rs/proptest/issues/15#issuecomment-348382287).
156 In particular, `proptest` improves on the concept of shrinking. So if you've
157 ever had problems/frustration with shrinking in `quickcheck`, then `proptest`
158 might be worth a try!
159
160 ## Alternatives for fuzzing
161
162 Please see the
163 [Rust Fuzz Book](https://rust-fuzz.github.io/book/introduction.html)
164 and the
165 [`arbitrary`](https://crates.io/crates/arbitrary) crate.
166
167 ## Discarding test results (or, properties are polymorphic!)
168
169 Sometimes you want to test a property that only holds for a *subset* of the
170 possible inputs, so that when your property is given an input that is outside
171 of that subset, you'd discard it. In particular, the property should *neither*
172 pass nor fail on inputs outside of the subset you want to test. But properties
173 return boolean values—which either indicate pass or fail.
174
175 To fix this, we need to take a step back and look at the type of the
176 `quickcheck` function:
177
178 ```rust
179 pub fn quickcheck<A: Testable>(f: A) {
180 // elided
181 }
182 ```
183
184 So `quickcheck` can test any value with a type that satisfies the `Testable`
185 trait. Great, so what is this `Testable` business?
186
187 ```rust
188 pub trait Testable {
189 fn result(&self, &mut Gen) -> TestResult;
190 }
191 ```
192
193 This trait states that a type is testable if it can produce a `TestResult`
194 given a source of randomness. (A `TestResult` stores information about the
195 results of a test, like whether it passed, failed or has been discarded.)
196
197 Sure enough, `bool` satisfies the `Testable` trait:
198
199 ```rust
200 impl Testable for bool {
201 fn result(&self, _: &mut Gen) -> TestResult {
202 TestResult::from_bool(*self)
203 }
204 }
205 ```
206
207 But in the example, we gave a *function* to `quickcheck`. Yes, functions can
208 satisfy `Testable` too!
209
210 ```rust
211 impl<A: Arbitrary + Debug, B: Testable> Testable for fn(A) -> B {
212 fn result(&self, g: &mut Gen) -> TestResult {
213 // elided
214 }
215 }
216 ```
217
218 Which says that a function satisfies `Testable` if and only if it has a single
219 parameter type (whose values can be randomly generated and shrunk) and returns
220 any type (that also satisfies `Testable`). So a function with type `fn(usize)
221 -> bool` satisfies `Testable` since `usize` satisfies `Arbitrary` and `bool`
222 satisfies `Testable`.
223
224 So to discard a test, we need to return something other than `bool`. What if we
225 just returned a `TestResult` directly? That should work, but we'll need to
226 make sure `TestResult` satisfies `Testable`:
227
228 ```rust
229 impl Testable for TestResult {
230 fn result(&self, _: &mut Gen) -> TestResult { self.clone() }
231 }
232 ```
233
234 Now we can test functions that return a `TestResult` directly.
235
236 As an example, let's test our reverse function to make sure that the reverse of
237 a vector of length 1 is equal to the vector itself.
238
239 ```rust
240 fn prop(xs: Vec<isize>) -> TestResult {
241 if xs.len() != 1 {
242 return TestResult::discard()
243 }
244 TestResult::from_bool(xs == reverse(&xs))
245 }
246 quickcheck(prop as fn(Vec<isize>) -> TestResult);
247 ```
248
249 (A full working program for this example is in
250 [`examples/reverse_single.rs`](https://github.com/BurntSushi/quickcheck/blob/master/examples/reverse_single.rs).)
251
252 So now our property returns a `TestResult`, which allows us to encode a bit
253 more information. There are a few more
254 [convenience functions defined for the `TestResult`
255 type](https://docs.rs/quickcheck/*/quickcheck/struct.TestResult.html).
256 For example, we can't just return a `bool`, so we convert a `bool` value to a
257 `TestResult`.
258
259 (The ability to discard tests allows you to get similar functionality as
260 Haskell's `==>` combinator.)
261
262 N.B. Since discarding a test means it neither passes nor fails, `quickcheck`
263 will try to replace the discarded test with a fresh one. However, if your
264 condition is seldom met, it's possible that `quickcheck` will have to settle
265 for running fewer tests than usual. By default, if `quickcheck` can't find
266 `100` valid tests after trying `10,000` times, then it will give up.
267 These parameters may be changed using
268 [`QuickCheck::tests`](https://docs.rs/quickcheck/*/quickcheck/struct.QuickCheck.html#method.tests)
269 and [`QuickCheck::max_tests`](https://docs.rs/quickcheck/*/quickcheck/struct.QuickCheck.html#method.max_tests),
270 or by setting the `QUICKCHECK_TESTS` and `QUICKCHECK_MAX_TESTS`
271 environment variables.
272 There is also `QUICKCHECK_MIN_TESTS_PASSED` which sets the minimum number of
273 valid tests that need pass (defaults to `0`) in order for it to be considered a
274 success.
275
276 ## Shrinking
277
278 Shrinking is a crucial part of QuickCheck that simplifies counter-examples for
279 your properties automatically. For example, if you erroneously defined a
280 function for reversing vectors as: (my apologies for the contrived example)
281
282 ```rust
283 fn reverse<T: Clone>(xs: &[T]) -> Vec<T> {
284 let mut rev = vec![];
285 for i in 1..xs.len() {
286 rev.insert(0, xs[i].clone())
287 }
288 rev
289 }
290 ```
291
292 And a property to test that `xs == reverse(reverse(xs))`:
293
294 ```rust
295 fn prop(xs: Vec<isize>) -> bool {
296 xs == reverse(&reverse(&xs))
297 }
298 quickcheck(prop as fn(Vec<isize>) -> bool);
299 ```
300
301 Then without shrinking, you might get a counter-example like:
302
303 ```text
304 [quickcheck] TEST FAILED. Arguments: ([-17, 13, -12, 17, -8, -10, 15, -19,
305 -19, -9, 11, -5, 1, 19, -16, 6])
306 ```
307
308 Which is pretty mysterious. But with shrinking enabled, you're nearly
309 guaranteed to get this counter-example every time:
310
311 ```text
312 [quickcheck] TEST FAILED. Arguments: ([0])
313 ```
314
315 Which is going to be much easier to debug.
316
317 ## More Thorough Checking
318
319 Quickcheck uses random input to test, so it won't
320 always find bugs that could be uncovered with a particular
321 property. You can improve your odds of finding these latent
322 bugs by spending more CPU cycles asking quickcheck to find
323 them for you. There are a few different ways to do this, and
324 which one you choose is mostly a matter of taste.
325
326 If you are finding yourself doing this sort of thing a
327 lot, you might also be interested in trying out
328 [`cargo fuzz`](https://github.com/rust-fuzz/cargo-fuzz),
329 which runs in a loop by default.
330
331 ### Running in a Loop
332
333 One approach is to run your quickcheck properties in a loop that
334 just keeps going until you tell it to stop or it finds a bug.
335 For example, you could use a bash script such as the following
336 one.
337
338 ```bash
339 #!/usr/bin/bash
340
341 while true
342 do
343 cargo test qc_
344 if [[ x$? != x0 ]] ; then
345 exit $?
346 fi
347 done
348 ```
349
350 One thing to note is that this script passes the `qc_` filter to
351 `cargo test`. This assumes that you've prefixed all your quickcheck
352 properties with `qc_`. You could leave off the filter, but then
353 you would be running all your deterministic tests as well, which
354 would take time away from quickcheck!
355
356 Checking the return code and exiting is also important. Without that
357 test, you won't ever notice when a failure happens.
358
359 ### Cranking the Number of Tests
360
361 Another approach is to just ask quickcheck to run properties more
362 times. You can do this either via the
363 [tests()](https://docs.rs/quickcheck/*/quickcheck/struct.QuickCheck.html#method.tests)
364 method, or via the `QUICKCHECK_TESTS` environment variable.
365 This will cause quickcheck to run for a much longer time. Unlike,
366 the loop approach this will take a bounded amount of time, which
367 makes it more suitable for something like a release cycle that
368 wants to really hammer your software.
369
370 ### Making Arbitrary Smarter
371
372 This approach entails spending more time generating interesting
373 inputs in your implementations of Arbitrary. The idea is to
374 focus on the corner cases. This approach can be tricky because
375 programmers are not usually great at intuiting corner cases,
376 and the whole idea of property checking is to take that burden
377 off the programmer. Despite the theoretical discomfort, this
378 approach can turn out to be practical.
379
380 ## Generating Structs
381
382 It is very simple to generate structs in QuickCheck. Consider the following
383 example, where the struct `Point` is defined:
384
385 ```rust
386 struct Point {
387 x: i32,
388 y: i32,
389 }
390 ```
391
392 In order to generate a random `Point` instance, you need to implement
393 the trait `Arbitrary` for the struct `Point`:
394
395 ```rust
396 use quickcheck::{Arbitrary, Gen};
397
398 impl Arbitrary for Point {
399 fn arbitrary(g: &mut Gen) -> Point {
400 Point {
401 x: i32::arbitrary(g),
402 y: i32::arbitrary(g),
403 }
404 }
405 }
406 ```
407
408 ## Case study: The Sieve of Eratosthenes
409
410 The [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes)
411 is a simple and elegant way to find all primes less than or equal to `N`.
412 Briefly, the algorithm works by allocating an array with `N` slots containing
413 booleans. Slots marked with `false` correspond to prime numbers (or numbers
414 not known to be prime while building the sieve) and slots marked with `true`
415 are known to not be prime. For each `n`, all of its multiples in this array
416 are marked as true. When all `n` have been checked, the numbers marked `false`
417 are returned as the primes.
418
419 As you might imagine, there's a lot of potential for off-by-one errors, which
420 makes it ideal for randomized testing. So let's take a look at my
421 implementation and see if we can spot the bug:
422
423 ```rust
424 fn sieve(n: usize) -> Vec<usize> {
425 if n <= 1 {
426 return vec![];
427 }
428
429 let mut marked = vec![false; n+1];
430 marked[0] = true;
431 marked[1] = true;
432 marked[2] = true;
433 for p in 2..n {
434 for i in (2*p..n).filter(|&n| n % p == 0) {
435 marked[i] = true;
436 }
437 }
438 marked.iter()
439 .enumerate()
440 .filter_map(|(i, &m)| if m { None } else { Some(i) })
441 .collect()
442 }
443 ```
444
445 Let's try it on a few inputs by hand:
446
447 ```text
448 sieve(3) => [2, 3]
449 sieve(5) => [2, 3, 5]
450 sieve(8) => [2, 3, 5, 7, 8] # !!!
451 ```
452
453 Something has gone wrong! But where? The bug is rather subtle, but it's an
454 easy one to make. It's OK if you can't spot it, because we're going to use
455 QuickCheck to help us track it down.
456
457 Even before looking at some example outputs, it's good to try and come up with
458 some *properties* that are always satisfiable by the output of the function. An
459 obvious one for the prime number sieve is to check if all numbers returned are
460 prime. For that, we'll need an `is_prime` function:
461
462 ```rust
463 fn is_prime(n: usize) -> bool {
464 n != 0 && n != 1 && (2..).take_while(|i| i*i <= n).all(|i| n % i != 0)
465 }
466 ```
467
468 All this is doing is checking to see if any number in `[2, sqrt(n)]` divides
469 `n` with base cases for `0` and `1`.
470
471 Now we can write our QuickCheck property:
472
473 ```rust
474 fn prop_all_prime(n: usize) -> bool {
475 sieve(n).into_iter().all(is_prime)
476 }
477 ```
478
479 And finally, we need to invoke `quickcheck` with our property:
480
481 ```rust
482 fn main() {
483 quickcheck(prop_all_prime as fn(usize) -> bool);
484 }
485 ```
486
487 A fully working source file with this code is in
488 [`examples/sieve.rs`](https://github.com/BurntSushi/quickcheck/blob/master/examples/sieve.rs).
489
490 The output of running this program has this message:
491
492 ```text
493 [quickcheck] TEST FAILED. Arguments: (4)
494 ```
495
496 Which says that `sieve` failed the `prop_all_prime` test when given `n = 4`.
497 Because of shrinking, it was able to find a (hopefully) minimal counter-example
498 for our property.
499
500 With such a short counter-example, it's hopefully a bit easier to narrow down
501 where the bug is. Since `4` is returned, it's likely never marked as being not
502 prime. Since `4` is a multiple of `2`, its slot should be marked as `true` when
503 `p = 2` on these lines:
504
505 ```rust
506 for i in (2*p..n).filter(|&n| n % p == 0) {
507 marked[i] = true;
508 }
509 ```
510
511 Ah! But does the `..` (range) operator include `n`? Nope! This particular
512 operator is a half-open interval.
513
514 A `2*p..n` range will never yield `4` when `n = 4`. When we change this to
515 `2*p..n+1`, all tests pass.
516
517 In addition, if our bug happened to result in an index out-of-bounds error,
518 then `quickcheck` can handle it just like any other failure—including
519 shrinking on failures caused by runtime errors.
520
521 But hold on... we're not done yet. Right now, our property tests that all
522 the numbers returned by `sieve` are prime but it doesn't test if the list is
523 complete. It does not ensure that all the primes between `0` and `n` are found.
524
525 Here's a property that is more comprehensive:
526
527 ```rust
528 fn prop_prime_iff_in_the_sieve(n: usize) -> bool {
529 sieve(n) == (0..(n + 1)).filter(|&i| is_prime(i)).collect::<Vec<_>>()
530 }
531 ```
532
533 It tests that for each number between 0 and n, inclusive, the naive primality test
534 yields the same result as the sieve.
535
536 Now, if we run it:
537
538 ```rust
539 fn main() {
540 quickcheck(prop_all_prime as fn(usize) -> bool);
541 quickcheck(prop_prime_iff_in_the_sieve as fn(usize) -> bool);
542 }
543 ```
544
545 we see that it fails immediately for value n = 2.
546
547 ```text
548 [quickcheck] TEST FAILED. Arguments: (2)
549 ```
550
551 If we inspect `sieve()` once again, we see that we mistakenly mark `2` as
552 non-prime. Removing the line `marked[2] = true;` results in both properties
553 passing.
554
555 ## What's not in this port of QuickCheck?
556
557 I think I've captured the key features, but there are still things missing:
558
559 - Only functions with 8 or fewer parameters can be quickchecked. This
560 limitation can be lifted to some `N`, but requires an implementation for each
561 `n` of the `Testable` trait.
562 - Functions that fail because of a stack overflow are not caught by QuickCheck.
563 Therefore, such failures will not have a witness attached
564 to them. (I'd like to fix this, but I don't know how.)
565 - `Coarbitrary` does not exist in any form in this package. It's unlikely that
566 it ever will.
567 - `Arbitrary` is not implemented for closures. See
568 [issue #56](https://github.com/BurntSushi/quickcheck/issues/56)
569 for more details on why.