protest 1.0.0

An ergonomic, powerful, and feature-rich property testing library with minimal boilerplate.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
# โœŠ Protest   [![Build Status]][actions] [![Latest Version]][crates.io] [![Documentation]][docs.rs]

[Build Status]: https://img.shields.io/github/actions/workflow/status/shrynx/protest/ci.yml?branch=main
[actions]: https://github.com/shrynx/protest/actions?query=branch%3Amain
[Latest Version]: https://img.shields.io/crates/v/protest.svg
[crates.io]: https://crates.io/crates/protest
[Documentation]: https://docs.rs/protest/badge.svg
[docs.rs]: https://docs.rs/protest


**Property-Based Testing for Rust** - An ergonomic, powerful, and feature-rich property testing library with minimal boilerplate.

## Features

- ๐Ÿš€ **Ergonomic API** - Test properties with closures, no boilerplate
- ๐ŸŽฏ **Automatic Generator Inference** - Smart type-based generator selection
- ๐Ÿ”ง **Derive Macros** - `#[derive(Generator)]` for custom types
- ๐Ÿ“ฆ **Declarative Macros** - `property!`, `assert_property!`, `generator!`
- โšก **Async Support** - First-class async property testing
- ๐Ÿ”„ **Smart Shrinking** - Automatic minimal counterexample finding
- ๐Ÿ’พ **Failure Persistence** - Save and replay failing test cases (optional)
- ๐Ÿ”ง **CLI Tool** - Manage failures from the command line ([protest-cli]protest-cli/)
- ๐ŸŽจ **Fluent Builders** - Chain configuration methods naturally
- ๐Ÿงช **Common Patterns** - Built-in helpers for mathematical properties
- ๐Ÿ”€ **Parallel Execution** - Run tests in parallel for speed
- ๐Ÿ“Š **Statistics & Coverage** - Track generation and test coverage
- ๐ŸŽญ **Flexible** - Works with any type, sync or async

## Quick Start

Add Protest to your `Cargo.toml`:

```toml
[dev-dependencies]
protest = { version = "*", features = ["derive", "persistence"] }
```

**Optional Extensions:**
```toml
protest-extras = "*"           # Extra generators (network, datetime, text)
protest-stateful = "*"         # Stateful testing & model checking
protest-criterion = "*"        # Property-based benchmarking
protest-insta = "*"            # Snapshot testing integration
protest-proptest-compat = "*"  # Migration helpers from proptest
```

See individual package READMEs for detailed documentation:
- [protest-extras]protest-extras/ - Additional generators
- [protest-stateful]protest-stateful/ - Stateful testing
- [protest-criterion]protest-criterion/ - Benchmarking
- [protest-insta]protest-insta/ - Snapshot testing
- [protest-proptest-compat]protest-proptest-compat/ - Migration guide
- [protest-cli]protest-cli/ - Command-line tool

### Ultra-Simple Example

```rust
use protest::*;

#[test]
fn test_addition_commutative() {
    // Test that addition is commutative with just one line!
    property!(generator!(i32, -100, 100), |(a, b)| a + b == b + a);
}
```

### Ergonomic API Example

```rust
use protest::ergonomic::*;

#[test]
fn test_reverse_twice_is_identity() {
    property(|mut v: Vec<i32>| {
        let original = v.clone();
        v.reverse();
        v.reverse();
        v == original
    })
    .iterations(1000)
    .run_with(VecGenerator::new(IntGenerator::new(-50, 50), 0, 100))
    .expect("Property should hold");
}
```

### Attribute Macro Example

```rust
use protest::property_test;

#[property_test(iterations = 100)]
fn test_string_length(s: String) {
    // Generator automatically inferred from type
    assert!(s.len() >= 0);
}
```

### Custom Struct Example

```rust
use protest::Generator;

#[derive(Debug, Clone, PartialEq, Generator)]
struct User {
    #[generator(range = "1..1000")]
    id: u32,

    #[generator(length = "5..50")]
    name: String,

    age: u8,
    active: bool,
}

#[property_test]
fn test_user_id(user: User) {
    assert!(user.id > 0 && user.id < 1000);
}
```

## API Styles

Protest offers multiple API styles - use what fits your needs:

### 1. Declarative Macros (Most Concise)

```rust
use protest::*;

// Simple property test
property!(generator!(i32, 0, 100), |x| x >= 0);

// With configuration
property!(
    generator!(i32, 0, 100),
    iterations = 1000,
    seed = 42,
    |x| x >= 0
);

// Assert style (panics on failure)
assert_property!(
    generator!(i32, 0, 100),
    |x| x * 2 > x,
    "Doubling should increase positive numbers"
);
```

### 2. Fluent Builder API (Most Flexible)

```rust
use protest::ergonomic::*;

property(|x: i32| x.abs() >= 0)
    .iterations(1000)
    .seed(42)
    .max_shrink_iterations(500)
    .run_with(IntGenerator::new(-100, 100))
    .expect("Absolute value is always non-negative");
```

