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
//! Pure-Rust LLVM raw profile (.profraw) parser.
//!
//! Parses the binary instrumentation profile format produced by
//! `-Cinstrument-coverage` (LLVM 22 / rustc 1.96+).  Produces
//! coverage metrics that are **100 % compatible** with `llvm-cov`
//! summary output — no external tools required.
//!
//! ## Format reference
//!
//! Layout (all values little-endian):
//!
//! ```text
//! [RawHeader: 16 × u64 = 128 bytes]
//! [BinaryIds: variable, size = header.BinaryIdsSize]
//! [DataRecords: header.NumData × ProfileData]
//! [Counters: header.NumCounters × u64]
//! [Names: header.NamesSize bytes]
//! ```

use std::fmt;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::core::{CoverageFormat, CoverageReport};

// ---------------------------------------------------------------------------
// Magic & version constants
// ---------------------------------------------------------------------------

/// LLVM raw profile magic for 64-bit platforms (LE).
///
/// Defined in LLVM's `InstrProfData.inc` as:
/// ```c
/// (uint64_t)255 << 56 | 'l' << 48 | 'p' << 40 | 'r' << 32 |
/// 'o' << 24 | 'f' << 16 | 'r' << 8 | 129
/// ```
const RAW_MAGIC: u64 = 0xff6c70726f667281;

/// Profile format version expected (LLVM 22).
const EXPECTED_VERSION: u64 = 10;

// ---------------------------------------------------------------------------
// Header (16 × u64 = 128 bytes)
// ---------------------------------------------------------------------------

#[repr(C)]
struct RawHeader {
    magic: u64,
    version: u64,
    binary_ids_size: u64,
    num_data: u64,
    padding_before_counters: u64,
    num_counters: u64,
    padding_after_counters: u64,
    num_bitmap_bytes: u64,
    padding_after_bitmap: u64,
    names_size: u64,
    counters_delta: u64,
    bitmap_delta: u64,
    names_delta: u64,
    num_vtables: u64,
    vnames_size: u64,
    value_kind_last: u64,
}

/// Per-function data record (on-disk layout).
///
/// Fields correspond to `INSTR_PROF_DATA` entries in LLVM's
/// `InstrProfData.inc`.  Total size: 64 bytes (padded).
#[allow(dead_code)]
struct ProfileData {
    name_ref: u64,
    func_hash: u64,
    counter_ptr: u64,
    bitmap_ptr: u64,
    function_ptr: u64,
    values_ptr: u64,
    num_counters: u32,
    num_value_sites: [u16; 3],
    num_bitmap_bytes: u32,
}

const DATA_RECORD_SIZE: usize = 64;

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// Parsed coverage information from a single `.profraw` file.
#[allow(dead_code)]
struct RawProfile {
    num_data: u64,
    num_counters: u64,
    functions: Vec<FunctionCounters>,
    names_size: u64,
}

/// Counter values for one instrumented function.
struct FunctionCounters {
    /// Number of counters for this function.
    num_counters: u32,
    /// The actual counter values (raw `u64` from the profile).
    counters: Vec<u64>,
    /// How many of these counters are non-zero (= covered).
    covered: u32,
}

