rvtest 0.2.0

A Next Level Testing Library for Rust — BDD specs, property-based testing, parametrized tests, rich reporting, and code coverage
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! Core types shared across all rvtest modules.
//!
//! This module defines the foundational data structures:
//!
//! - [`TestStatus`] — outcome of a single test (Passed, Failed, Skipped, TimedOut)
//! - [`TestCase`] — a single test with metadata and result
//! - [`TestSuite`] — a collection of related test cases
//! - [`TestRun`] — aggregate results from one or more suites
//! - [`TestKind`] — Unit, Integration, or Doc tests
//! - [`RunnerConfig`] — global configuration for a test run
//! - [`ReportFormat`] / [`CoverageFormat`] — output format enums
//! - [`CoverageReport`] — aggregated coverage metrics
//! - [`SourceLocation`] — file:line:column tracking

use std::fmt;
use std::time::{Duration, SystemTime};

/// A location in source code where a test is defined or an assertion failed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceLocation {
    /// The file path.
    pub file: String,
    /// The line number (1-indexed).
    pub line: u32,
    /// The optional column number.
    pub column: Option<u32>,
}

impl fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.column {
            Some(col) => write!(f, "{}:{}:{}", self.file, self.line, col),
            None => write!(f, "{}:{}", self.file, self.line),
        }
    }
}

/// The outcome of a single test case execution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TestStatus {
    /// The test completed successfully without panicking.
    Passed,
    /// The test panicked or returned an error.
    Failed {
        /// A human-readable description of the failure.
        reason: String,
        /// Where the failure originated, if known.
        location: Option<SourceLocation>,
    },
    /// The test was skipped, optionally with a reason.
    Skipped {
        /// Why the test was skipped.
        reason: Option<String>,
    },
    /// The test exceeded its allotted time budget.
    TimedOut {
        /// The maximum duration allowed.
        duration: Duration,
        /// Where the test is defined, if known.
        location: Option<SourceLocation>,
    },
}

impl TestStatus {
    /// Returns `true` if the status represents a passing outcome.
    pub fn is_passed(&self) -> bool {
        matches!(self, TestStatus::Passed)
    }

    /// Returns `true` if the status represents any kind of failure (including timeout).
    pub fn is_failed(&self) -> bool {
        matches!(self, TestStatus::Failed { .. } | TestStatus::TimedOut { .. })
    }

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

impl fmt::Display for TestStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TestStatus::Passed => write!(f, "PASSED"),
            TestStatus::Failed { reason, .. } => write!(f, "FAILED: {reason}"),
            TestStatus::Skipped { reason: Some(r) } => write!(f, "SKIPPED: {r}"),
            TestStatus::Skipped { reason: None } => write!(f, "SKIPPED"),
            TestStatus::TimedOut { duration, .. } => {
                write!(f, "TIMED OUT after {duration:?}")
            }
        }
    }
}

/// A single test case with its metadata and execution result.
#[derive(Debug, Clone)]
pub struct TestCase {
    /// The human-readable name of the test.
    pub name: String,
    /// The name of the parent suite, if any.
    pub suite: Option<String>,
    /// Tags attached to this test for filtering and organisation.
    pub tags: Vec<String>,
    /// The outcome of executing the test.
    pub status: TestStatus,
    /// How long the test took to execute.
    pub duration: Duration,
    /// How many assertions were performed (best-effort count).
    pub assertions: u64,
    /// Where the test was defined in source code.
    pub location: Option<SourceLocation>,
    /// Named parameters supplied to a parametrized test.
    pub parameters: Vec<(String, String)>,
    /// Captured stdout/stderr output during test execution, if any.
    pub captured_output: Option<String>,
}

impl TestCase {
    /// Create a new test case with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        TestCase {
            name: name.into(),
            suite: None,
            tags: Vec::new(),
            status: TestStatus::Passed,
            duration: Duration::ZERO,
            assertions: 0,
            location: None,
            parameters: Vec::new(),
            captured_output: None,
        }
    }
}

/// The kind of test suite, used by the PrettyReporter for section headers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TestKind {
    /// Unit tests (typically from `src/lib.rs` or `src/main.rs`).
    Unit,
    /// Integration tests (from `tests/` directory).
    Integration,
    /// Documentation tests (code examples in doc comments).
    Doc,
}

