protest 1.1.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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Test runner integration and compatibility utilities
//!
//! This module provides utilities for integrating Protest with various Rust test runners
//! and frameworks, including custom output formatting and test result reporting.

use crate::{PropertyResult, TestFailure, TestSuccess};
use std::fmt;
use std::time::Duration;

/// Test runner integration utilities
pub struct TestRunner;

impl TestRunner {
    /// Format a property test result for standard test output
    pub fn format_result<T>(result: &PropertyResult<T>) -> String
    where
        T: fmt::Debug,
    {
        match result {
            Ok(success) => Self::format_success(success),
            Err(failure) => Self::format_failure(failure),
        }
    }

    /// Format a successful test result
    pub fn format_success<T>(success: &TestSuccess<T>) -> String {
        let mut output = String::new();

        output.push_str(&format!(
            "Property test PASSED after {} iterations",
            success.iterations
        ));

        if let Some(seed) = success.config.seed {
            output.push_str(&format!(" (seed: {})", seed));
        }

        // Note: TestSuccess doesn't have test_duration field
        // This would need to be tracked separately if needed

        if let Some(stats) = &success.stats {
            output.push_str(&format!("\nGenerated {} values", stats.total_generated));
            output.push_str(&format!(
                ", avg generation time: {:?}",
                stats.performance_metrics.average_generation_time
            ));
        }

        output
    }

    /// Format a failed test result
    pub fn format_failure<T>(failure: &TestFailure<T>) -> String
    where
        T: fmt::Debug,
    {
        let mut output = String::new();

        output.push_str(&format!("Property test FAILED: {}", failure.error));
        output.push_str(&format!(
            "\nOriginal failing input: {:?}",
            failure.original_input
        ));

        if let Some(shrunk) = &failure.shrunk_input {
            output.push_str(&format!("\nMinimal failing input: {:?}", shrunk));
            output.push_str(&format!(
                " (found after {} shrinking steps)",
                failure.shrink_steps
            ));
        }

        if let Some(seed) = failure.config.seed {
            output.push_str(&format!(
                "\nSeed: {} (use this to reproduce the failure)",
                seed
            ));
        }

        output.push_str(&format!("\nTest duration: {:?}", failure.test_duration));

        if failure.shrink_duration > Duration::from_millis(0) {
            output.push_str(&format!(
                ", shrinking duration: {:?}",
                failure.shrink_duration
            ));
        }

        output
    }

    /// Create a panic message for property test failures
    pub fn create_panic_message<T>(failure: &TestFailure<T>) -> String
    where
        T: fmt::Debug,
    {
        format!("Property test failed: {}", Self::format_failure(failure))
    }

    /// Check if we're running under cargo test
    pub fn is_cargo_test() -> bool {
        std::env::var("CARGO").is_ok() || std::env::var("CARGO_PKG_NAME").is_ok()
    }

    /// Check if we're running with verbose output
    pub fn is_verbose_output() -> bool {
        std::env::args().any(|arg| arg == "--nocapture" || arg == "-v" || arg == "--verbose")
    }

    /// Print test progress if verbose output is enabled
    pub fn print_progress(message: &str) {
        if Self::is_verbose_output() {
            println!("protest: {}", message);
        }
    }

    /// Print test statistics if verbose output is enabled
    pub fn print_statistics<T>(success: &TestSuccess<T>) {
        if Self::is_verbose_output()
            && let Some(stats) = &success.stats
        {
            println!("protest: Test statistics:");
            println!(
                "protest:   Total values generated: {}",
                stats.total_generated
            );
            println!(
                "protest:   Generation time: {:?}",
                stats.performance_metrics.total_generation_time
            );
            println!(
                "protest:   Average per value: {:?}",
                stats.performance_metrics.average_generation_time
            );

            if stats.performance_metrics.memory_stats.peak_memory_usage > 0 {
                println!(
                    "protest:   Peak memory usage: {} KB",
                    stats.performance_metrics.memory_stats.peak_memory_usage / 1024
                );
            }
        }
    }
}

/// Custom test result type for better integration with test frameworks
#[derive(Debug)]
pub enum TestResult {
    /// Test passed
    Passed {
        iterations: usize,
        duration: Duration,
        seed: Option<u64>,
    },
    /// Test failed
    Failed {
        error: String,
        original_input: String,
        shrunk_input: Option<String>,
        shrink_steps: usize,
        seed: Option<u64>,
        duration: Duration,
    },
    /// Test was skipped
    Skipped { reason: String },
}

