json_snapshots/
json_snapshots.rs

1//! JSON Snapshot Testing Example
2//!
3//! This example demonstrates how to use property-based testing with JSON snapshots
4//! to test serialization of complex data structures.
5//!
6//! Run with: cargo run --example json_snapshots --features protest/derive
7
8use protest::{
9    Generator, config::GeneratorConfig, primitives::IntGenerator, primitives::VecGenerator,
10};
11use protest_insta::PropertySnapshots;
12use rand::SeedableRng;
13use rand::rngs::StdRng;
14use serde::Serialize;
15
16#[derive(Serialize, Debug)]
17struct UserProfile {
18    user_id: i32,
19    username: String,
20    scores: Vec<i32>,
21    total_score: i32,
22    is_premium: bool,
23}
24
25fn generate_username(id: i32) -> String {
26    format!("user_{}", id)
27}
28
29fn main() {
30    println!("=== JSON Snapshot Testing Example ===\n");
31
32    // Create a seeded RNG for reproducibility
33    let mut rng = StdRng::seed_from_u64(42);
34    let config = GeneratorConfig::default();
35
36    // Create generators
37    let id_generator = IntGenerator::new(1, 1000);
38    let score_generator = VecGenerator::new(IntGenerator::new(0, 100), 1, 10);
39
40    // Create snapshot helper
41    let mut snapshots = PropertySnapshots::new("user_profiles");
42
43    println!("Generating 5 user profiles and creating JSON snapshots...\n");
44
45    // Generate and snapshot 5 different user profiles
46    for i in 0..5 {
47        let user_id = id_generator.generate(&mut rng, &config);
48        let username = generate_username(user_id);
49        let scores = score_generator.generate(&mut rng, &config);
50        let total_score: i32 = scores.iter().sum();
51        let is_premium = total_score > 250;
52
53        let profile = UserProfile {
54            user_id,
55            username,
56            scores: scores.clone(),
57            total_score,
58            is_premium,
59        };
60
61        println!("Profile {}: {:?}", i, profile);
62
63        // Create a JSON snapshot - this will create files in snapshots/
64        snapshots.assert_json_snapshot(&profile);
65    }
66
67    println!("\n✅ Created 5 JSON snapshots in snapshots/ directory");
68    println!("   Review them with: cargo insta review");
69}