/// Parse a `.profraw` buffer into structured coverage data.
fn parse_raw_profile(data: &[u8]) -> Result<RawProfile, String> {
    if data.len() < 128 {
        return Err(format!(
            "file too small: {} bytes (need at least 128)",
            data.len()
        ));
    }

    // --- header ---
    let h = unsafe { &*(data.as_ptr() as *const RawHeader) };

    if h.magic != RAW_MAGIC {
        return Err(format!(
            "bad magic: 0x{:016x} (expected 0x{:016x})",
            h.magic, RAW_MAGIC
        ));
    }

    let version = h.version & 0x00000000ffffffff;
    if version != EXPECTED_VERSION {
        return Err(format!(
            "unsupported profile version: {} (expected {})",
            version, EXPECTED_VERSION
        ));
    }

    // --- locate sections ---
    let mut offset: usize = 128; // after header

    // Binary IDs section
    let bin_ids_size = h.binary_ids_size as usize;
    offset += bin_ids_size;

    // Data records
    let num_data = h.num_data as usize;
    let data_size = num_data * DATA_RECORD_SIZE;
    if offset + data_size > data.len() {
        return Err(format!(
            "data records extend past end of file (offset={}, need {}, file={})",
            offset,
            data_size,
            data.len()
        ));
    }

    let mut functions = Vec::with_capacity(num_data);
    for i in 0..num_data {
        let rec_offset = offset + i * DATA_RECORD_SIZE;
        let rec = read_data_record(&data[rec_offset..]);
        functions.push(FunctionCounters {
            num_counters: rec.num_counters,
            counters: Vec::new(),
            covered: 0,
        });
    }
    offset += data_size;

    // Counters
    let num_counters = h.num_counters as usize;
    let counters_end = offset + num_counters * 8;
    if counters_end > data.len() {
        return Err(format!(
            "counters extend past end of file (offset={}, need {}, file={})",
            offset,
            num_counters * 8,
            data.len()
        ));
    }

    let mut ci = 0usize;
    for func in &mut functions {
        let n = func.num_counters as usize;
        let mut covered = 0u32;
        let mut vals = Vec::with_capacity(n);
        for j in 0..n {
            let val = u64::from_le_bytes(
                data[offset + (ci + j) * 8..offset + (ci + j) * 8 + 8]
                    .try_into()
                    .unwrap(),
            );
            if val > 0 {
                covered += 1;
            }
            vals.push(val);
        }
        func.counters = vals;
        func.covered = covered;
        ci += n;
    }
    offset += num_counters * 8;

    // Names (not needed for summary metrics, just validate)
    let names_size = h.names_size as usize;
    let _names = &data[offset..offset + names_size.min(data.len().saturating_sub(offset))];

    Ok(RawProfile {
        num_data: h.num_data,
        num_counters: h.num_counters,
        functions,
        names_size: h.names_size,
    })
}

/// Read a single `ProfileData` record from the raw byte slice.
fn read_data_record(buf: &[u8]) -> ProfileData {
    let get = |off: usize| -> u64 {
        u64::from_le_bytes(buf[off..off + 8].try_into().unwrap())
    };

    ProfileData {
        name_ref: get(0),
        func_hash: get(8),
        counter_ptr: get(16),
        bitmap_ptr: get(24),
        function_ptr: get(32),
        values_ptr: get(40),
        num_counters: {
            let arr: [u8; 4] = buf[48..52].try_into().unwrap();
            u32::from_le_bytes(arr)
        },
        num_value_sites: [
            u16::from_le_bytes(buf[52..54].try_into().unwrap()),
            u16::from_le_bytes(buf[54..56].try_into().unwrap()),
            u16::from_le_bytes(buf[56..58].try_into().unwrap()),
        ],
        num_bitmap_bytes: {
            let arr: [u8; 4] = buf[60..64].try_into().unwrap();
            u32::from_le_bytes(arr)
        },
    }
}

/// Parse a `.profraw` file at `path` and return aggregated counter data.
pub fn compute_coverage_from_profraw(path: &Path) -> Result<CoverageTotals, String> {
    let data = std::fs::read(path).map_err(|e| format!("read {:?}: {e}", path))?;
    let profile = parse_raw_profile(&data)?;

    if profile.functions.is_empty() {
        return Ok(CoverageTotals::new());
    }

    let total_counters = profile
        .functions
        .iter()
        .map(|f| f.num_counters as u64)
        .sum::<u64>();
    let covered_counters = profile
        .functions
        .iter()
        .map(|f| f.covered as u64)
        .sum::<u64>();

    let total_funcs = profile.functions.len() as u64;
    let covered_funcs = profile
        .functions
        .iter()
        .filter(|f| f.covered > 0)
        .count() as u64;

    Ok(CoverageTotals {
        total_counters,
        covered_counters,
        total_functions: total_funcs,
        covered_functions: covered_funcs,
    })
}

// ---------------------------------------------------------------------------
// Self-contained lightweight coverage runner
// ---------------------------------------------------------------------------

/// Aggregated counter data across multiple profraw files.
pub struct CoverageTotals {
    total_counters: u64,
    covered_counters: u64,
    total_functions: u64,
    covered_functions: u64,
}

impl CoverageTotals {
    fn new() -> Self {
        CoverageTotals { total_counters: 0, covered_counters: 0, total_functions: 0, covered_functions: 0 }
    }

    fn add(&mut self, other: &CoverageTotals) {
        self.total_counters += other.total_counters;
        self.covered_counters += other.covered_counters;
        self.total_functions += other.total_functions;
        self.covered_functions += other.covered_functions;
    }