impl TestResult {
    /// Create a TestResult from a PropertyResult
    pub fn from_property_result<T>(result: PropertyResult<T>) -> Self
    where
        T: fmt::Debug,
    {
        match result {
            Ok(success) => TestResult::Passed {
                iterations: success.iterations,
                duration: Duration::from_nanos(0), // TestSuccess doesn't track duration
                seed: success.config.seed,
            },
            Err(failure) => TestResult::Failed {
                error: failure.error.to_string(),
                original_input: format!("{:?}", failure.original_input),
                shrunk_input: failure.shrunk_input.as_ref().map(|s| format!("{:?}", s)),
                shrink_steps: failure.shrink_steps,
                seed: failure.config.seed,
                duration: failure.test_duration,
            },
        }
    }

    /// Check if the test passed
    pub fn is_passed(&self) -> bool {
        matches!(self, TestResult::Passed { .. })
    }

    /// Check if the test failed
    pub fn is_failed(&self) -> bool {
        matches!(self, TestResult::Failed { .. })
    }

    /// Check if the test was skipped
    pub fn is_skipped(&self) -> bool {
        matches!(self, TestResult::Skipped { .. })
    }

    /// Get the test duration if available
    pub fn duration(&self) -> Option<Duration> {
        match self {
            TestResult::Passed { duration, .. } => Some(*duration),
            TestResult::Failed { duration, .. } => Some(*duration),
            TestResult::Skipped { .. } => None,
        }
    }

    /// Get the seed used for the test if available
    pub fn seed(&self) -> Option<u64> {
        match self {
            TestResult::Passed { seed, .. } => *seed,
            TestResult::Failed { seed, .. } => *seed,
            TestResult::Skipped { .. } => None,
        }
    }
}

impl fmt::Display for TestResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TestResult::Passed {
                iterations,
                duration,
                seed,
            } => {
                write!(f, "PASSED ({} iterations in {:?}", iterations, duration)?;
                if let Some(seed) = seed {
                    write!(f, ", seed: {}", seed)?;
                }
                write!(f, ")")
            }
            TestResult::Failed {
                error,
                original_input,
                shrunk_input,
                shrink_steps,
                seed,
                duration,
            } => {
                write!(f, "FAILED: {}", error)?;
                write!(f, "\n  Original input: {}", original_input)?;
                if let Some(shrunk) = shrunk_input {
                    write!(
                        f,
                        "\n  Minimal input: {} (after {} steps)",
                        shrunk, shrink_steps
                    )?;
                }
                if let Some(seed) = seed {
                    write!(f, "\n  Seed: {}", seed)?;
                }
                write!(f, "\n  Duration: {:?}", duration)
            }
            TestResult::Skipped { reason } => {
                write!(f, "SKIPPED: {}", reason)
            }
        }
    }
}

/// Trait for custom test output formatting
pub trait TestOutputFormatter {
    /// Format the start of a test
    fn format_test_start(&self, test_name: &str) -> String;

    /// Format a successful test result
    fn format_test_success(&self, test_name: &str, result: &TestResult) -> String;

    /// Format a failed test result
    fn format_test_failure(&self, test_name: &str, result: &TestResult) -> String;

    /// Format a skipped test result
    fn format_test_skipped(&self, test_name: &str, result: &TestResult) -> String;
}

/// Default test output formatter compatible with cargo test
pub struct DefaultFormatter;

impl TestOutputFormatter for DefaultFormatter {
    fn format_test_start(&self, test_name: &str) -> String {
        format!("test {} ... ", test_name)
    }

    fn format_test_success(&self, _test_name: &str, result: &TestResult) -> String {
        match result {
            TestResult::Passed {
                iterations,
                duration,
                ..
            } => {
                format!("ok ({} iterations, {:?})", iterations, duration)
            }
            _ => "ok".to_string(),
        }
    }

    fn format_test_failure(&self, _test_name: &str, result: &TestResult) -> String {
        match result {
            TestResult::Failed { .. } => "FAILED".to_string(),
            _ => "FAILED".to_string(),
        }
    }

    fn format_test_skipped(&self, _test_name: &str, _result: &TestResult) -> String {
        "ignored".to_string()
    }
}