### 3. Attribute Macros (Most Integrated)

```rust
use protest::property_test;

#[property_test(iterations = 100, seed = 42)]
fn test_vec_operations(v: Vec<i32>) {
    let mut sorted = v.clone();
    sorted.sort();
    assert!(sorted.windows(2).all(|w| w[0] <= w[1]));
}
```

### 4. Direct API (Most Control)

```rust
use protest::*;

struct MyProperty;
impl Property<i32> for MyProperty {
    type Output = ();
    fn test(&self, input: i32) -> Result<(), PropertyError> {
        if input >= 0 {
            Ok(())
        } else {
            Err(PropertyError::property_failed("negative number"))
        }
    }
}

let result = check(IntGenerator::new(0, 100), MyProperty);
assert!(result.is_ok());
```

## Common Property Patterns

Protest includes built-in helpers for common mathematical properties:

```rust
use protest::ergonomic::patterns::*;

// Commutativity: f(a, b) == f(b, a)
commutative(|a: i32, b: i32| a + b);

// Associativity: f(f(a, b), c) == f(a, f(b, c))
associative(|a: i32, b: i32| a + b);

// Idempotence: f(f(x)) == f(x)
idempotent(|x: i32| x.abs());

// Round-trip: decode(encode(x)) == x
round_trip(
    |x: i32| x.to_string(),
    |s: String| s.parse().unwrap()
);

// Inverse functions: f(g(x)) == x && g(f(x)) == x
inverse(|x: i32| x * 2, |x: i32| x / 2);

// Identity element: f(x, e) == x
has_identity(|a: i32, b: i32| a + b, 0);

// Monotonicity
monotonic_increasing(|x: i32| x * x);

// Distributivity
distributive(
    |a: i32, b: i32| a * b,
    |a: i32, b: i32| a + b
);
```

## Async Support

Full support for runtime-agnostic async property testing. Works with any async runtime (tokio, async-std, smol):

```rust
use protest::*;

struct AsyncFetchProperty;

impl AsyncProperty<u32> for AsyncFetchProperty {
    type Output = ();

    async fn test(&self, id: u32) -> Result<(), PropertyError> {
        let user = fetch_user(id).await;
        if id > 0 && user.is_none() {
            Err(PropertyError::property_failed("User not found"))
        } else {
            Ok(())
        }
    }
}

#[tokio::test]
async fn test_async_property() {
    let result = check_async(
        IntGenerator::new(1, 100),
        AsyncFetchProperty
    ).await;

    assert!(result.is_ok());
}
```

**Note:** Protest is runtime-agnostic - you bring your own async runtime. Add tokio, async-std, or smol to your dev-dependencies as needed.

## Automatic Generator Inference

Protest automatically infers generators for common types:

```rust
use protest::ergonomic::AutoGen;

// All primitive types
i32::auto_generator();
String::auto_generator();
bool::auto_generator();

// Collections
Vec::<i32>::auto_generator();
HashMap::<String, i32>::auto_generator();

// Tuples
<(i32, String)>::auto_generator();

// Options
Option::<i32>::auto_generator();

// Your custom types with #[derive(Generator)]
User::auto_generator();
```

## Shrinking

When a property fails, Protest automatically finds the minimal counterexample:

```rust
property!(generator!(i32, 1, 100), |x| x < 50);
// Fails with: Property failed with input 50 (shrunk from larger value)
//           Focus on input: 50
```

## Configuration

Extensive configuration options:

```rust
use protest::*;
use std::time::Duration;

let config = TestConfig {
    iterations: 1000,                            // Number of test cases
    seed: Some(42),                               // For reproducibility
    max_shrink_iterations: 500,                  // Shrinking limit
    shrink_timeout: Duration::from_secs(10),     // Shrinking timeout
    generator_config: GeneratorConfig {
        size_hint: 100,                          // Size for collections
        max_depth: 5,                            // For nested structures
        ..GeneratorConfig::default()
    },
    ..TestConfig::default()
};
```

## Failure Persistence & Replay

Save failing test cases and automatically replay them (requires `persistence` feature):

```rust
use protest::*;

PropertyTestBuilder::new()
    .test_name("my_critical_test")
    .persist_failures()  // Enable automatic failure saving & replay
    .iterations(10000)
    .run(u32::arbitrary(), |x: u32| {
        // Your property test
        if x > 1000 {
            Err("Value too large")
        } else {
            Ok(())
        }
    });
```

**What happens:**
1. Failed tests are automatically saved to `.protest/failures/`
2. On subsequent runs, failures are replayed before running new cases
3. Fixed failures are automatically cleaned up

Install the CLI tool for advanced failure management:
```bash
cargo install protest-cli
```

See the [CLI documentation](protest-cli/README.md) for complete details on managing failures, generating regression tests, and corpus building.

## Stateful Property Testing