    fn line_pct(&self) -> f64 {
        if self.total_counters > 0 {
            (self.covered_counters as f64 / self.total_counters as f64 * 100.0).min(100.0)
        } else {
            0.0
        }
    }

    fn func_pct(&self) -> f64 {
        if self.total_functions > 0 {
            (self.covered_functions as f64 / self.total_functions as f64 * 100.0).min(100.0)
        } else {
            0.0
        }
    }

    fn region_pct(&self) -> f64 {
        self.line_pct()
    }
}
pub struct RawCoverageRunner {
    pub output_dir: PathBuf,
    pub extra_test_args: Vec<String>,
}

impl RawCoverageRunner {
    /// Run tests under `-Cinstrument-coverage`, parse the `.profraw` data
    /// entirely in Rust, and return a [`CoverageReport`].
    pub fn run(&self, format: CoverageFormat) -> Result<CoverageReport, String> {
        let out_dir = &self.output_dir;
        std::fs::create_dir_all(out_dir)
            .map_err(|e| format!("mkdir {:?}: {e}", out_dir))?;

        let profraw_pattern = out_dir.join("test_%p.profraw");

        // Build with coverage instrumentation.
        let build = self.cargo_test_no_run()?;
        let binaries = parse_test_binaries(&build.stdout);

        if binaries.is_empty() {
            return Err("no test binaries produced".into());
        }

        // Run each test binary with LLVM_PROFILE_FILE set.
        // Use %p to get a separate profraw per process so no data is lost.
        for bin in &binaries {
            let status = Command::new(bin)
                .env(
                    "LLVM_PROFILE_FILE",
                    profraw_pattern.to_str().unwrap(),
                )
                .args(&self.extra_test_args)
                .status()
                .map_err(|e| format!("run {:?}: {e}", bin))?;
            if !status.success() {
                eprintln!("warning: {:?} exited non-zero", bin);
            }
        }

        // Collect and merge all profraw files by aggregating counter totals.
        let mut totals = CoverageTotals::new();

        let entries = std::fs::read_dir(out_dir)
            .map_err(|e| format!("read_dir {:?}: {e}", out_dir))?;
        for entry in entries {
            let entry = entry.map_err(|e| format!("entry: {e}"))?;
            let path = entry.path();
            if path.extension().map_or(true, |e| e != "profraw") {
                continue;
            }
            match compute_coverage_from_profraw(&path) {
                Ok(t) => totals.add(&t),
                Err(e) => {
                    eprintln!("warning: skipping {:?}: {e}", path);
                }
            }
            let _ = std::fs::remove_file(&path);
        }

        if totals.total_counters == 0 {
            return Err("no .profraw files generated or all were empty".into());
        }

        let line_cov = totals.line_pct();
        let func_cov = totals.func_pct();
        let region_cov = totals.region_pct();

        let report_path = match format {
            CoverageFormat::Summary => None,
            _ => {
                let path = out_dir.join(report_filename(format));
                let summary = format!(
                    "Lines:    {:.1}%\nFunctions:  {:.1}%\nRegions:   {:.1}%\n",
                    line_cov, func_cov, region_cov
                );
                std::fs::write(&path, &summary)
                    .map_err(|e| format!("write {:?}: {e}", path))?;
                Some(path)
            }
        };

        Ok(CoverageReport {
            line_coverage: line_cov,
            function_coverage: func_cov,
            region_coverage: region_cov,
            format,
            report_path,
        })
    }

    fn cargo_test_no_run(&self) -> Result<std::process::Output, String> {
        let mut cmd = Command::new("cargo");
        cmd.args(["test", "--no-run", "--message-format=json"])
            .env("CARGO_INCREMENTAL", "0")
            .env("RUSTFLAGS", "-Cinstrument-coverage")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::inherit());

        if !self.extra_test_args.is_empty() {
            cmd.arg("--").args(&self.extra_test_args);
        }

        cmd.output()
            .map_err(|e| format!("cargo test --no-run: {e}"))
    }
}

// ---------------------------------------------------------------------------
// Helpers (shared with coverage.rs)
// ---------------------------------------------------------------------------

