### Rust Main Function Invoking QuickCheck Source: https://github.com/burntsushi/quickcheck/blob/master/README.md The main function to run QuickCheck tests. This example shows how to invoke quickcheck with a specific property. ```rust fn main() { quickcheck(prop_all_prime as fn(usize) -> bool); } ``` -------------------------------- ### Define a Point struct Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A simple struct definition to be used for random generation examples. ```rust struct Point { x: i32, y: i32, } ``` -------------------------------- ### Define a faulty reverse function Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A contrived example of a function that reverses a slice incorrectly, used to demonstrate shrinking. ```rust fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for i in 1..xs.len() { rev.insert(0, xs[i].clone()) } rev } ``` -------------------------------- ### Discard test inputs using TestResult Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Example of a property function that discards inputs not meeting specific criteria. ```rust fn prop(xs: Vec) -> TestResult { if xs.len() != 1 { return TestResult::discard() } TestResult::from_bool(xs == reverse(&xs)) } quickcheck(prop as fn(Vec) -> TestResult); ``` -------------------------------- ### Shrinking for Minimal Counter-Examples Source: https://context7.com/burntsushi/quickcheck/llms.txt Demonstrates how QuickCheck identifies bugs by shrinking failing inputs to the smallest possible counter-example. ```rust use quickcheck::quickcheck; // Buggy sieve implementation (intentionally incorrect) fn sieve(n: usize) -> Vec { if n <= 1 { return vec![]; } let mut marked = vec![false; n + 1]; marked[0] = true; marked[1] = true; marked[2] = true; // Bug: incorrectly marks 2 as non-prime for p in 2..n { for i in (2 * p..n).filter(|&n| n % p == 0) { // Bug: should be ..=n marked[i] = true; } } marked.iter().enumerate() .filter_map(|(i, &m)| if m { None } else { Some(i) }) .collect() } fn is_prime(n: usize) -> bool { n != 0 && n != 1 && (2..).take_while(|i| i * i <= n).all(|i| n % i != 0) } fn main() { // This property will fail and shrink to find minimal counter-example fn prop_all_prime(n: usize) -> bool { sieve(n).into_iter().all(is_prime) } // Without shrinking: might fail with Arguments: ([-17, 13, -12, 17, ...]) // With shrinking: fails with Arguments: (4) - much easier to debug! // Uncomment to see the failure: // quickcheck(prop_all_prime as fn(usize) -> bool); // Output: [quickcheck] TEST FAILED. Arguments: (4) } ``` -------------------------------- ### Simple QuickCheck Test with `quickcheck!` Macro Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Demonstrates a basic property-based test using the `quickcheck!` macro. This macro is compatible with older Rust versions. It requires importing `quickcheck` and the function to be tested. ```rust fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs.iter() { rev.insert(0, x.clone()) } rev } #[cfg(test)] mod tests { use quickcheck::quickcheck; use super::reverse; quickcheck! { fn prop(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } } } ``` -------------------------------- ### Configuring QuickCheck via Environment Variables Source: https://context7.com/burntsushi/quickcheck/llms.txt Configures test execution parameters like iteration counts and logging without modifying source code. ```rust use quickcheck::quickcheck; // Environment variables: // QUICKCHECK_TESTS=1000 - Number of tests to run (default: 100) // QUICKCHECK_MAX_TESTS=50000 - Max attempts including discards (default: 10000) // QUICKCHECK_MIN_TESTS_PASSED=500 - Minimum valid tests required (default: 0) // QUICKCHECK_GENERATOR_SIZE=200 - Size parameter for Gen (default: 100) // RUST_LOG=quickcheck - Enable info logging for test progress fn prop_addition_commutative(a: i64, b: i64) -> bool { a.wrapping_add(b) == b.wrapping_add(a) } fn main() { // Run with: QUICKCHECK_TESTS=10000 RUST_LOG=quickcheck cargo run quickcheck(prop_addition_commutative as fn(i64, i64) -> bool); } ``` -------------------------------- ### Adding QuickCheck and Macros as Development Dependencies Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Configuration for adding both `quickcheck` and `quickcheck_macros` as development dependencies in a Rust project's `Cargo.toml` file. ```toml [dev-dependencies] quickcheck = "1" quickcheck_macros = "1" ``` -------------------------------- ### Rust Main Function Invoking Multiple QuickCheck Properties Source: https://github.com/burntsushi/quickcheck/blob/master/README.md This main function demonstrates how to run multiple QuickCheck properties sequentially. It ensures both the primality of returned numbers and the completeness of the sieve are tested. ```rust fn main() { quickcheck(prop_all_prime as fn(usize) -> bool); quickcheck(prop_prime_iff_in_the_sieve as fn(usize) -> bool); } ``` -------------------------------- ### Adding QuickCheck as a Regular Dependency Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Configuration for adding the `quickcheck` crate as a regular dependency in a Rust project's `Cargo.toml` file. ```toml [dependencies] quickcheck = "1" ``` -------------------------------- ### Define properties with quickcheck! macro Source: https://context7.com/burntsushi/quickcheck/llms.txt Generates standard Rust test functions from property definitions within a module. Requires the quickcheck_macros crate. ```rust #[macro_use] extern crate quickcheck; fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs.iter() { rev.insert(0, x.clone()) } rev } #[cfg(test)] mod tests { use super::reverse; quickcheck! { fn prop_reverse_reverse(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } fn prop_reverse_length(xs: Vec) -> bool { xs.len() == reverse(&xs).len() } } } // Run with: cargo test // Output: test tests::prop_reverse_reverse ... ok // Output: test tests::prop_reverse_length ... ok ``` -------------------------------- ### Adding QuickCheck as a Development Dependency Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Configuration for adding the `quickcheck` crate as a development dependency in a Rust project's `Cargo.toml` file. ```toml [dev-dependencies] quickcheck = "1" ``` -------------------------------- ### Run property tests with quickcheck function Source: https://context7.com/burntsushi/quickcheck/llms.txt Executes a property test against randomly generated inputs. Panics with a minimal counter-example if the property fails. ```rust use quickcheck::quickcheck; fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs { rev.insert(0, x.clone()); } rev } fn main() { // Property: reversing a vector twice yields the original fn prop_double_reverse(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } // Run the property test with 100 random inputs quickcheck(prop_double_reverse as fn(Vec) -> bool); // Output: (Passed 100 QuickCheck tests.) } ``` -------------------------------- ### Run tests in a loop with Bash Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A bash script to repeatedly execute tests prefixed with 'qc_' until a failure occurs. ```bash #!/usr/bin/bash while true do cargo test qc_ if [[ x$? != x0 ]] ; then exit $? fi done ``` -------------------------------- ### Configure tests with QuickCheck builder Source: https://context7.com/burntsushi/quickcheck/llms.txt Customizes test execution parameters such as test count, attempt limits, and random number generator settings. ```rust use quickcheck::{QuickCheck, Gen}; fn prop_sorted_len(mut xs: Vec) -> bool { let original_len = xs.len(); xs.sort(); xs.len() == original_len } fn main() { // Configure and run with custom settings QuickCheck::new() .tests(1000) // Run 1000 tests instead of default 100 .max_tests(50000) // Allow up to 50000 attempts (for discarded tests) .min_tests_passed(500) // Require at least 500 valid tests to pass .rng(Gen::new(200)) // Use generator with size 200 .quickcheck(prop_sorted_len as fn(Vec) -> bool); } ``` -------------------------------- ### QuickCheck Test with `#[quickcheck]` Attribute Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Shows how to use the `#[quickcheck]` attribute to convert a property function into a `#[test]` function. This requires importing the `quickcheck` macro from the `quickcheck_macros` crate. ```rust fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs { rev.insert(0, x.clone()) } rev } #[cfg(test)] mod tests { use quickcheck_macros::quickcheck; use super::reverse; #[quickcheck] fn double_reversal_is_identity(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } } ``` -------------------------------- ### Use #[quickcheck] attribute for property tests Source: https://context7.com/burntsushi/quickcheck/llms.txt Converts a function into a property test using a procedural macro attribute. Offers cleaner syntax and better IDE integration. ```rust use quickcheck_macros::quickcheck; fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs { rev.insert(0, x.clone()) } rev } #[cfg(test)] mod tests { use super::reverse; use quickcheck_macros::quickcheck; #[quickcheck] fn double_reversal_is_identity(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } #[quickcheck] fn reverse_preserves_length(xs: Vec) -> bool { xs.len() == reverse(&xs).len() } } // Run with: cargo test ``` -------------------------------- ### Testing Multi-Parameter Properties Source: https://context7.com/burntsushi/quickcheck/llms.txt Supports functions with up to 8 parameters, where each parameter is independently generated and shrunk. ```rust use quickcheck::quickcheck; fn main() { // Two-parameter property fn prop_addition_commutative(a: i32, b: i32) -> bool { a.wrapping_add(b) == b.wrapping_add(a) } quickcheck(prop_addition_commutative as fn(i32, i32) -> bool); // Three-parameter property fn prop_addition_associative(a: i32, b: i32, c: i32) -> bool { a.wrapping_add(b.wrapping_add(c)) == a.wrapping_add(b).wrapping_add(c) } quickcheck(prop_addition_associative as fn(i32, i32, i32) -> bool); // Four-parameter property with different types fn prop_concat_lengths(a: String, b: String, c: Vec, d: Vec) -> bool { let str_len = a.len() + b.len(); let vec_len = c.len() + d.len(); format!("{}{}", a, b).len() == str_len && [c, d].concat().len() == vec_len } quickcheck(prop_concat_lengths as fn(String, String, Vec, Vec) -> bool); } ``` -------------------------------- ### Define the quickcheck function signature Source: https://github.com/burntsushi/quickcheck/blob/master/README.md The core function signature for running property tests in quickcheck. ```rust pub fn quickcheck(f: A) { // elided } ``` -------------------------------- ### Rust QuickCheck Property: Sieve Completeness Check Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A more comprehensive QuickCheck property that verifies if the sieve returns all primes up to n and only primes. It compares the sieve's output with a direct primality test for all numbers in the range. ```rust fn prop_prime_iff_in_the_sieve(n: usize) -> bool { sieve(n) == (0..(n + 1)).filter(|&i| is_prime(i)).collect::>() } ``` -------------------------------- ### Implement Testable for functions Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Implementation allowing functions with a single parameter to be tested. ```rust impl Testable for fn(A) -> B { fn result(&self, g: &mut Gen) -> TestResult { // elided } } ``` -------------------------------- ### Implement Testable for bool Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Standard implementation allowing boolean functions to be tested. ```rust impl Testable for bool { fn result(&self, _: &mut Gen) -> TestResult { TestResult::from_bool(*self) } } ``` -------------------------------- ### Implement Arbitrary Trait for Custom Types Source: https://context7.com/burntsushi/quickcheck/llms.txt Define how to generate and shrink custom types by implementing the Arbitrary trait, enabling them to be used in property tests. ```rust use quickcheck::{Arbitrary, Gen, quickcheck}; #[derive(Clone, Debug, PartialEq)] struct Point { x: i32, y: i32, } impl Arbitrary for Point { fn arbitrary(g: &mut Gen) -> Point { Point { x: i32::arbitrary(g), y: i32::arbitrary(g), } } fn shrink(&self) -> Box> { // Shrink by trying smaller x and y values let x = self.x; let y = self.y; Box::new( x.shrink().map(move |x| Point { x, y }) .chain(y.shrink().map(move |y| Point { x, y })) ) } } fn distance_from_origin(p: &Point) -> f64 { ((p.x as f64).powi(2) + (p.y as f64).powi(2)).sqrt() } fn main() { fn prop_distance_non_negative(p: Point) -> bool { distance_from_origin(&p) >= 0.0 } quickcheck(prop_distance_non_negative as fn(Point) -> bool); } ``` -------------------------------- ### Rust QuickCheck Property: All Numbers Returned are Prime Source: https://github.com/burntsushi/quickcheck/blob/master/README.md This QuickCheck property tests if all numbers returned by the sieve function are indeed prime. It requires the `is_prime` helper function. ```rust fn prop_all_prime(n: usize) -> bool { sieve(n).into_iter().all(is_prime) } ``` -------------------------------- ### Define a property for testing Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A property function that checks if double-reversing a vector returns the original vector. ```rust fn prop(xs: Vec) -> bool { xs == reverse(&reverse(&xs)) } quickcheck(prop as fn(Vec) -> bool); ``` -------------------------------- ### Rust Sieve of Eratosthenes Implementation Source: https://github.com/burntsushi/quickcheck/blob/master/README.md This function implements the Sieve of Eratosthenes to find prime numbers up to n. It initializes a boolean array and marks multiples of each prime as non-prime. ```rust fn sieve(n: usize) -> Vec { if n <= 1 { return vec![]; } let mut marked = vec![false; n+1]; marked[0] = true; marked[1] = true; marked[2] = true; for p in 2..n { for i in (2*p..n).filter(|&n| n % p == 0) { marked[i] = true; } } marked.iter() .enumerate() .filter_map(|(i, &m)| if m { None } else { Some(i) }) .collect() } ``` -------------------------------- ### Generate Random Values with Gen Source: https://context7.com/burntsushi/quickcheck/llms.txt Use the Gen struct to generate random values or select from collections, with support for custom sizes and seeds for reproducibility. ```rust use quickcheck::{Gen, Arbitrary}; fn main() { // Create a generator with size 100 let mut g = Gen::new(100); // Generate arbitrary values of various types let random_int: i32 = i32::arbitrary(&mut g); let random_vec: Vec = Vec::::arbitrary(&mut g); let random_string: String = String::arbitrary(&mut g); println!("Random i32: {}", random_int); println!("Random Vec: {:?}", random_vec); println!("Random String: {:?}", random_string); // Create a generator with a specific seed for reproducibility let mut seeded_g = Gen::from_size_and_seed(50, 12345); let reproducible: Vec = Vec::::arbitrary(&mut seeded_g); println!("Reproducible Vec: {:?}", reproducible); // Use choose to select from a slice let mut g2 = Gen::new(10); let options = ["red", "green", "blue"]; if let Some(color) = g2.choose(&options) { println!("Chosen color: {}", color); } } ``` -------------------------------- ### Define the Testable trait Source: https://github.com/burntsushi/quickcheck/blob/master/README.md The trait that types must implement to be used as properties in quickcheck. ```rust pub trait Testable { fn result(&self, &mut Gen) -> TestResult; } ``` -------------------------------- ### Implement Testable for TestResult Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Implementation allowing TestResult to be returned directly from property functions. ```rust impl Testable for TestResult { fn result(&self, _: &mut Gen) -> TestResult { self.clone() } } ``` -------------------------------- ### Implement Arbitrary for a struct Source: https://github.com/burntsushi/quickcheck/blob/master/README.md Implementation of the Arbitrary trait to enable random generation of Point instances. ```rust use quickcheck::{Arbitrary, Gen}; impl Arbitrary for Point { fn arbitrary(g: &mut Gen) -> Point { Point { x: i32::arbitrary(g), y: i32::arbitrary(g), } } } ``` -------------------------------- ### Rust Primality Test Helper Function Source: https://github.com/burntsushi/quickcheck/blob/master/README.md A helper function to determine if a given number is prime. It checks for divisibility by numbers up to the square root of n. ```rust fn is_prime(n: usize) -> bool { n != 0 && n != 1 && (2..).take_while(|i| i*i <= n).all(|i| n % i != 0) } ``` -------------------------------- ### Disable Shrinking with NoShrink Source: https://context7.com/burntsushi/quickcheck/llms.txt Wrap types in NoShrink to prevent the library from attempting to shrink values during test failures. ```rust use quickcheck::{quickcheck, Arbitrary, NoShrink, QuickCheck}; fn main() { // Property using NoShrink to prevent shrinking of the input fn prop_no_shrink_value(value: NoShrink) -> bool { // Access the inner value let inner = value.inner(); // Verify the shrinker doesn't yield the original value (would cause infinite loop) !inner.shrink().any(|v| v == *inner) } QuickCheck::new().quickcheck(prop_no_shrink_value as fn(NoShrink) -> bool); // Use into_inner() to consume and get ownership of the inner value fn prop_consume_noshrink(value: NoShrink) -> bool { let s: String = value.into_inner(); s.len() == s.chars().count() || s.chars().any(|c| c.len_utf8() > 1) } quickcheck(prop_consume_noshrink as fn(NoShrink) -> bool); } ``` -------------------------------- ### Control Test Outcomes with TestResult Source: https://context7.com/burntsushi/quickcheck/llms.txt Use TestResult to discard invalid test inputs or explicitly define pass/fail conditions, including expected panics. ```rust use quickcheck::{quickcheck, TestResult}; fn reverse(xs: &[T]) -> Vec { let mut rev = vec![]; for x in xs { rev.insert(0, x.clone()); } rev } fn main() { // Property: single-element vectors are unchanged by reverse fn prop_single_element_unchanged(xs: Vec) -> TestResult { if xs.len() != 1 { // Discard test inputs that don't have exactly one element return TestResult::discard(); } TestResult::from_bool(xs == reverse(&xs)) } quickcheck(prop_single_element_unchanged as fn(Vec) -> TestResult); // Property that must cause a panic fn prop_division_by_zero_panics(x: i32) -> TestResult { if x == 0 { return TestResult::discard(); } // Test passes if the closure panics TestResult::must_fail(move || { let _ = 1 / (x - x); // This will panic with division by zero }) } quickcheck(prop_division_by_zero_panics as fn(i32) -> TestResult); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.