/// A collection of related test cases that share a common context.
#[derive(Debug, Clone)]
pub struct TestSuite {
    /// The name of this suite (e.g. a module or `describe` block name).
    pub name: String,
    /// An optional description of what this suite covers.
    pub description: Option<String>,
    /// The test cases belonging to this suite.
    pub tests: Vec<TestCase>,
    /// Total wall-clock duration for all tests in this suite.
    pub duration: Duration,
    /// The kind of tests in this suite.
    pub kind: TestKind,
    /// The source path or crate name (e.g. `src/lib.rs`, `tests/integration.rs`, `rvtest`).
    pub source_path: String,
}

impl TestSuite {
    /// Create a new empty suite with the given name.
    pub fn new(name: impl Into<String>) -> Self {
        TestSuite {
            name: name.into(),
            description: None,
            tests: Vec::new(),
            duration: Duration::ZERO,
            kind: TestKind::Unit,
            source_path: String::new(),
        }
    }

    /// Returns `true` if this suite is a doc-test section.
    pub fn is_doc(&self) -> bool {
        self.kind == TestKind::Doc
    }

    /// Returns the number of tests in this suite.
    pub fn len(&self) -> usize {
        self.tests.len()
    }

    /// Returns `true` if this suite contains no tests.
    pub fn is_empty(&self) -> bool {
        self.tests.is_empty()
    }

    /// Returns an iterator over tests that passed.
    pub fn passed(&self) -> impl Iterator<Item = &TestCase> {
        self.tests.iter().filter(|t| t.status.is_passed())
    }

    /// Returns an iterator over tests that failed.
    pub fn failed(&self) -> impl Iterator<Item = &TestCase> {
        self.tests.iter().filter(|t| t.status.is_failed())
    }

    /// Returns an iterator over tests that were skipped.
    pub fn skipped(&self) -> impl Iterator<Item = &TestCase> {
        self.tests.iter().filter(|t| t.status.is_skipped())
    }

    /// Returns `true` if every test in this suite passed.
    pub fn success(&self) -> bool {
        self.failed().count() == 0
    }

    /// Panics with a detailed failure report if any test in this suite
    /// did not pass. Designed for use inside `#[test]` functions.
    ///
    /// # Example
    ///
    /// ```ignore
    /// #[test]
    /// fn my_tests() {
    ///     describe("Calculator")
    ///         .it("adds", || assert_eq!(2 + 2, 4))
    ///         .run()
    ///         .assert_all_pass();
    /// }
    /// ```
    pub fn assert_all_pass(&self) {
        let failed: Vec<&TestCase> = self.failed().collect();
        if !failed.is_empty() {
            let mut msg = format!(
                "{} test(s) failed in suite '{}':\n",
                failed.len(),
                self.name,
            );
            for t in &failed {
                let dur_ms = t.duration.as_secs_f64() * 1000.0;
                let reason = match &t.status {
                    TestStatus::Failed { reason, .. } => reason.as_str(),
                    TestStatus::TimedOut { .. } => "timed out",
                    _ => "unknown",
                };
                msg.push_str(&format!("{} [{dur_ms:.1}ms] — {reason}\n", t.name));
            }
            panic!("{msg}");
        }
    }
}

/// Aggregated results from an entire test run consisting of one or more suites.
#[derive(Debug, Clone)]
pub struct TestRun {
    /// The suites that were executed.
    pub suites: Vec<TestSuite>,
    /// Wall-clock time the run started.
    pub start_time: SystemTime,
    /// Wall-clock time the run finished.
    pub end_time: SystemTime,
    /// Total wall-clock duration of the run.
    pub duration: Duration,
}

impl TestRun {
    /// Create a new `TestRun` starting now.
    pub fn new() -> Self {
        TestRun {
            suites: Vec::new(),
            start_time: SystemTime::now(),
            end_time: SystemTime::now(),
            duration: Duration::ZERO,
        }
    }

    /// Returns the total number of test cases across all suites.
    pub fn total(&self) -> usize {
        self.suites.iter().map(|s| s.tests.len()).sum()
    }

    /// Returns the number of passed test cases.
    pub fn total_passed(&self) -> usize {
        self.suites.iter().flat_map(|s| s.tests.iter()).filter(|t| t.status.is_passed()).count()
    }