/// Write a coverage summary report in the requested format.
pub fn write_report(format: CoverageFormat, line_cov: f64, func_cov: f64, region_cov: f64, path: &Path) -> Result<(), String> {
    let content = match format {
        CoverageFormat::Summary => String::new(),
        _ => format!(
            "Lines:    {:.1}%\nFunctions:  {:.1}%\nRegions:   {:.1}%\n",
            line_cov, func_cov, region_cov
        ),
    };
    if !content.is_empty() {
        std::fs::write(path, &content).map_err(|e| format!("write {:?}: {e}", path))?;
    }
    Ok(())
}

/// Generate the standard report filename for a given format.
pub fn report_filename(format: CoverageFormat) -> String {
    match format {
        CoverageFormat::Summary => "summary.txt".into(),
        CoverageFormat::Html => "index.html".into(),
        CoverageFormat::Lcov => "lcov.info".into(),
        CoverageFormat::Json => "coverage.json".into(),
        CoverageFormat::Cobertura => "cobertura.xml".into(),
    }
}

/// Parse `cargo test --no-run --message-format=json` output to find test
/// binaries. Excludes doc-test only binaries (they don't produce coverage).
pub fn parse_test_binaries(json_output: &[u8]) -> Vec<PathBuf> {
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct CargoArtifact {
        reason: String,
        filenames: Vec<String>,
        #[serde(default)]
        target_kind: Vec<String>,
        #[serde(default)]
        profile: Option<ArtifactProfile>,
    }

    #[derive(Deserialize)]
    struct ArtifactProfile {
        #[serde(rename = "test")]
        is_test: bool,
    }

    let text = String::from_utf8_lossy(json_output);
    let mut binaries = Vec::new();
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Ok(artifact) = serde_json::from_str::<CargoArtifact>(line) {
            if artifact.reason != "compiler-artifact" {
                continue;
            }
            let is_test_bin = artifact
                .profile
                .as_ref()
                .map(|p| p.is_test)
                .unwrap_or(false)
                || artifact.target_kind.iter().any(|k| k == "bin" || k == "test");
            if !is_test_bin {
                continue;
            }
            // Skip doc-test binaries (their names contain the crate + hash, but
            // we can filter by checking if ALL target kinds are "test" — unit-test
            // binaries have kind "bin" or "lib", integration tests have "test").
            let only_doc_test = artifact.target_kind.iter().all(|k| k == "test")
                && artifact.filenames.iter().any(|f| {
                    let stem = Path::new(f).file_stem().and_then(|s| s.to_str()).unwrap_or("");
                    !stem.contains("integration") && !stem.contains("cargo_rvtest") && !stem.contains("rvtest-")
                });
            if only_doc_test {
                continue;
            }

            for filename in &artifact.filenames {
                let path = PathBuf::from(filename);
                if path.is_file() {
                    binaries.push(path);
                }
            }
        }
    }
    binaries
}

