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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
use std::io::{self, IsTerminal, Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};

use clap::Parser;
use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};

use rvtest::core::{CoverageFormat, ReportFormat, TestRun};
#[cfg(test)]
use rvtest::core::{TestCase, TestKind, TestStatus, TestSuite};
use rvtest::coverage::{CoverageCollector, CoverageConfig};
use rvtest::report::{self, TestReporter};
use rvtest::runner::parse_cargo_test_output;

#[derive(Parser)]
#[command(
    name = "cargo-rvtest",
    about = "A Next Level Testing Library for Rust",
    version,
    long_about = "rvtest is A Next Level Testing Library for Rust.\n\n\
                   rvtest extends Rust's built-in testing with BDD specs, \
                   property-based testing, parametrized tests, and rich reporting. \
                   Use `cargo rvtest` to run tests or `cargo rvtest --coverage` \
                   for code coverage analysis."
)]
struct Cli {
    // === Test options ===
    /// Filter test names by substring (case-insensitive).
    #[arg(short = 'f', long = "filter")]
    filter: Option<String>,

    /// Only run tests carrying all of these tags (can be specified multiple times).
    #[arg(short = 't', long = "tag")]
    include_tags: Vec<String>,

    /// Skip tests carrying any of these tags (can be specified multiple times).
    #[arg(short = 'E', long = "exclude-tag")]
    exclude_tags: Vec<String>,

    /// Number of retries for flaky tests.
    #[arg(short = 'r', long = "retries", default_value = "0")]
    retries: u32,

    /// Default per-test timeout in seconds.
    #[arg(long = "timeout")]
    timeout_secs: Option<f64>,

    /// Run tests sequentially.
    #[arg(long = "no-parallel")]
    no_parallel: bool,

    /// Maximum number of threads for parallel execution.
    #[arg(long = "max-threads", default_value = "0")]
    max_threads: usize,

    /// Output format: pretty, tap, junit, json, compact.
    #[arg(short = 'F', long = "format", default_value = "pretty")]
    format: String,

    /// Stop after the first failure.
    #[arg(long = "fail-fast")]
    fail_fast: bool,

    /// Seed for randomised features.
    #[arg(long = "seed")]
    seed: Option<u64>,

    /// Show verbose output (list all tests).
    #[arg(short = 'v', long = "verbose")]
    verbose: bool,

    /// Show captured stdout/stderr for failing tests.
    #[arg(long = "show-output")]
    show_output: bool,

    // === Watch / Daemon mode ===
    /// Re-run tests automatically when source files change.
    #[arg(long = "watch")]
    watch: bool,

    /// Persistent compile daemon — builds once, re-runs test binaries directly
    /// on file changes for sub-second iteration.
    #[arg(long = "daemon")]
    daemon: bool,

    // === Flaky detection ===
    /// Detect flaky tests by running the suite multiple times.
    /// Optionally specify the number of runs: --detect-flaky=20 (default 10).
    #[arg(long = "detect-flaky", default_missing_value = "10", num_args = 0..=1, require_equals = false, default_value = "0")]
    detect_flaky: u32,

    // === Fast mode ===
    /// Use fast linker (mold/lld) and disable debug info for faster test compilation.
    #[arg(long = "fast")]
    fast: bool,

    /// Use Cranelift codegen backend (requires nightly Rust).
    /// Install: `rustup component add rustc-codegen-cranelift-preview --toolchain nightly`.
    #[arg(long = "cranelift")]
    cranelift: bool,

    /// Number of threads for parallel front-end (requires nightly Rust).
    /// Uses `-Zthreads=N` to speed up type-checking. Typical values: 4–8.
    #[arg(long = "parallel-frontend")]
    parallel_frontend: Option<usize>,

    // === Profiling ===
    /// Show the N slowest tests (default 5). Pass --profile-slow=10 to show top 10.
    #[arg(long = "profile-slow", default_missing_value = "5", num_args = 0..=1, require_equals = false)]
    profile_slow: Option<u32>,

    // === Snapshot options ===
    /// Update all snapshots to match current output.
    #[arg(long = "update-all")]
    update_all: bool,