    /// Returns the number of failed test cases (including timeouts).
    pub fn total_failed(&self) -> usize {
        self.suites.iter().flat_map(|s| s.tests.iter()).filter(|t| t.status.is_failed()).count()
    }

    /// Returns the number of skipped test cases.
    pub fn total_skipped(&self) -> usize {
        self.suites.iter().flat_map(|s| s.tests.iter()).filter(|t| t.status.is_skipped()).count()
    }

    /// Returns `true` if every test passed.
    pub fn success(&self) -> bool {
        self.total_failed() == 0
    }

    /// Returns an iterator over all test cases that failed.
    pub fn all_failed(&self) -> impl Iterator<Item = &TestCase> {
        self.suites.iter().flat_map(|s| s.failed())
    }

    /// Returns the `n` slowest test cases across all suites, sorted by
    /// duration (longest first).
    pub fn slowest(&self, n: usize) -> Vec<&TestCase> {
        let mut all: Vec<&TestCase> = self.suites.iter().flat_map(|s| s.tests.iter()).collect();
        all.sort_by(|a, b| b.duration.cmp(&a.duration));
        all.truncate(n);
        all
    }
}

impl Default for TestRun {
    fn default() -> Self {
        Self::new()
    }
}

/// The output format used when rendering test results.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ReportFormat {
    /// Human-readable, colourised output (default).
    #[default]
    Pretty,
    /// Test Anything Protocol — machine-parseable line-based format.
    Tap,
    /// JUnit XML — widely supported by CI systems.
    Junit,
    /// JSON output — suitable for programmatic consumption.
    Json,
    /// Compact single-line-per-test output.
    Compact,
    /// GitHub Actions annotations.
    Github,
}

impl std::str::FromStr for ReportFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "pretty" | "human" => Ok(Self::Pretty),
            "tap" => Ok(Self::Tap),
            "junit" | "xml" => Ok(Self::Junit),
            "json" => Ok(Self::Json),
            "compact" => Ok(Self::Compact),
            "github" | "gh" => Ok(Self::Github),
            _ => Err(format!("unknown report format: {s}")),
        }
    }
}

/// Global configuration for a test run.
#[derive(Debug, Clone)]
pub struct RunnerConfig {
    /// Only run tests whose name contains this string.
    pub filter: Option<String>,
    /// Only run tests carrying *all* of these tags.
    pub include_tags: Vec<String>,
    /// Skip tests carrying *any* of these tags.
    pub exclude_tags: Vec<String>,
    /// Default number of retries for flaky tests.
    pub default_retries: u32,
    /// Default per-test timeout.
    pub default_timeout: Option<Duration>,
    /// Whether to run tests in parallel.
    pub parallel: bool,
    /// Maximum number of threads for parallel execution.
    pub max_threads: usize,
    /// Output format for results.
    pub format: ReportFormat,
    /// Stop after the first failure.
    pub fail_fast: bool,
    /// Seed for randomised features (property testing, shuffle).
    pub seed: Option<u64>,
    /// Show detailed output for each test.
    pub verbose: bool,
    /// Capture stdout/stderr during test execution and show on failure.
    pub output_capture: bool,
}

impl Default for RunnerConfig {
    fn default() -> Self {
        RunnerConfig {
            filter: None,
            include_tags: Vec::new(),
            exclude_tags: Vec::new(),
            default_retries: 0,
            default_timeout: None,
            parallel: true,
            max_threads: num_cpus(),
            format: ReportFormat::Pretty,
            fail_fast: false,
            seed: None,
            verbose: false,
            output_capture: false,
        }
    }
}

// ---------------------------------------------------------------------------
// Coverage types
// ---------------------------------------------------------------------------

/// Output format for coverage reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CoverageFormat {
    /// Plain-text summary printed to stdout.
    #[default]
    Summary,
    /// HTML report with line-level detail.
    Html,
    /// LCOV tracefile (for IDE integration, Coveralls, etc.).
    Lcov,
    /// Machine-readable JSON.
    Json,
    /// Cobertura XML (for Jenkins, GitLab, etc.).
    Cobertura,
}

impl std::str::FromStr for CoverageFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "summary" | "text" => Ok(Self::Summary),
            "html" => Ok(Self::Html),
            "lcov" | "tracefile" => Ok(Self::Lcov),
            "json" => Ok(Self::Json),
            "cobertura" | "xml" => Ok(Self::Cobertura),
            _ => Err(format!("unknown coverage format: {s}")),
        }
    }
}