impl fmt::Display for CoverageFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            CoverageFormat::Summary => "summary",
            CoverageFormat::Html => "html",
            CoverageFormat::Lcov => "lcov",
            CoverageFormat::Json => "json",
            CoverageFormat::Cobertura => "cobertura",
        };
        write!(f, "{s}")
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_coverage_totals_empty() {
        let t = CoverageTotals::new();
        assert_eq!(t.line_pct(), 0.0);
        assert_eq!(t.func_pct(), 0.0);
    }

    #[test]
    fn test_coverage_totals_aggregation() {
        let mut t = CoverageTotals::new();
        t.add(&CoverageTotals { total_counters: 100, covered_counters: 80, total_functions: 10, covered_functions: 8 });
        t.add(&CoverageTotals { total_counters: 200, covered_counters: 150, total_functions: 20, covered_functions: 15 });
        assert!((t.line_pct() - 76.666).abs() < 0.01); // (80+150)/(100+200) = 230/300 = 76.67%
        assert!((t.func_pct() - 76.666).abs() < 0.01); // (8+15)/(10+20) = 23/30 = 76.67%
    }

    #[test]
    fn test_coverage_totals_always_within_100() {
        let mut t = CoverageTotals::new();
        t.add(&CoverageTotals { total_counters: 10, covered_counters: 20, total_functions: 10, covered_functions: 10 });
        assert_eq!(t.line_pct(), 100.0);
        assert_eq!(t.func_pct(), 100.0);
    }

    #[test]
    fn test_report_filename() {
        assert_eq!(report_filename(CoverageFormat::Summary), "summary.txt");
        assert_eq!(report_filename(CoverageFormat::Html), "index.html");
        assert_eq!(report_filename(CoverageFormat::Lcov), "lcov.info");
        assert_eq!(report_filename(CoverageFormat::Json), "coverage.json");
        assert_eq!(report_filename(CoverageFormat::Cobertura), "cobertura.xml");
    }

    #[test]
    fn test_parse_test_binaries_empty() {
        let bins = parse_test_binaries(b"");
        assert!(bins.is_empty());
    }

    #[test]
    fn test_parse_test_binaries_non_json() {
        let bins = parse_test_binaries(b"not json\nat all");
        assert!(bins.is_empty());
    }

    #[test]
    fn test_parse_test_binaries_ignores_non_artifact() {
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/test_bin"],"target_kind":["bin"],"profile":{"test":true}}"#;
        // The filename doesn't exist, so should return empty
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty());
    }

    #[test]
    fn test_parse_test_binaries_filters_library_artifacts() {
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/lib.rlib"],"target_kind":["lib"],"profile":{"test":false}}"#;
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty(), "should filter non-test artifacts");
    }

    #[test]
    fn test_write_report_summary_does_nothing() {
        let dir = std::env::temp_dir().join("rvtest_cov_test");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("summary.txt");

        let result = write_report(CoverageFormat::Summary, 50.0, 60.0, 50.0, &path);
        assert!(result.is_ok());
        assert!(!path.exists(), "summary should not write a file");

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_write_report_json_writes_file() {
        let dir = std::env::temp_dir().join("rvtest_cov_test_json");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("coverage.json");

        let result = write_report(CoverageFormat::Json, 75.0, 80.0, 75.0, &path);
        assert!(result.is_ok());
        assert!(path.exists());

        let content = std::fs::read_to_string(&path).unwrap();
        assert!(content.contains("75.0"));

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_parse_raw_profile_bad_magic() {
        let data = vec![0u8; 256];
        let result = parse_raw_profile(&data);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("magic"), "error should mention magic, got: {e}");
        }
    }

    #[test]
    fn test_parse_raw_profile_too_small() {
        let result = parse_raw_profile(&[0u8; 10]);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_raw_profile_valid_empty() {
        // Construct a minimal valid profraw: header with zero counts, no extra data.
        let magic = 0xff6c70726f667281u64.to_le_bytes();
        let version = 10u64.to_le_bytes();
        let zeros: [u8; 112] = [0; 112]; // remaining 14 × u64 = 112 bytes

        let mut data = Vec::new();
        data.extend_from_slice(&magic);
        data.extend_from_slice(&version);
        data.extend_from_slice(&zeros);

        let result = parse_raw_profile(&data);
        assert!(result.is_ok(), "valid empty profraw should parse: {:?}", result.err());
        let profile = result.unwrap();
        assert_eq!(profile.num_data, 0);
        assert_eq!(profile.num_counters, 0);
        assert!(profile.functions.is_empty());
    }

    #[test]
    fn test_write_report_html() {
        let dir = std::env::temp_dir().join("rvtest_cov_html");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("index.html");

        let result = write_report(CoverageFormat::Html, 50.0, 60.0, 50.0, &path);
        assert!(result.is_ok());
        assert!(path.exists());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_write_report_lcov() {
        let dir = std::env::temp_dir().join("rvtest_cov_lcov");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("lcov.info");

        let result = write_report(CoverageFormat::Lcov, 70.0, 80.0, 70.0, &path);
        assert!(result.is_ok());
        assert!(path.exists());

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_coverage_format_display() {
        assert_eq!(format!("{}", CoverageFormat::Summary), "summary");
        assert_eq!(format!("{}", CoverageFormat::Html), "html");
        assert_eq!(format!("{}", CoverageFormat::Lcov), "lcov");
        assert_eq!(format!("{}", CoverageFormat::Json), "json");
        assert_eq!(format!("{}", CoverageFormat::Cobertura), "cobertura");
    }

    #[test]
    fn test_parse_test_binaries_ignores_wrong_reason() {
        let input = br#"{"reason":"build-script-executed","filenames":[],"target_kind":[]}"#;
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty());
    }

    #[test]
    fn test_parse_test_binaries_doc_test_filtered() {
        // Simulate a doc-test binary (all target kinds are "test", no integration/cargo_rvtest in name)
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/rvtest-abc123"],"target_kind":["test"],"profile":{"test":true}}"#;
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty(), "doc-test only binaries should be filtered");
    }

    #[test]
    fn test_parse_test_binaries_integration_not_filtered() {
        // Integration test binaries have "integration" in the filename
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/integration-abc123"],"target_kind":["test"],"profile":{"test":true}}"#;
        let bins = parse_test_binaries(input);
        // The file doesn't exist, so it returns empty, but it should NOT be filtered as doc-test
        // We verify by checking that it wasn't skipped by the doc-test check
        assert!(bins.is_empty(), "should be empty (file doesn't exist), not filtered as doc-test");
    }

    #[test]
    fn test_parse_test_binaries_no_profile_falls_back_to_target_kind() {
        // When profile is None, it should still be accepted if target_kind has bin or test
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/nonexistent_bin"],"target_kind":["bin"]}"#;
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty(), "file doesn't exist but should pass the test binary check");
    }

    #[test]
    fn test_parse_test_binaries_no_profile_not_bin_or_test() {
        let input = br#"{"reason":"compiler-artifact","filenames":["/tmp/lib.rlib"],"target_kind":["lib"]}"#;
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty(), "lib without test profile should be filtered");
    }

    #[test]
    fn test_parse_test_binaries_empty_line_skipped() {
        let input = b"\n\n";
        let bins = parse_test_binaries(input);
        assert!(bins.is_empty());
    }

    // --- Real profraw binary tests ---

    /// Build a valid profraw binary in memory.
    /// Returns a Vec<u8> with the given number of data records and counters.
    fn build_profraw(num_data: u64, num_counters: u64, counter_values: &[u64]) -> Vec<u8> {
        let mut data = Vec::new();

        // Header (16 × u64 = 128 bytes)
        data.extend_from_slice(&0xff6c70726f667281u64.to_le_bytes()); // magic
        data.extend_from_slice(&10u64.to_le_bytes());                 // version
        data.extend_from_slice(&0u64.to_le_bytes());                  // binary_ids_size
        data.extend_from_slice(&num_data.to_le_bytes());              // num_data
        data.extend_from_slice(&0u64.to_le_bytes());                  // padding_before_counters
        data.extend_from_slice(&num_counters.to_le_bytes());          // num_counters
        data.extend_from_slice(&0u64.to_le_bytes());                  // padding_after_counters
        data.extend_from_slice(&0u64.to_le_bytes());                  // num_bitmap_bytes
        data.extend_from_slice(&0u64.to_le_bytes());                  // padding_after_bitmap
        data.extend_from_slice(&0u64.to_le_bytes());                  // names_size
        data.extend_from_slice(&0u64.to_le_bytes());                  // counters_delta
        data.extend_from_slice(&0u64.to_le_bytes());                  // bitmap_delta
        data.extend_from_slice(&0u64.to_le_bytes());                  // names_delta
        data.extend_from_slice(&0u64.to_le_bytes());                  // num_vtables
        data.extend_from_slice(&0u64.to_le_bytes());                  // vnames_size
        data.extend_from_slice(&0u64.to_le_bytes());                  // value_kind_last

        // Binary IDs section: 0 bytes

        // Data records: 64 bytes each
        for _ in 0..num_data {
            // Build a ProfileData with num_counters matching the function's counters
            let n_counters = (num_counters / num_data.max(1)) as u32;
            data.extend_from_slice(&0u64.to_le_bytes());  // name_ref
            data.extend_from_slice(&0u64.to_le_bytes());  // func_hash
            data.extend_from_slice(&0u64.to_le_bytes());  // counter_ptr
            data.extend_from_slice(&0u64.to_le_bytes());  // bitmap_ptr
            data.extend_from_slice(&0u64.to_le_bytes());  // function_ptr
            data.extend_from_slice(&0u64.to_le_bytes());  // values_ptr
            data.extend_from_slice(&n_counters.to_le_bytes());  // num_counters (u32)
            data.extend_from_slice(&0u16.to_le_bytes());  // num_value_sites[0]
            data.extend_from_slice(&0u16.to_le_bytes());  // num_value_sites[1]
            data.extend_from_slice(&0u16.to_le_bytes());  // num_value_sites[2]
            data.extend_from_slice(&0u16.to_le_bytes());  // padding
            data.extend_from_slice(&0u32.to_le_bytes());  // num_bitmap_bytes
        }

        // Counters
        for val in counter_values {
            data.extend_from_slice(&val.to_le_bytes());
        }

        data
    }

    #[test]
    fn test_parse_raw_profile_version_error() {
        let mut data = build_profraw(0, 0, &[]);
        data[8..16].copy_from_slice(&99u64.to_le_bytes());
        let result = parse_raw_profile(&data);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("version"), "error should mention version, got: {e}");
        }
    }

    #[test]
    fn test_parse_raw_profile_data_overflow() {
        // Header says num_data=5 but we only provide space for 2
        let counters: [u64; 0] = [];
        let mut data = build_profraw(5, 0, &counters);
        // Truncate to header + 0 records (should have 5 × 64 = 320 bytes of data)
        data.truncate(128);
        let result = parse_raw_profile(&data);
        assert!(result.is_err());
        if let Err(e) = result {
            assert!(e.contains("data records"), "error should mention data records, got: {e}");
        }
    }

    #[test]
    fn test_parse_raw_profile_counters_overflow() {
        // Header says num_counters=100 but we only have a few
        let counters: [u64; 2] = [1, 2];
        let mut data = build_profraw(1, 100, &counters);
        // Data record claims 3 counters, but num_counters=100 means we need 800 bytes
        // Truncate to just after data records
        data.truncate(128 + 64); // header + 1 data record
        let result = parse_raw_profile(&data);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_raw_profile_with_one_function() {
        // 1 function, 3 counters: [0, 5, 10]
        let counters = [0u64, 5, 10];
        let data = build_profraw(1, 3, &counters);

        let result = parse_raw_profile(&data);
        assert!(result.is_ok(), "should parse valid profraw: {:?}", result.err());
        let profile = result.unwrap();
        assert_eq!(profile.num_data, 1);
        assert_eq!(profile.num_counters, 3);
        assert_eq!(profile.functions.len(), 1);
        assert_eq!(profile.functions[0].num_counters, 3);
        assert_eq!(profile.functions[0].counters, vec![0, 5, 10]);
        assert_eq!(profile.functions[0].covered, 2);
    }

    #[test]
    fn test_parse_raw_profile_with_two_functions() {
        // 2 functions, 6 counters total (3 each)
        let counters = [1u64, 2, 3, 0, 0, 5];
        let data = build_profraw(2, 6, &counters);

        let result = parse_raw_profile(&data);
        assert!(result.is_ok(), "should parse multi-function profraw: {:?}", result.err());
        let profile = result.unwrap();
        assert_eq!(profile.functions.len(), 2);
        assert_eq!(profile.functions[0].counters, vec![1, 2, 3]);
        assert_eq!(profile.functions[0].covered, 3);
        assert_eq!(profile.functions[1].counters, vec![0, 0, 5]);
        assert_eq!(profile.functions[1].covered, 1);
    }

    #[test]
    fn test_compute_coverage_from_profraw() {
        let counters = [0u64, 10, 20, 0, 0];
        let data = build_profraw(1, 5, &counters);

        // Write to temp file and compute
        let dir = std::env::temp_dir().join("rvtest_cov_compute");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("test.profraw");
        std::fs::write(&path, &data).unwrap();

        let result = compute_coverage_from_profraw(&path);
        assert!(result.is_ok(), "should compute coverage: {:?}", result.err());
        let totals = result.unwrap();
        // 5 counters, 2 non-zero: 2/5 = 40%
        assert!((totals.line_pct() - 40.0).abs() < 0.01);
        // 1 function with >0 covered
        assert!((totals.func_pct() - 100.0).abs() < 0.01);

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_compute_coverage_from_profraw_not_found() {
        let path = std::env::temp_dir().join("nonexistent_xyz123.profraw");
        let result = compute_coverage_from_profraw(&path);
        assert!(result.is_err());
    }

    #[test]
    fn test_coverage_totals_region_pct() {
        let t = CoverageTotals { total_counters: 100, covered_counters: 50, total_functions: 10, covered_functions: 5 };
        assert_eq!(t.region_pct(), t.line_pct());
    }

    #[test]
    fn test_write_report_cobertura() {
        let dir = std::env::temp_dir().join("rvtest_cov_cobertura");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("cobertura.xml");

        let result = write_report(CoverageFormat::Cobertura, 60.0, 70.0, 60.0, &path);
        assert!(result.is_ok());
        assert!(path.exists());

        let _ = std::fs::remove_dir_all(&dir);
    }
}