/// Verbose test output formatter with detailed information
pub struct VerboseFormatter;

impl TestOutputFormatter for VerboseFormatter {
    fn format_test_start(&self, test_name: &str) -> String {
        format!("Running property test: {}", test_name)
    }

    fn format_test_success(&self, test_name: &str, result: &TestResult) -> String {
        format!("{} {}", test_name, result)
    }

    fn format_test_failure(&self, test_name: &str, result: &TestResult) -> String {
        format!("{} {}", test_name, result)
    }

    fn format_test_skipped(&self, test_name: &str, result: &TestResult) -> String {
        format!("- {} {}", test_name, result)
    }
}

/// JSON test output formatter for machine-readable results
pub struct JsonFormatter;

impl TestOutputFormatter for JsonFormatter {
    fn format_test_start(&self, test_name: &str) -> String {
        format!(
            r#"{{"event":"started","name":"{}","type":"property_test"}}"#,
            test_name
        )
    }

    fn format_test_success(&self, test_name: &str, result: &TestResult) -> String {
        match result {
            TestResult::Passed {
                iterations,
                duration,
                seed,
            } => {
                let seed_json = seed
                    .map(|s| format!(r#","seed":{}"#, s))
                    .unwrap_or_default();
                format!(
                    r#"{{"event":"ok","name":"{}","type":"property_test","iterations":{},"duration_ms":{}{}}}"#,
                    test_name,
                    iterations,
                    duration.as_millis(),
                    seed_json
                )
            }
            _ => format!(
                r#"{{"event":"ok","name":"{}","type":"property_test"}}"#,
                test_name
            ),
        }
    }

    fn format_test_failure(&self, test_name: &str, result: &TestResult) -> String {
        match result {
            TestResult::Failed {
                error,
                original_input,
                shrunk_input,
                shrink_steps,
                seed,
                duration,
            } => {
                let seed_json = seed
                    .map(|s| format!(r#","seed":{}"#, s))
                    .unwrap_or_default();
                let shrunk_json = shrunk_input
                    .as_ref()
                    .map(|s| format!(r#","shrunk_input":"{}","shrink_steps":{}"#, s, shrink_steps))
                    .unwrap_or_default();

                format!(
                    r#"{{"event":"failed","name":"{}","type":"property_test","error":"{}","original_input":"{}","duration_ms":{}{}{}}}"#,
                    test_name,
                    error.replace('"', r#"\""#),
                    original_input.replace('"', r#"\""#),
                    duration.as_millis(),
                    seed_json,
                    shrunk_json
                )
            }
            _ => format!(
                r#"{{"event":"failed","name":"{}","type":"property_test"}}"#,
                test_name
            ),
        }
    }

    fn format_test_skipped(&self, test_name: &str, result: &TestResult) -> String {
        match result {
            TestResult::Skipped { reason } => {
                format!(
                    r#"{{"event":"ignored","name":"{}","type":"property_test","reason":"{}"}}"#,
                    test_name,
                    reason.replace('"', r#"\""#)
                )
            }
            _ => format!(
                r#"{{"event":"ignored","name":"{}","type":"property_test"}}"#,
                test_name
            ),
        }
    }
}

/// Test execution context for custom test runners
pub struct TestContext {
    pub test_name: String,
    pub formatter: Box<dyn TestOutputFormatter>,
    pub capture_output: bool,
    pub verbose: bool,
}

impl TestContext {
    /// Create a new test context with default settings
    pub fn new(test_name: String) -> Self {
        let verbose = TestRunner::is_verbose_output();
        let formatter: Box<dyn TestOutputFormatter> = if verbose {
            Box::new(VerboseFormatter)
        } else {
            Box::new(DefaultFormatter)
        };

        Self {
            test_name,
            formatter,
            capture_output: !verbose,
            verbose,
        }
    }

    /// Create a test context with JSON output
    pub fn with_json_output(test_name: String) -> Self {
        Self {
            test_name,
            formatter: Box::new(JsonFormatter),
            capture_output: false,
            verbose: false,
        }
    }

    /// Create a test context with custom formatter
    pub fn with_formatter(test_name: String, formatter: Box<dyn TestOutputFormatter>) -> Self {
        Self {
            test_name,
            formatter,
            capture_output: false,
            verbose: false,
        }
    }

    /// Execute a property test with this context
    pub fn execute<T, F>(&self, test_fn: F) -> TestResult
    where
        T: fmt::Debug,
        F: FnOnce() -> PropertyResult<T>,
    {
        if !self.capture_output {
            print!("{}", self.formatter.format_test_start(&self.test_name));
        }

        let result = test_fn();
        let test_result = TestResult::from_property_result(result);

        if !self.capture_output {
            match &test_result {
                TestResult::Passed { .. } => {
                    println!(
                        "{}",
                        self.formatter
                            .format_test_success(&self.test_name, &test_result)
                    );
                }
                TestResult::Failed { .. } => {
                    println!(
                        "{}",
                        self.formatter
                            .format_test_failure(&self.test_name, &test_result)
                    );
                }
                TestResult::Skipped { .. } => {
                    println!(
                        "{}",
                        self.formatter
                            .format_test_skipped(&self.test_name, &test_result)
                    );
                }
            }
        }

        test_result
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{PropertyError, TestConfig};
    use std::time::Duration;

    #[test]
    fn test_format_success() {
        let success: TestSuccess<i32> = TestSuccess::new(
            100,
            TestConfig {
                seed: Some(42),
                ..TestConfig::default()
            },
            None,
        );

        let formatted = TestRunner::format_success(&success);
        assert!(formatted.contains("PASSED"));
        assert!(formatted.contains("100 iterations"));
        assert!(formatted.contains("seed: 42"));
        // Note: TestSuccess doesn't track duration, so we don't check for it
    }

    #[test]
    fn test_format_failure() {
        let failure = TestFailure::new(
            PropertyError::property_failed("Test error"),
            42,
            Some(1),
            5,
            TestConfig {
                seed: Some(123),
                ..TestConfig::default()
            },
            1, // failed_iteration
            Duration::from_millis(200),
            Duration::from_millis(50),
        );

        let formatted = TestRunner::format_failure(&failure);
        assert!(formatted.contains("FAILED"));
        assert!(formatted.contains("Test error"));
        assert!(formatted.contains("42"));
        assert!(formatted.contains("1"));
        assert!(formatted.contains("5 shrinking steps"));
        assert!(formatted.contains("123"));
    }

    #[test]
    fn test_test_result_conversion() {
        let success: PropertyResult<i32> = Ok(TestSuccess::new(50, TestConfig::default(), None));

        let test_result = TestResult::from_property_result(success);
        assert!(test_result.is_passed());
        // TestSuccess doesn't track duration, so it defaults to 0ns
        assert_eq!(test_result.duration(), Some(Duration::from_nanos(0)));
    }

    #[test]
    fn test_default_formatter() {
        let formatter = DefaultFormatter;
        let result = TestResult::Passed {
            iterations: 100,
            duration: Duration::from_millis(500),
            seed: Some(42),
        };

        let start = formatter.format_test_start("my_test");
        assert_eq!(start, "test my_test ... ");

        let success = formatter.format_test_success("my_test", &result);
        assert!(success.contains("ok"));
        assert!(success.contains("100 iterations"));
    }

    #[test]
    fn test_verbose_formatter() {
        let formatter = VerboseFormatter;
        let result = TestResult::Failed {
            error: "Property failed".to_string(),
            original_input: "42".to_string(),
            shrunk_input: Some("1".to_string()),
            shrink_steps: 3,
            seed: Some(123),
            duration: Duration::from_millis(200),
        };

        let failure = formatter.format_test_failure("my_test", &result);
        assert!(failure.contains(""));
        assert!(failure.contains("my_test"));
        assert!(failure.contains("FAILED"));
    }

    #[test]
    fn test_json_formatter() {
        let formatter = JsonFormatter;
        let result = TestResult::Passed {
            iterations: 100,
            duration: Duration::from_millis(500),
            seed: Some(42),
        };

        let success = formatter.format_test_success("my_test", &result);
        assert!(success.contains(r#""event":"ok""#));
        assert!(success.contains(r#""name":"my_test""#));
        assert!(success.contains(r#""iterations":100"#));
        assert!(success.contains(r#""seed":42"#));
    }

    #[test]
    fn test_test_context_creation() {
        let context = TestContext::new("test_name".to_string());
        assert_eq!(context.test_name, "test_name");

        let json_context = TestContext::with_json_output("json_test".to_string());
        assert_eq!(json_context.test_name, "json_test");
        assert!(!json_context.verbose);
    }
}