/// Aggregated coverage metrics for a codebase.
#[derive(Debug, Clone)]
pub struct CoverageReport {
    /// Percentage of lines covered (0.0 – 100.0).
    pub line_coverage: f64,
    /// Percentage of functions covered.
    pub function_coverage: f64,
    /// Percentage of regions (basic blocks) covered.
    pub region_coverage: f64,
    /// The format the full report was generated in.
    pub format: CoverageFormat,
    /// Path to the generated report file, if applicable.
    pub report_path: Option<std::path::PathBuf>,
}

/// Heuristic for the number of available CPUs.
fn num_cpus() -> usize {
    std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    mod test_status {
        use super::*;

        #[test]
        fn passed_is_passed_true() {
            assert!(TestStatus::Passed.is_passed());
        }

        #[test]
        fn passed_is_failed_false() {
            assert!(!TestStatus::Passed.is_failed());
        }

        #[test]
        fn passed_is_skipped_false() {
            assert!(!TestStatus::Passed.is_skipped());
        }

        #[test]
        fn failed_is_failed_true() {
            let s = TestStatus::Failed { reason: "x".into(), location: None };
            assert!(s.is_failed());
        }

        #[test]
        fn failed_is_passed_false() {
            let s = TestStatus::Failed { reason: "x".into(), location: None };
            assert!(!s.is_passed());
        }

        #[test]
        fn skipped_is_skipped_true() {
            let s = TestStatus::Skipped { reason: None };
            assert!(s.is_skipped());
        }

        #[test]
        fn timed_out_is_failed() {
            let s = TestStatus::TimedOut { duration: Duration::from_secs(1), location: None };
            assert!(s.is_failed());
        }

        #[test]
        fn display_passed() {
            assert_eq!(format!("{}", TestStatus::Passed), "PASSED");
        }

        #[test]
        fn display_failed() {
            let s = TestStatus::Failed { reason: "boom".into(), location: None };
            assert_eq!(format!("{}", s), "FAILED: boom");
        }

        #[test]
        fn display_skipped_no_reason() {
            let s = TestStatus::Skipped { reason: None };
            assert_eq!(format!("{}", s), "SKIPPED");
        }

        #[test]
        fn display_skipped_with_reason() {
            let s = TestStatus::Skipped { reason: Some("slow".into()) };
            assert_eq!(format!("{}", s), "SKIPPED: slow");
        }

        #[test]
        fn display_timed_out() {
            let s = TestStatus::TimedOut { duration: Duration::from_secs(5), location: None };
            let text = format!("{}", s);
            assert!(text.contains("TIMED OUT"));
            assert!(text.contains("5s"));
        }
    }

    mod source_location {
        use super::*;

        #[test]
        fn display_with_column() {
            let loc = SourceLocation { file: "src/lib.rs".into(), line: 42, column: Some(7) };
            assert_eq!(format!("{}", loc), "src/lib.rs:42:7");
        }

        #[test]
        fn display_without_column() {
            let loc = SourceLocation { file: "src/lib.rs".into(), line: 42, column: None };
            assert_eq!(format!("{}", loc), "src/lib.rs:42");
        }
    }

    mod test_case {
        use super::*;

        #[test]
        fn new_creates_passed() {
            let tc = TestCase::new("my test");
            assert_eq!(tc.name, "my test");
            assert!(tc.status.is_passed());
            assert_eq!(tc.duration, Duration::ZERO);
        }

        #[test]
        fn new_has_no_suite() {
            let tc = TestCase::new("x");
            assert!(tc.suite.is_none());
        }

        #[test]
        fn new_empty_tags() {
            let tc = TestCase::new("x");
            assert!(tc.tags.is_empty());
        }
    }

    mod test_suite {
        use super::*;

        fn sample_suite() -> TestSuite {
            let mut suite = TestSuite::new("Math");
            suite.tests.push(TestCase {
                name: "add".into(), suite: Some("Math".into()), tags: vec![],
                status: TestStatus::Passed, duration: Duration::from_millis(5),
                assertions: 0, location: None, parameters: vec![], captured_output: None,
            });
            suite.tests.push(TestCase {
                name: "sub".into(), suite: Some("Math".into()), tags: vec![],
                status: TestStatus::Failed { reason: "expected 2 got 3".into(), location: None },
                duration: Duration::from_millis(3), assertions: 0, location: None, parameters: vec![],
                captured_output: None,
            });
            suite.tests.push(TestCase {
                name: "skip".into(), suite: Some("Math".into()), tags: vec![],
                status: TestStatus::Skipped { reason: None },
                duration: Duration::ZERO, assertions: 0, location: None, parameters: vec![],
                captured_output: None,
            });
            suite
        }

        #[test]
        fn len_counts_tests() {
            assert_eq!(sample_suite().len(), 3);
        }

        #[test]
        fn passed_returns_only_passed() {
            assert_eq!(sample_suite().passed().count(), 1);
        }

        #[test]
        fn failed_returns_only_failed() {
            assert_eq!(sample_suite().failed().count(), 1);
        }

        #[test]
        fn skipped_returns_only_skipped() {
            assert_eq!(sample_suite().skipped().count(), 1);
        }

        #[test]
        fn success_false_when_failures() {
            assert!(!sample_suite().success());
        }

        #[test]
        fn success_true_when_all_pass() {
            let mut suite = TestSuite::new("AllGood");
            suite.tests.push(TestCase::new("t1"));
            assert!(suite.success());
        }

        #[test]
        fn empty_suite_is_empty() {
            let suite = TestSuite::new("Empty");
            assert!(suite.is_empty());
        }

        #[test]
        fn is_doc_false_by_default() {
            let suite = TestSuite::new("x");
            assert!(!suite.is_doc());
        }

        #[test]
        fn is_doc_true_when_kind_doc() {
            let mut suite = TestSuite::new("x");
            suite.kind = TestKind::Doc;
            assert!(suite.is_doc());
        }
    }

    mod test_run {
        use super::*;

        fn sample_run() -> TestRun {
            let mut suite = TestSuite::new("A");
            suite.tests.push(TestCase { name: "t1".into(), suite: None, tags: vec![],
                status: TestStatus::Passed, duration: Duration::from_millis(1),
                assertions: 0, location: None, parameters: vec![], captured_output: None });
            suite.tests.push(TestCase { name: "t2".into(), suite: None, tags: vec![],
                status: TestStatus::Failed { reason: "fail".into(), location: None },
                duration: Duration::from_millis(2), assertions: 0, location: None, parameters: vec![], captured_output: None });
            suite.tests.push(TestCase { name: "t3".into(), suite: None, tags: vec![],
                status: TestStatus::Skipped { reason: None },
                duration: Duration::ZERO, assertions: 0, location: None, parameters: vec![], captured_output: None });
            TestRun { suites: vec![suite], start_time: SystemTime::now(),
                end_time: SystemTime::now(), duration: Duration::from_millis(10) }
        }

        #[test]
        fn total_counts_all() {
            assert_eq!(sample_run().total(), 3);
        }

        #[test]
        fn total_passed() {
            assert_eq!(sample_run().total_passed(), 1);
        }

        #[test]
        fn total_failed() {
            assert_eq!(sample_run().total_failed(), 1);
        }

        #[test]
        fn total_skipped() {
            assert_eq!(sample_run().total_skipped(), 1);
        }

        #[test]
        fn success_false_with_failures() {
            assert!(!sample_run().success());
        }

        #[test]
        fn success_true_all_pass() {
            let run = TestRun::new();
            assert!(run.success());
        }

        #[test]
        fn slowest_returns_n_longest() {
            let run = sample_run();
            let slow = run.slowest(2);
            assert_eq!(slow.len(), 2);
            assert_eq!(slow[0].name, "t2");
        }

        #[test]
        fn slowest_returns_all_when_n_larger() {
            let run = sample_run();
            let slow = run.slowest(10);
            assert_eq!(slow.len(), 3);
        }

        #[test]
        fn all_failed_iter() {
            let run = sample_run();
            let failed: Vec<_> = run.all_failed().collect();
            assert_eq!(failed.len(), 1);
            assert_eq!(failed[0].name, "t2");
        }

        #[test]
        fn default_run_empty() {
            let run = TestRun::default();
            assert!(run.suites.is_empty());
            assert!(run.success());
        }
    }

    mod report_format {
        use super::*;

        #[test]
        fn parse_pretty() {
            assert_eq!("pretty".parse::<ReportFormat>().unwrap(), ReportFormat::Pretty);
            assert_eq!("human".parse::<ReportFormat>().unwrap(), ReportFormat::Pretty);
        }

        #[test]
        fn parse_tap() {
            assert_eq!("tap".parse::<ReportFormat>().unwrap(), ReportFormat::Tap);
        }

        #[test]
        fn parse_junit() {
            assert_eq!("junit".parse::<ReportFormat>().unwrap(), ReportFormat::Junit);
            assert_eq!("xml".parse::<ReportFormat>().unwrap(), ReportFormat::Junit);
        }

        #[test]
        fn parse_json() {
            assert_eq!("json".parse::<ReportFormat>().unwrap(), ReportFormat::Json);
        }

        #[test]
        fn parse_compact() {
            assert_eq!("compact".parse::<ReportFormat>().unwrap(), ReportFormat::Compact);
        }

        #[test]
        fn parse_github() {
            assert_eq!("github".parse::<ReportFormat>().unwrap(), ReportFormat::Github);
            assert_eq!("gh".parse::<ReportFormat>().unwrap(), ReportFormat::Github);
        }

        #[test]
        fn parse_unknown_error() {
            assert!("wtf".parse::<ReportFormat>().is_err());
        }

        #[test]
        fn parse_is_case_insensitive() {
            assert_eq!("JSON".parse::<ReportFormat>().unwrap(), ReportFormat::Json);
            assert_eq!("Pretty".parse::<ReportFormat>().unwrap(), ReportFormat::Pretty);
        }

        #[test]
        fn default_is_pretty() {
            assert_eq!(ReportFormat::default(), ReportFormat::Pretty);
        }
    }

    mod coverage_format {
        use super::*;

        #[test]
        fn parse_summary() {
            assert_eq!("summary".parse::<CoverageFormat>().unwrap(), CoverageFormat::Summary);
            assert_eq!("text".parse::<CoverageFormat>().unwrap(), CoverageFormat::Summary);
        }

        #[test]
        fn parse_html() {
            assert_eq!("html".parse::<CoverageFormat>().unwrap(), CoverageFormat::Html);
        }

        #[test]
        fn parse_lcov() {
            assert_eq!("lcov".parse::<CoverageFormat>().unwrap(), CoverageFormat::Lcov);
            assert_eq!("tracefile".parse::<CoverageFormat>().unwrap(), CoverageFormat::Lcov);
        }

        #[test]
        fn parse_json() {
            assert_eq!("json".parse::<CoverageFormat>().unwrap(), CoverageFormat::Json);
        }

        #[test]
        fn parse_cobertura() {
            assert_eq!("cobertura".parse::<CoverageFormat>().unwrap(), CoverageFormat::Cobertura);
            assert_eq!("xml".parse::<CoverageFormat>().unwrap(), CoverageFormat::Cobertura);
        }

        #[test]
        fn parse_unknown_error() {
            assert!("bogus".parse::<CoverageFormat>().is_err());
        }

        #[test]
        fn default_is_summary() {
            assert_eq!(CoverageFormat::default(), CoverageFormat::Summary);
        }
    }

    mod runner_config {
        use super::*;

        #[test]
        fn default_parallel_true() {
            assert!(RunnerConfig::default().parallel);
        }

        #[test]
        fn default_format_pretty() {
            assert_eq!(RunnerConfig::default().format, ReportFormat::Pretty);
        }

        #[test]
        fn default_no_filter() {
            assert!(RunnerConfig::default().filter.is_none());
        }

        #[test]
        fn default_no_tags() {
            let cfg = RunnerConfig::default();
            assert!(cfg.include_tags.is_empty());
            assert!(cfg.exclude_tags.is_empty());
        }

        #[test]
        fn default_zero_retries() {
            assert_eq!(RunnerConfig::default().default_retries, 0);
        }

        #[test]
        fn coverage_report_with_path() {
            let report = CoverageReport {
                line_coverage: 80.0,
                function_coverage: 90.0,
                region_coverage: 80.0,
                format: CoverageFormat::Html,
                report_path: Some(std::path::PathBuf::from("report.html")),
            };
            assert_eq!(report.format, CoverageFormat::Html);
            assert_eq!(report.report_path.unwrap().to_str().unwrap(), "report.html");
        }
    }
}