    /// Review pending snapshots interactively.
    #[arg(long = "review")]
    review: bool,

    // === Coverage options ===
    /// Enable code coverage collection via LLVM instrumentation.
    #[arg(long = "coverage")]
    coverage: bool,

    /// Coverage output format: summary, html, lcov, json, cobertura.
    #[arg(long = "coverage-format", default_value = "summary")]
    coverage_format: String,

    /// Directory to place coverage artifacts.
    #[arg(long = "coverage-dir", default_value = "target/coverage")]
    coverage_dir: PathBuf,

    /// Minimum line-coverage percentage (fails if below threshold).
    #[arg(long = "coverage-min")]
    coverage_min: Option<f64>,

    /// Open coverage report in browser (implies --coverage).
    #[arg(long = "coverage-open")]
    coverage_open: bool,
}

fn main() {
    // Skip the subcommand name when invoked via `cargo rvtest`.
    // Cargo always passes the subcommand name as argv[1].
    let args: Vec<String> = std::env::args().collect();
    let raw_args: Vec<String> = if args.len() > 1 && args[1] == "rvtest" {
        let mut a = vec![args[0].clone()];
        a.extend_from_slice(&args[2..]);
        a
    } else {
        args
    };

    let args = Cli::parse_from(raw_args);

    // === Coverage mode ===
    if args.coverage || args.coverage_open {
        let cov_format: CoverageFormat = args.coverage_format.parse().unwrap_or_else(|e| {
            eprintln!("{e}, falling back to 'summary'");
            CoverageFormat::Summary
        });

        let cov_config = CoverageConfig {
            enabled: true,
            format: cov_format,
            output_dir: args.coverage_dir.clone(),
            min_threshold: args.coverage_min,
            open_report: args.coverage_open,
            ..Default::default()
        };

        let collector = CoverageCollector::new(cov_config);
        match collector.collect() {
            Ok(report) => {
                println!(
                    "Coverage: {:.1}% lines, {:.1}% functions, {:.1}% regions",
                    report.line_coverage,
                    report.function_coverage,
                    report.region_coverage,
                );
                if let Some(path) = &report.report_path {
                    println!("Report: {}", path.display());
                }
                std::process::exit(0);
            }
            Err(e) => {
                eprintln!("Coverage collection failed:\n{e}");
                std::process::exit(1);
            }
        }
    }

    // === Snapshot config ===
    if args.update_all {
        rvtest::snapshot::set_update_all(true);
    }
    if args.review {
        rvtest::snapshot::set_review_mode(true);
    }

    // === Daemon mode ===
    if args.daemon {
        let filter = args.filter.clone();
        let format: ReportFormat = args.format.parse().unwrap_or(ReportFormat::Pretty);
        let daemon = rvtest::daemon::CompileDaemon::new(filter, format);
        daemon.run();
        return;
    }

    // === Watch mode ===
    if args.watch {
        let filter = args.filter.clone();
        let format = args.format.clone();
        let fast = args.fast;
        let slow_count = args.profile_slow.unwrap_or(0) as usize;
        let cranelift = args.cranelift;
        let parallel_frontend = args.parallel_frontend;
        watch_loop(filter, format, fast, slow_count, cranelift, parallel_frontend);
        return;
    }

    // === Flaky detection ===
    if args.detect_flaky > 0 {
        let filter = args.filter.clone();
        let n = args.detect_flaky;
        let verbose = args.verbose;
        let fast = args.fast;
        let cranelift = args.cranelift;
        let parallel_frontend = args.parallel_frontend;
        detect_flaky(filter, n, verbose, fast, cranelift, parallel_frontend);
        return;
    }

    // === Test mode ===
    let format: ReportFormat = args.format.parse().unwrap_or_else(|e| {
        eprintln!("{e}, falling back to 'pretty'");
        ReportFormat::Pretty
    });

    // Warn about nightly requirement for --cranelift / --parallel-frontend
    if args.cranelift || args.parallel_frontend.is_some() {
        if !is_nightly() {
            eprintln!("warning: --cranelift and --parallel-frontend require nightly Rust.\n\
                       Switch with: `rustup default nightly` or use `cargo +nightly rvtest`.");
        }
        if args.cranelift && !has_cranelift_component() {
            eprintln!("warning: Cranelift codegen backend not found.\n\
                       Install: `rustup component add rustc-codegen-cranelift-preview --toolchain nightly`");
        }
    }

    let run = run_cargo_test(args.filter.as_deref(), args.fast, args.cranelift, args.parallel_frontend);

    let report = render(&format, &run, args.profile_slow.unwrap_or(0) as usize);
    println!("{report}");
    std::process::exit(if run.success() { 0 } else { 1 });
}