Test state machines, databases, and concurrent systems with **protest-stateful**:

```rust
use protest_stateful::{Operation, prelude::*};

#[derive(Debug, Clone, Operation)]
#[operation(state = "Vec<i32>")]
enum StackOp {
    #[execute("state.push(*field_0)")]
    #[weight(5)]
    Push(i32),

    #[execute("state.pop()")]
    #[precondition("!state.is_empty()")]
    Pop,
}
```

**Features:**
- State machine testing with derive macros
- Model-based testing (compare against reference implementation)
- Temporal properties (Always, Eventually)
- Linearizability verification for concurrent systems

See [protest-stateful README](protest-stateful/README.md) for complete documentation.

## Examples

The repository includes comprehensive examples:

- [`basic_usage.rs`]examples/basic_usage.rs - Getting started
- [`ergonomic_api_demo.rs`]examples/ergonomic_api_demo.rs - All ergonomic features
- [`custom_structs.rs`]examples/custom_structs.rs - Custom types with derive
- [`async_properties.rs`]examples/async_properties.rs - Async testing
- [`advanced_patterns.rs`]examples/advanced_patterns.rs - Advanced techniques

Run examples:
```bash
cargo run --example ergonomic_api_demo
cargo run --example custom_structs
cargo run --example async_properties
```

## Property-Based Benchmarking

Benchmark with diverse generated inputs using **protest-criterion**:

```rust
use criterion::Criterion;
use protest_criterion::PropertyBencher;

fn bench_sort(c: &mut Criterion) {
    c.bench_property("vec sort", vec_generator, |v: &Vec<i32>| {
        let mut sorted = v.clone();
        sorted.sort();
    }, 100);
}
```

See [protest-criterion README](protest-criterion/README.md) for details.

## Property-Based Snapshot Testing

Visual regression testing with **protest-insta**:

```rust
use protest_insta::PropertySnapshots;

#[test]
fn test_report_snapshots() {
    let mut snapshots = PropertySnapshots::new("reports");

    for report in generate_reports() {
        snapshots.assert_json_snapshot(&report);
    }
}
```

See [protest-insta README](protest-insta/README.md) for details.


## Migrating from Proptest

Use **protest-proptest-compat** for migration helpers:

### Before (Proptest)
```rust
proptest! {
    #[test]
    fn test_addition(a in 0..100i32, b in 0..100i32) {
        assert!(a + b >= a && a + b >= b);
    }
}
```

### After (Protest)
```rust
#[test]
fn test_addition() {
    property!(generator!(i32, 0, 100), |(a, b)| {
        a + b >= a && a + b >= b
    });
}
```

See [protest-proptest-compat README](protest-proptest-compat/README.md) for the complete migration guide.

## Feature Flags

```toml
[features]
default = ["derive"]
derive = ["protest-derive"]    # Derive macros for Generator trait
persistence = ["serde", "serde_json"]  # Failure persistence & replay
```

Protest has minimal dependencies and no required runtime dependencies. Async support is built-in and runtime-agnostic. The `persistence` feature is optional and adds `serde` for JSON serialization of test failures.

## Comparison with Other Libraries

| Feature | Protest | proptest | quickcheck |
|---------|---------|----------|------------|
| Ergonomic API | โœ… | โŒ | โŒ |
| Automatic Inference | โœ… | โŒ | Partial |
| Derive Macros | โœ… | โœ… | โœ… |
| Async Support | โœ… | โŒ | โŒ |
| Declarative Macros | โœ… | โŒ | โŒ |
| Fluent Builders | โœ… | Partial | โŒ |
| Pattern Helpers | โœ… | โŒ | โŒ |
| Shrinking | โœ… | โœ… | โœ… |
| Statistics | โœ… | Partial | โŒ |
| Failure Persistence | โœ… | Partial | โŒ |
| Test Corpus | โœ… | โŒ | โŒ |

## Documentation

Full documentation is available on [docs.rs](https://docs.rs/protest).

### Key Modules

- `protest::ergonomic` - Ergonomic API (closures, builders, patterns)
- `protest::primitives` - Built-in generators (int, string, vec, hashmap, etc.)
- `protest::generator` - Generator trait and utilities
- `protest::property` - Property trait and execution
- `protest::shrink` - Shrinking infrastructure
- `protest::persistence` - Failure persistence and replay (optional)
- `protest::config` - Configuration types
- `protest::statistics` - Coverage and statistics

### Protest Extras

The [`protest-extras`](protest-extras/) crate provides 23 additional specialized generators and enhanced shrinking strategies:

See the [protest-extras README](protest-extras/README.md) for detailed examples and documentation.


## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Acknowledgments

Inspired by:
- [proptest]https://github.com/proptest-rs/proptest - Rust property testing
- [QuickCheck]https://github.com/BurntSushi/quickcheck - Original Rust QuickCheck
- [Hypothesis]https://hypothesis.works/ - Python property testing

---

Made with โค๏ธ for the Rust community