Skip to main content

debug_snapshots/
debug_snapshots.rs

1//! Debug Snapshot Testing Example
2//!
3//! This example shows how to use debug snapshots to test computation results
4//! and verify output format across different inputs.
5//!
6//! Run with: cargo run --example debug_snapshots --features protest/derive
7
8use protest::{Generator, config::GeneratorConfig, primitives::IntGenerator};
9use protest_insta::PropertySnapshots;
10use rand::SeedableRng;
11use rand::rngs::StdRng;
12
13#[derive(Debug, Clone)]
14#[allow(dead_code)]
15struct ComputationResult {
16    input: i32,
17    factorial: u64,
18    is_even: bool,
19    digits: Vec<u8>,
20}
21
22fn factorial(n: i32) -> u64 {
23    if n <= 1 { 1 } else { (1..=n as u64).product() }
24}
25
26fn get_digits(n: i32) -> Vec<u8> {
27    n.abs()
28        .to_string()
29        .chars()
30        .filter_map(|c| c.to_digit(10).map(|d| d as u8))
31        .collect()
32}
33
34fn compute(n: i32) -> ComputationResult {
35    // Limit factorial to prevent overflow
36    let n_clamped = n.clamp(0, 20);
37
38    ComputationResult {
39        input: n,
40        factorial: factorial(n_clamped),
41        is_even: n % 2 == 0,
42        digits: get_digits(n),
43    }
44}
45
46fn main() {
47    println!("=== Debug Snapshot Testing Example ===\n");
48
49    // Create a seeded RNG for reproducibility
50    let mut rng = StdRng::seed_from_u64(123);
51    let config = GeneratorConfig::default();
52
53    // Create generator for small integers
54    let generator = IntGenerator::new(1, 15);
55
56    // Create snapshot helper
57    let mut snapshots = PropertySnapshots::new("computations");
58
59    println!("Computing results for 8 generated inputs...\n");
60
61    // Generate and snapshot 8 computation results
62    for i in 0..8 {
63        let input = generator.generate(&mut rng, &config);
64        let result = compute(input);
65
66        println!("Computation {}: {:?}", i, result);
67
68        // Create a debug snapshot
69        snapshots.assert_debug_snapshot(&result);
70    }
71
72    println!("\n✅ Created 8 debug snapshots in snapshots/ directory");
73    println!("   Review them with: cargo insta review");
74}