/// Run `cargo test` and parse the output into a structured [`TestRun`].
fn run_cargo_test(filter: Option<&str>, fast: bool, cranelift: bool, parallel_frontend: Option<usize>) -> TestRun {
    let start = SystemTime::now();
    let wall_start = Instant::now();

    let mut cmd = Command::new("cargo");
    cmd.arg("test").arg("--color=never");

    // Collect extra RUSTFLAGS from fast / cranelift / parallel-frontend
    let mut extra_rustflags: Vec<String> = Vec::new();

    if fast {
        // Disable debug info — 30–40% faster incremental rebuilds
        cmd.env("CARGO_PROFILE_DEV_DEBUG", "0");

        // Auto-detect fast linker (mold → lld)
        if let Some(linker) = detect_fast_linker() {
            extra_rustflags.push(format!("-C link-arg=-fuse-ld={linker}"));
        }
    }

    if cranelift {
        extra_rustflags.push("-Zcodegen-backend=cranelift".to_owned());
    }

    if let Some(n) = parallel_frontend {
        extra_rustflags.push(format!("-Zthreads={n}"));
    }

    // Merge any extra RUSTFLAGS with existing env
    if !extra_rustflags.is_empty() {
        let extra = extra_rustflags.join(" ");
        let existing = std::env::var_os("RUSTFLAGS");
        let merged = match existing {
            Some(ref val) if !val.is_empty() => format!("{} {}", val.to_str().unwrap_or(""), extra),
            None | Some(_) => extra,
        };
        cmd.env("RUSTFLAGS", merged);
    }

    if let Some(f) = filter {
        cmd.arg("--").arg(f);
    }

    let is_tty = io::stdout().is_terminal();
    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();
    let spinner_handle = std::thread::spawn(move || {
        if !is_tty {
            r.store(false, Ordering::SeqCst);
            return;
        }
        let frames = ["", "", "", "", "", "", "", "", "", ""];
        let mut i = 0;
        while r.load(Ordering::SeqCst) {
            print!("\r  {} {}  {} running...", frames[i], dim("cargo test"), dim("tests"));
            io::stdout().flush().ok();
            i = (i + 1) % frames.len();
            std::thread::sleep(Duration::from_millis(80));
        }
    });

    let output = match cmd.output() {
        Ok(o) => {
            running.store(false, Ordering::SeqCst);
            let _ = spinner_handle.join();
            if is_tty {
                print!("\r");
                io::stdout().flush().ok();
            }
            o
        }
        Err(e) => {
            running.store(false, Ordering::SeqCst);
            let _ = spinner_handle.join();
            if is_tty {
                print!("\r");
                io::stdout().flush().ok();
            }
            eprintln!("Error: failed to run `cargo test`: {e}");
            std::process::exit(1);
        }
    };

    let duration = wall_start.elapsed();
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    // Section headers (Running … , Doc-tests …) are on stderr, test lines on stdout.
    let suites = parse_cargo_test_output(&stderr, &stdout);

    TestRun {
        suites,
        start_time: start,
        end_time: SystemTime::now(),
        duration,
    }
}

fn dim(s: &str) -> String {
    format!("\x1b[2m{s}\x1b[0m")
}

/// Returns `true` if the current toolchain is nightly Rust.
fn is_nightly() -> bool {
    let output = Command::new("rustc").arg("--version").output().ok();
    match output {
        Some(o) if o.status.success() => {
            let s = String::from_utf8_lossy(&o.stdout);
            s.contains("nightly")
        }
        _ => false,
    }
}

/// Returns `true` if the Cranelift codegen component is installed.
fn has_cranelift_component() -> bool {
    // Try: `rustc -Zcodegen-backend=cranelift --version`
    let mut cmd = Command::new("rustc");
    cmd.args(["-Zcodegen-backend=cranelift", "--version"]);
    cmd.stdout(Stdio::null()).stderr(Stdio::null());
    cmd.status().map(|s| s.success()).unwrap_or(false)
}

/// Detect the best available fast linker. Returns `Some("mold")` or
/// `Some("lld")` if found, or `None` to use the system default.
fn detect_fast_linker() -> Option<&'static str> {
    // mold provides the biggest speedup — check first
    if Command::new("mold").arg("--version").stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok() {
        return Some("mold");
    }
    // lld is available on most Linux systems; Rust has used it as the
    // default linker since 1.90, but let's verify it's usable.
    if Command::new("ld.lld").arg("--version").stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok() {
        return Some("lld");
    }
    None
}

// (parse_cargo_test_output moved to rvtest::runner)

// ---------------------------------------------------------------------------
// Watch mode
// ---------------------------------------------------------------------------

fn watch_loop(mut filter: Option<String>, format_str: String, fast: bool, slow_count: usize, cranelift: bool, parallel_frontend: Option<usize>) {
    let done = Arc::new(AtomicBool::new(false));
    let format: ReportFormat = format_str.parse().unwrap_or(ReportFormat::Pretty);

    // Build watcher for src/ and tests/.
    let (tx, rx) = std::sync::mpsc::channel::<Result<Event, notify::Error>>();
    let mut watcher = match RecommendedWatcher::new(tx, Config::default()) {
        Ok(w) => w,
        Err(e) => {
            eprintln!("Error: cannot start file watcher: {e}");
            std::process::exit(1);
        }
    };
    for dir in &["src", "tests"] {
        if Path::new(dir).exists() {
            let _ = watcher.watch(Path::new(dir), RecursiveMode::Recursive);
        }
    }

    // Initial run.
    run_and_print(&filter, &format, fast, slow_count, cranelift, parallel_frontend);
    eprint!("  Watching src/, tests/ for changes... [q] quit [r] re-run [f] filter\n\n");

    // Register Ctrl-C handler via libc.
    #[cfg(unix)]
    {
        unsafe {
            libc::signal(libc::SIGINT, sigint_handler as *const () as libc::sighandler_t);
        }
    }

    let debounce = Duration::from_millis(300);
    let mut pending = false;

    loop {
        if done.load(Ordering::SeqCst) {
            break;
        }

        // Collect events within debounce window.
        let deadline = Instant::now() + debounce;
        while Instant::now() < deadline && !done.load(Ordering::SeqCst) {
            match rx.recv_timeout(Duration::from_millis(50)) {
                Ok(Ok(_)) => pending = true,
                Ok(Err(_)) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }

        // Check for keypresses (non-blocking on Unix).
        #[cfg(unix)]
        if !done.load(Ordering::SeqCst) {
            match check_watch_key() {
                WatchKey::Quit => {
                    eprintln!("Quitting.");
                    break;
                }
                WatchKey::Rerun => {
                    eprintln!("  Re-running tests...\n");
                    run_and_print(&filter, &format, fast, slow_count, cranelift, parallel_frontend);
                    eprint!("\n  Watching... [q] quit [r] re-run [f] filter\n\n");
                    continue;
                }
                WatchKey::Filter => {
                    eprint!("  Enter filter: ");
                    let _ = std::io::stdout().flush();
                    let mut input = String::new();
                    if std::io::stdin().read_line(&mut input).is_ok() {
                        let trimmed = input.trim().to_owned();
                        if trimmed.is_empty() {
                            filter = None;
                            eprintln!("  Filter cleared.");
                        } else {
                            filter = Some(trimmed);
                            eprintln!("  Filter set to: {}", filter.as_deref().unwrap_or(""));
                        }
                    }
                    eprintln!("  Re-running tests...\n");
                    run_and_print(&filter, &format, fast, slow_count, cranelift, parallel_frontend);
                    eprint!("\n  Watching... [q] quit [r] re-run [f] filter\n\n");
                    continue;
                }
                WatchKey::None => {}
            }
        }

        if !pending && !done.load(Ordering::SeqCst) {
            std::thread::sleep(Duration::from_millis(100));
            continue;
        }

        pending = false;

        if done.load(Ordering::SeqCst) {
            break;
        }

        eprintln!("  Change detected — re-running tests...\n");
        run_and_print(&filter, &format, fast, slow_count, cranelift, parallel_frontend);
        eprint!("\n  Watching... [q] quit [r] re-run [f] filter\n\n");
    }
}

#[cfg(unix)]
unsafe extern "C" fn sigint_handler(_: libc::c_int) {
    // Default Ctrl-C handling — process will terminate.
}

enum WatchKey { Quit, Rerun, Filter, None }

#[cfg(unix)]
fn check_watch_key() -> WatchKey {
    use std::os::fd::AsRawFd;
    let fd = io::stdin().as_raw_fd();
    let mut fds: libc::fd_set = unsafe { std::mem::zeroed() };
    unsafe { libc::FD_SET(fd, &mut fds) };
    let mut tv = libc::timeval { tv_sec: 0, tv_usec: 0 };
    let ret = unsafe { libc::select(fd + 1, &mut fds, std::ptr::null_mut(), std::ptr::null_mut(), &mut tv) };
    if ret > 0 {
        let mut buf = [0u8; 1];
        if io::stdin().read_exact(&mut buf).is_ok() {
            match buf[0] {
                b'q' | b'Q' => return WatchKey::Quit,
                b'r' | b'R' => return WatchKey::Rerun,
                b'f' | b'F' => return WatchKey::Filter,
                _ => {}
            }
        }
    }
    WatchKey::None
}

#[cfg(not(unix))]
fn check_watch_key() -> WatchKey {
    WatchKey::None
}

/// Run `cargo test` N times and report which tests are flaky.
fn detect_flaky(filter: Option<String>, num_runs: u32, verbose: bool, fast: bool, cranelift: bool, parallel_frontend: Option<usize>) {
    use std::collections::HashMap;

    eprintln!("\n  🔍 Running test suite {num_runs} times to detect flaky tests...\n");

    let mut results: HashMap<String, (u32, u32)> = HashMap::new(); // name → (passes, total)

    for run in 1..=num_runs {
        if verbose {
            eprint!("  Run {run}/{num_runs}... ");
        }

        let test_run = run_cargo_test(filter.as_deref(), fast, cranelift, parallel_frontend);

        for suite in &test_run.suites {
            for test in &suite.tests {
                // Only track tests that actually ran (ignore skipped/ignored).
                if test.status.is_skipped() {
                    continue;
                }
                let entry = results.entry(test.name.clone()).or_insert((0, 0));
                entry.1 += 1; // total
                if test.status.is_passed() {
                    entry.0 += 1; // passes
                }
            }
        }

        if verbose {
            let passed = test_run.total_passed();
            let failed = test_run.total_failed();
            eprintln!("{passed} passed, {failed} failed");
        }
    }

    // Report flaky tests.
    eprintln!();
    let mut flaky_found = false;

    let mut sorted: Vec<_> = results.into_iter().collect();
    sorted.sort_by(|a, b| a.0.cmp(&b.0));

    for (name, (passes, total)) in &sorted {
        let rate = *passes as f64 / *total as f64 * 100.0;
        if rate < 100.0 {
            flaky_found = true;
            eprintln!(
                "  ⚠  {name:<60} {passes}/{total} passes ({rate:.0}%)"
            );
        }
    }

    if !flaky_found {
        eprintln!("  ✅ No flaky tests detected — every test passed on all {num_runs} runs.");
    }
    eprintln!();
}

fn run_and_print(filter: &Option<String>, format: &ReportFormat, fast: bool, slow_count: usize, cranelift: bool, parallel_frontend: Option<usize>) {
    let run = run_cargo_test(filter.as_deref(), fast, cranelift, parallel_frontend);
    let report = render(format, &run, slow_count);
    println!("{report}");
}

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

    #[test]
    fn dim_wraps_in_ansi() {
        let s = dim("hello");
        assert_eq!(s, "\x1b[2mhello\x1b[0m");
    }

    #[test]
    fn dim_empty_string() {
        let s = dim("");
        assert_eq!(s, "\x1b[2m\x1b[0m");
    }

    #[test]
    fn detect_fast_linker_returns_some_or_none() {
        // Just verify it runs without panicking and returns a valid result
        let linker = detect_fast_linker();
        match linker {
            Some("mold") | Some("lld") | None => {}
            _ => panic!("unexpected linker: {linker:?}"),
        }
    }

    #[test]
    fn parse_cargo_test_output_empty() {
        let suites = parse_cargo_test_output("", "");
        assert!(suites.is_empty() || suites.len() == 1);
    }

    #[test]
    fn parse_cargo_test_output_with_one_pass() {
        let stderr = "Running unittests src/lib.rs (target/debug/deps/lib-abc123)\n";
        let stdout = "test my_test ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert_eq!(suites[0].tests.len(), 1);
        assert!(suites[0].tests[0].status.is_passed());
    }

    #[test]
    fn parse_cargo_test_output_with_failure() {
        let stderr = "Running unittests src/lib.rs (target/debug/deps/lib-abc123)\n";
        let stdout = "test failing_test ... FAILED\n\ntest result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out\n\nfailures:\n\nfailures:\n    failing_test\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert!(!suites[0].success());
    }

    #[test]
    fn parse_cargo_test_output_with_ignored() {
        let stderr = "Running unittests src/lib.rs (target/debug/deps/lib-abc123)\n";
        let stdout = "test skipped_test ... ignored\ntest result: ok. 0 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert!(suites[0].tests[0].status.is_skipped());
    }

    #[test]
    fn parse_cargo_test_output_multiple_sections() {
        let stderr = "Running unittests src/lib.rs (target/debug/deps/lib-abc123)\nRunning tests/integration.rs (target/debug/deps/integration-def456)\n";
        let stdout = "test unit_test ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\ntest integration_test ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 2);
    }

    #[test]
    fn parse_cargo_test_output_doc_tests() {
        let stderr = "Doc-tests rvtest\n";
        let stdout = "test test_foo ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert_eq!(suites[0].kind, TestKind::Doc);
    }

    #[test]
    fn parse_cargo_test_output_fallback_section() {
        let suites = parse_cargo_test_output("", "test foo ... ok\ntest result: ok. 1 passed; 0 failed; 0 ignored\n");
        assert!(!suites.is_empty());
    }

    #[test]
    fn parse_cargo_test_output_failure_details() {
        let stderr = "Running unittests src/lib.rs (target/debug/deps/lib-abc123)\n";
        let stdout = "\
---- my_test stdout ----
some detail line
another detail
test my_test ... FAILED
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out
failures:
    my_test
";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert!(!suites.is_empty());
        assert!(!suites[0].success());
    }

    #[test]
    fn parse_cargo_test_output_doc_test_name_formatting() {
        let stderr = "Doc-tests rvtest\n";
        let stdout = "test test_foo ... ok\ntest result: ok. 1 passed; 0 failed\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert_eq!(suites[0].kind, TestKind::Doc);
        assert_eq!(suites[0].source_path, "rvtest");
        assert_eq!(suites[0].tests[0].name, "rvtest - test_foo");
    }

    #[test]
    fn parse_cargo_test_output_failure_with_location_suite_name() {
        let stderr = "Running tests/integration.rs (target/debug/deps/integration-abc)\n";
        let stdout = "test my_test ... FAILED\ntest result: FAILED. 0 passed; 1 failed\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites[0].kind, TestKind::Integration);
        assert_eq!(suites[0].source_path, "tests/integration.rs");
    }

    #[test]
    fn render_with_slow_tests() {
        let mut suite = TestSuite::new("test");
        suite.tests.push(TestCase {
            name: "test :: slow".into(), suite: Some("test".into()), tags: vec![],
            status: TestStatus::Passed, duration: Duration::from_secs(2),
            assertions: 0, location: None, parameters: vec![], captured_output: None,
        });
        let run = TestRun {
            suites: vec![suite],
            start_time: SystemTime::now(),
            end_time: SystemTime::now(),
            duration: Duration::from_secs(2),
        };
        let result = render(&ReportFormat::Compact, &run, 5);
        assert!(result.contains("Slowest"));
        assert!(result.contains("2.00s"));
    }

    #[test]
    fn render_without_slow() {
        let run = TestRun::new();
        let result = render(&ReportFormat::Compact, &run, 0);
        assert!(result.contains("0/0"));
    }

    #[test]
    fn render_all_formats() {
        let run = TestRun::new();
        for fmt in [ReportFormat::Pretty, ReportFormat::Tap, ReportFormat::Junit, ReportFormat::Json, ReportFormat::Compact, ReportFormat::Github] {
            let result = render(&fmt, &run, 0);
            assert!(!result.is_empty(), "render output should not be empty for {fmt:?}");
        }
    }

    #[test]
    fn render_slow_zero_no_slow_section() {
        // When slow_count is 0, no slow test section should be added
        let mut suite = TestSuite::new("test");
        suite.tests.push(TestCase {
            name: "test :: fast".into(), suite: Some("test".into()), tags: vec![],
            status: TestStatus::Passed, duration: Duration::from_millis(1),
            assertions: 0, location: None, parameters: vec![], captured_output: None,
        });
        let run = TestRun {
            suites: vec![suite],
            start_time: SystemTime::now(),
            end_time: SystemTime::now(),
            duration: Duration::from_millis(1),
        };
        let result = render(&ReportFormat::Pretty, &run, 0);
        assert!(!result.contains("Slowest"), "should not show slowest section when count is 0");
    }

    #[test]
    fn render_slow_nonzero_no_tests() {
        // When slow_count > 0 but no tests, no slow section
        let run = TestRun::new();
        let result = render(&ReportFormat::Pretty, &run, 5);
        assert!(!result.contains("Slowest"));
    }

    #[test]
    fn render_pretty_with_multiple_suites() {
        let mut s1 = TestSuite::new("A");
        s1.tests.push(TestCase::new("A :: t1"));
        let mut s2 = TestSuite::new("B");
        s2.tests.push(TestCase::new("B :: t2"));
        let run = TestRun {
            suites: vec![s1, s2],
            start_time: SystemTime::now(),
            end_time: SystemTime::now(),
            duration: Duration::from_millis(10),
        };
        let result = render(&ReportFormat::Pretty, &run, 0);
        assert!(result.contains("A"));
        assert!(result.contains("B"));
    }

    #[test]
    fn format_duration_exact_second() {
        // 1.0s exactly should format as seconds
        let s = crate::report::format_duration(Duration::from_secs(1));
        assert_eq!(s, "1.00s");
    }

    #[test]
    fn format_duration_just_below_second() {
        let s = crate::report::format_duration(Duration::from_millis(999));
        assert_eq!(s, "999.0ms");
    }

    // ---- parse_cargo_test_output edge cases ----

    #[test]
    fn parse_cargo_test_output_no_parentheses() {
        // Running line without parentheses
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "test foo ... ok\ntest result: ok. 1 passed; 0 failed\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert!(!suites.is_empty());
    }

    #[test]
    fn parse_cargo_test_output_malformed_test_line() {
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "test malformed_no_separator\ntest result: ok. 0 passed; 0 failed\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        // The malformed line should be silently skipped
        assert_eq!(suites.len(), 1);
        assert_eq!(suites[0].tests.len(), 0);
    }

    #[test]
    fn parse_cargo_test_output_extra_lines_after_last_section() {
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "test t1 ... ok\ntest result: ok. 1 passed; 0 failed\ntest extra_after_result ... ok\n";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert_eq!(suites.len(), 1);
        assert_eq!(suites[0].tests.len(), 1);
    }

    #[test]
    fn parse_cargo_test_output_multiple_failures_with_details() {
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "\
---- test_a stdout ----
detail for a
---- test_b stdout ----
detail for b
test test_a ... FAILED
test test_b ... FAILED
test result: FAILED. 0 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out
failures:
    test_a
    test_b
";
        let suites = parse_cargo_test_output(stderr, stdout);
        assert!(!suites.is_empty());
        assert!(!suites[0].success());
        assert_eq!(suites[0].tests.len(), 2);
    }

    #[test]
    fn parse_cargo_test_output_empty_failure_line() {
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "\
---- my_test stdout ----

test my_test ... FAILED
test result: FAILED. 0 passed; 1 failed; 0 ignored
failures:
    my_test
";
        let suites = parse_cargo_test_output(stderr, stdout);
        // Empty lines inside failure block should be handled
        assert!(!suites[0].success());
    }

    #[test]
    fn parse_cargo_test_output_unknown_status_skipped() {
        let stderr = "Running unittests src/lib.rs\n";
        let stdout = "\
test my_test ... ???unknown???
test result: ok. 0 passed; 0 failed; 0 ignored
";
        let suites = parse_cargo_test_output(stderr, stdout);
        // Unknown status lines are skipped
        assert_eq!(suites[0].tests.len(), 0);
    }

    // ---- is_nightly ----

    #[test]
    fn is_nightly_returns_bool() {
        // Should not panic, returns true on nightly or false on stable
        let _ = is_nightly();
    }

    // ---- has_cranelift_component ----

    #[test]
    fn has_cranelift_component_returns_bool() {
        // Should not panic — returns true only if component is installed
        let _ = has_cranelift_component();
    }

    // ---- Cli arg parsing ----

    #[test]
    fn cli_defaults() {
        let args = Cli::parse_from(["cargo-rvtest"]);
        assert!(!args.fast);
        assert!(!args.cranelift);
        assert!(args.parallel_frontend.is_none());
    }

    #[test]
    fn cli_cranelift_flag() {
        let args = Cli::parse_from(["cargo-rvtest", "--cranelift"]);
        assert!(args.cranelift);
    }

    #[test]
    fn cli_parallel_frontend() {
        let args = Cli::parse_from(["cargo-rvtest", "--parallel-frontend", "4"]);
        assert_eq!(args.parallel_frontend, Some(4));
    }

    #[test]
    fn cli_cranelift_with_fast() {
        let args = Cli::parse_from(["cargo-rvtest", "--fast", "--cranelift"]);
        assert!(args.fast);
        assert!(args.cranelift);
    }

    #[test]
    fn cli_review_flag() {
        let args = Cli::parse_from(["cargo-rvtest", "--review"]);
        assert!(args.review);
    }

    #[test]
    fn cli_daemon_flag() {
        let args = Cli::parse_from(["cargo-rvtest", "--daemon"]);
        assert!(args.daemon);
    }

    #[test]
    fn cli_all_fast_flags() {
        let args = Cli::parse_from([
            "cargo-rvtest",
            "--fast",
            "--cranelift",
            "--parallel-frontend",
            "8",
        ]);
        assert!(args.fast);
        assert!(args.cranelift);
        assert_eq!(args.parallel_frontend, Some(8));
    }

}

fn render(format: &ReportFormat, run: &TestRun, slow_count: usize) -> String {
    let reporter: Box<dyn TestReporter> = match format {
        ReportFormat::Pretty => Box::new(report::PrettyReporter::new()),
        ReportFormat::Tap => Box::new(report::TapReporter),
        ReportFormat::Junit => Box::new(report::JunitReporter::new()),
        ReportFormat::Json => Box::new(report::JsonReporter),
        ReportFormat::Compact => Box::new(report::CompactReporter),
        ReportFormat::Github => Box::new(report::GithubReporter),
    };
    let mut out = reporter.report(run);

    if slow_count > 0 {
        let slow = run.slowest(slow_count);
        if !slow.is_empty() {
            use std::fmt::Write;
            let _ = writeln!(out);
            let _ = writeln!(out, "  {} Slowest tests", dim(""));
            for (i, test) in slow.iter().enumerate() {
                let dur = report::format_duration(test.duration);
                let name = test.name.replace(" :: ", " > ");
                let _ = writeln!(out, "    {}.  {:>8}  {}", i + 1, dur, name);
            }
        }
    }

    out
}