cargo-coverage-gate 0.5.0

A cargo subcommand that gates pull requests on per-package line coverage measured by cargo-llvm-cov
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! End-to-end verdict computation.
//!
//! Ties together [`attribute`], [`aggregate`], and [`threshold`] to
//! produce a [`Report`] — one [`PackageOutcome`] per gated package, each
//! classified as [`Status::Ok`], [`Status::Fail`], or
//! [`Status::NoData`] — and a derived [`Verdict`] usable as a process
//! exit code.
//!
//! [`attribute`]: crate::attribute
//! [`aggregate`]: crate::aggregate
//! [`threshold`]: crate::threshold

use std::collections::HashSet;
use std::path::PathBuf;

use crate::Verdict;
use crate::aggregate::{LineTotals, aggregate};
use crate::attribute::{AttributionOutcome, attribute};
use crate::error::{CoverageGateError, UnknownPackageSelectorError};
use crate::lcov_cov::{CoverageReport, FileReport};
use crate::threshold::{Threshold, ThresholdSource};
use crate::workspace::{Member, Workspace};

/// Status of a single package against its threshold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Status {
    /// Measured percentage met or exceeded the threshold.
    Ok,
    /// Measured percentage fell below the threshold.
    Fail,
    /// No coverage data was attributed to the package. This is treated
    /// as a configuration error: a package that we asked to gate must
    /// have some test binary contributing data.
    NoData,
    /// The package declared `expect-no-coverable-lines = true` and indeed
    /// had no coverable lines. A passing outcome.
    NoCoverableLines,
    /// The package declared `expect-no-coverable-lines = true` but
    /// coverable lines were found. Treated as a gate failure (a
    /// regression): either the new code should be tested under a real
    /// `min-lines-percent` floor, or it should not be there.
    UnexpectedCoverableLines,
}

/// One row of the verdict report.
#[derive(Debug, Clone)]
pub(crate) struct PackageOutcome {
    /// Cargo package name.
    pub(crate) name: String,
    /// Resolved threshold and the layer it came from.
    pub(crate) threshold: Threshold,
    /// Aggregated line counters; may be all-zero when status is `NoData`.
    pub(crate) totals: LineTotals,
    /// Outcome of the comparison.
    pub(crate) status: Status,
    /// Source locations relevant to a failing outcome.
    pub(crate) diagnostics: Vec<LineDiagnostic>,
}

impl PackageOutcome {
    /// Measured line-coverage percentage for this package, or `None`
    /// when no coverage data was attributed (status `NoData`).
    pub(crate) fn percent(&self) -> Option<f64> {
        self.totals.percent()
    }
}

/// Relevant source lines from one file in a failing package.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct LineDiagnostic {
    /// Path relative to the package manifest directory when possible.
    pub(crate) path: PathBuf,
    /// Uncovered lines for a numeric failure, or all coverable lines for
    /// an `expect-no-coverable-lines` failure.
    pub(crate) lines: Vec<u32>,
}

/// Full verdict report — one row per gated package.
#[derive(Debug, Clone)]
pub(crate) struct Report {
    /// One outcome per gated package, in alphabetical order by name.
    pub(crate) outcomes: Vec<PackageOutcome>,
    /// Number of source files in the lcov tracefile whose paths did
    /// not match any workspace member. Surfaced as a single aggregated
    /// warning rather than per-file noise.
    pub(crate) unattributed: usize,
}

impl Report {
    /// Roll the per-package outcomes up into an overall [`Verdict`].
    ///
    /// `NoData` dominates `Fail` dominates `Ok`: any `NoData` produces
    /// [`Verdict::ConfigError`]; otherwise any `Fail` or
    /// `UnexpectedCoverableLines` produces [`Verdict::Fail`]; otherwise
    /// [`Verdict::Pass`]. `NoCoverableLines` is a passing outcome.
    pub(crate) fn verdict(&self) -> Verdict {
        let mut has_fail = false;
        for o in &self.outcomes {
            match o.status {
                Status::NoData => return Verdict::ConfigError,
                Status::Fail | Status::UnexpectedCoverableLines => has_fail = true,
                Status::Ok | Status::NoCoverableLines => {}
            }
        }
        if has_fail { Verdict::Fail } else { Verdict::Pass }
    }
}

/// Evaluate a parsed coverage report against the resolved workspace.
///
/// `gated_packages` is the result of applying `--package` to the
/// workspace's member list: when empty, every member is gated. Each
/// entry is a cargo-style package selector — a literal name or a Unix
/// glob pattern (`*` and `?`). A literal that matches no workspace
/// member, or a glob that matches none, produces a [`CoverageGateError`].
pub(crate) fn evaluate(report: &CoverageReport, workspace: &Workspace, gated_packages: &[String]) -> Result<Report, CoverageGateError> {
    let gated = resolve_gated(workspace, gated_packages)?;

    let AttributionOutcome { by_member, unattributed } = attribute(&report.files, &workspace.members);

    let mut outcomes: Vec<PackageOutcome> = gated
        .iter()
        .map(|m| {
            let attrib = by_member.get(m.name.as_str()).map_or(&[][..], Vec::as_slice);
            let totals = aggregate(attrib);
            // A package that asserts it has no coverable lines is gated by
            // that assertion, not by a numeric floor: the resolved
            // threshold value is unused for display (the renderer
            // special-cases the status), but the `package` source label is
            // accurate because the assertion is always package-scoped.
            let (threshold, status) = if m.expect_no_coverable_lines {
                let threshold = Threshold {
                    min_lines_percent: 0.0,
                    source: ThresholdSource::Package,
                };
                (threshold, classify_no_coverable_lines(totals))
            } else {
                let threshold = Threshold::resolve(m, workspace);
                let status = classify(totals, threshold);
                (threshold, status)
            };
            let diagnostics = diagnostics(attrib, m, status);
            PackageOutcome {
                name: m.name.clone(),
                threshold,
                totals,
                status,
                diagnostics,
            }
        })
        .collect();
    outcomes.sort_by(|a, b| a.name.cmp(&b.name));

    Ok(Report {
        outcomes,
        unattributed: unattributed.len(),
    })
}

fn diagnostics(files: &[&FileReport], member: &Member, status: Status) -> Vec<LineDiagnostic> {
    let mut diagnostics: Vec<LineDiagnostic> = files
        .iter()
        .filter_map(|file| {
            let lines = match status {
                Status::Fail => &file.uncovered_lines,
                Status::UnexpectedCoverableLines => &file.coverable_lines,
                Status::Ok | Status::NoData | Status::NoCoverableLines => return None,
            };
            if lines.is_empty() {
                return None;
            }
            Some(LineDiagnostic {
                path: file
                    .filename
                    .strip_prefix(&member.manifest_dir)
                    .unwrap_or(&file.filename)
                    .to_path_buf(),
                lines: lines.clone(),
            })
        })
        .collect();
    diagnostics.sort_by(|a, b| a.path.cmp(&b.path));
    diagnostics
}

/// Resolve `packages` (each a cargo-style selector) against the
/// workspace.
///
/// An empty `packages` list selects every member. Otherwise each
/// selector is matched against member names: bare identifiers require
/// exact match, while selectors containing `*` or `?` are matched as
/// Unix shell globs (mirroring `cargo build -p 'tokio-*'`). A selector
/// that matches no member is a configuration error. Members matched by
/// multiple selectors appear only once.
pub(crate) fn resolve_gated<'w>(workspace: &'w Workspace, packages: &[String]) -> Result<Vec<&'w Member>, CoverageGateError> {
    if packages.is_empty() {
        return Ok(workspace.members.iter().collect());
    }
    let mut seen: HashSet<&str> = HashSet::new();
    let mut out = Vec::with_capacity(packages.len());
    for spec in packages {
        let matches: Vec<&Member> = workspace.members.iter().filter(|m| glob_matches(spec, &m.name)).collect();
        if matches.is_empty() {
            return Err(UnknownPackageSelectorError::new(spec.clone()).into());
        }
        for m in matches {
            if seen.insert(m.name.as_str()) {
                out.push(m);
            }
        }
    }
    Ok(out)
}

/// Tiny Unix-style glob matcher: `*` matches any run of characters
/// (including empty), `?` matches exactly one character. Everything
/// else matches literally. No character classes, no escapes — package
/// names are simple identifiers, so this is sufficient.
fn glob_matches(pattern: &str, name: &str) -> bool {
    let p: Vec<char> = pattern.chars().collect();
    let n: Vec<char> = name.chars().collect();
    glob_inner(&p, 0, &n, 0)
}

// `pi += 1` and `pi + N` arithmetic on the position counters has
// cargo-mutants mutations (`*=`, `*`) that would keep the counter from
// advancing — producing non-terminating mutants whenever a pattern
// contains `*`. The classifying tests in `glob_matcher_handles_wildcards`
// catch every behavioral mutation; the only mutations the suite cannot
// kill in finite time are these arithmetic ones. Skip mutating the body
// rather than padding the suite with unrelated timeout-guard tests.
#[mutants::skip]
fn glob_inner(p: &[char], mut pi: usize, n: &[char], mut ni: usize) -> bool {
    while pi < p.len() {
        match p[pi] {
            '*' => {
                // Collapse runs of `*` and try every possible match
                // length for the next literal segment.
                while pi < p.len() && p[pi] == '*' {
                    pi += 1;
                }
                if pi == p.len() {
                    return true;
                }
                for k in ni..=n.len() {
                    if glob_inner(p, pi, n, k) {
                        return true;
                    }
                }
                return false;
            }
            '?' => {
                if ni >= n.len() {
                    return false;
                }
                pi += 1;
                ni += 1;
            }
            c => {
                if ni >= n.len() || n[ni] != c {
                    return false;
                }
                pi += 1;
                ni += 1;
            }
        }
    }
    ni == n.len()
}

/// Compare `totals` against `threshold` and classify the outcome.
fn classify(totals: LineTotals, threshold: Threshold) -> Status {
    // A zero threshold is the explicit opt-out documented in the
    // design: the crate passes regardless of how much (or whether
    // any) coverage data was attributed to it. The schema rejects
    // negative values, so this is effectively an exact-zero check;
    // expressing it as `<= 0.0` keeps the predicate robust against
    // any future plumbing that might surface a `-0.0`.
    if threshold.min_lines_percent <= 0.0 {
        return Status::Ok;
    }
    let Some(pct) = totals.percent() else {
        return Status::NoData;
    };
    // Display rounding must not weaken the configured floor. In particular,
    // 100% requires every coverable line to be covered.
    if pct >= threshold.min_lines_percent {
        Status::Ok
    } else {
        Status::Fail
    }
}

/// Classify a package that declared `expect-no-coverable-lines = true`.
///
/// The assertion holds when no coverable lines were attributed (which
/// includes the "no attributed files at all" case, since that yields a
/// zero line count). Any coverable lines mean the assertion is now false
/// — the package grew testable code — so it fails as a regression.
fn classify_no_coverable_lines(totals: LineTotals) -> Status {
    if totals.count == 0 {
        Status::NoCoverableLines
    } else {
        Status::UnexpectedCoverableLines
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::*;

    fn make_file(path: &str, count: u32, covered: u32) -> FileReport {
        FileReport {
            filename: PathBuf::from(path),
            lines_total: count,
            lines_covered: covered,
            coverable_lines: (1..=count).collect(),
            uncovered_lines: ((covered + 1)..=count).collect(),
        }
    }

    fn make_member(name: &str, manifest_dir: &str, min_lines_percent: Option<f64>) -> Member {
        Member {
            name: name.to_owned(),
            manifest_dir: PathBuf::from(manifest_dir),
            min_lines_percent,
            expect_no_coverable_lines: false,
        }
    }

    fn make_member_expect_empty(name: &str, manifest_dir: &str) -> Member {
        Member {
            name: name.to_owned(),
            manifest_dir: PathBuf::from(manifest_dir),
            min_lines_percent: None,
            expect_no_coverable_lines: true,
        }
    }

    fn make_report(files: Vec<FileReport>) -> CoverageReport {
        CoverageReport { files }
    }

    fn make_workspace(members: Vec<Member>, default: Option<f64>) -> Workspace {
        Workspace {
            members,
            default_min_lines_percent: default,
        }
    }

    #[test]
    fn all_pass() {
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 100, 95),
            make_file("/repo/crates/beta/src/lib.rs", 50, 50),
        ]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(90.0)),
                make_member("beta", "/repo/crates/beta", Some(80.0)),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Pass);
        assert!(r.outcomes.iter().all(|o| o.status == Status::Ok));
    }

    #[test]
    fn one_failure_produces_fail_verdict() {
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 100, 95),
            make_file("/repo/crates/beta/src/lib.rs", 100, 60),
        ]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(90.0)),
                make_member("beta", "/repo/crates/beta", Some(80.0)),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Fail);
        let beta = r.outcomes.iter().find(|o| o.name == "beta").unwrap();
        assert_eq!(beta.status, Status::Fail);
        assert!((beta.percent().unwrap() - 60.0).abs() < f64::EPSILON);
        assert_eq!(beta.diagnostics[0].path, PathBuf::from("src/lib.rs"));
        assert_eq!(beta.diagnostics[0].lines, (61..=100).collect::<Vec<_>>());
    }

    #[test]
    fn unexpected_coverable_lines_report_every_instrumented_location() {
        let report = make_report(vec![make_file("/repo/crates/alpha/src/lib.rs", 4, 2)]);
        let ws = make_workspace(vec![make_member_expect_empty("alpha", "/repo/crates/alpha")], None);
        let evaluated = evaluate(&report, &ws, &[]).expect("evaluate");
        let alpha = &evaluated.outcomes[0];
        assert_eq!(alpha.status, Status::UnexpectedCoverableLines);
        assert_eq!(alpha.diagnostics[0].path, PathBuf::from("src/lib.rs"));
        assert_eq!(alpha.diagnostics[0].lines, vec![1, 2, 3, 4]);
    }

    #[test]
    fn diagnostics_omit_files_without_relevant_lines() {
        let file = make_file("/repo/crates/alpha/src/lib.rs", 0, 0);
        let member = make_member("alpha", "/repo/crates/alpha", Some(80.0));
        assert!(diagnostics(&[&file], &member, Status::Fail).is_empty());
    }

    #[test]
    fn no_data_dominates_fail() {
        let report = make_report(vec![make_file("/repo/crates/alpha/src/lib.rs", 100, 60)]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(80.0)),
                // `beta` is gated but has no data attributed.
                make_member("beta", "/repo/crates/beta", Some(80.0)),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::ConfigError);
        let beta = r.outcomes.iter().find(|o| o.name == "beta").unwrap();
        assert_eq!(beta.status, Status::NoData);
    }

    #[test]
    fn package_flag_restricts_scope() {
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 100, 95),
            make_file("/repo/crates/beta/src/lib.rs", 100, 50),
        ]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(90.0)),
                make_member("beta", "/repo/crates/beta", Some(80.0)),
            ],
            None,
        );
        // Only gate alpha; beta would have failed but is out of scope.
        let r = evaluate(&report, &ws, &["alpha".to_owned()]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Pass);
        assert_eq!(r.outcomes.len(), 1);
        assert_eq!(r.outcomes[0].name, "alpha");
    }

    #[test]
    fn package_flag_with_unknown_name_errors() {
        let ws = make_workspace(vec![make_member("alpha", "/repo/crates/alpha", None)], None);
        let report = make_report(Vec::new());
        let err = evaluate(&report, &ws, &["typo".to_owned()]).expect_err("unknown package must error");
        let rendered = err.to_string();
        assert!(rendered.contains("typo"));
        assert!(rendered.contains("--package"));
    }

    #[test]
    fn glob_selector_matches_multiple_members() {
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", None),
                make_member("alpha_macros", "/repo/crates/alpha_macros", None),
                make_member("beta", "/repo/crates/beta", None),
            ],
            None,
        );
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 10, 10),
            make_file("/repo/crates/alpha_macros/src/lib.rs", 10, 10),
        ]);
        let r = evaluate(&report, &ws, &["alpha*".to_owned()]).expect("evaluate");
        let names: Vec<_> = r.outcomes.iter().map(|o| o.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "alpha_macros"]);
    }

    #[test]
    fn glob_matching_no_member_errors() {
        let ws = make_workspace(vec![make_member("alpha", "/repo/crates/alpha", None)], None);
        let report = make_report(Vec::new());
        let err = evaluate(&report, &ws, &["beta*".to_owned()]).expect_err("no match must error");
        assert!(err.to_string().contains("beta*"));
    }

    #[test]
    fn overlapping_selectors_dedupe_members() {
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", None),
                make_member("alpha_macros", "/repo/crates/alpha_macros", None),
            ],
            None,
        );
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 10, 10),
            make_file("/repo/crates/alpha_macros/src/lib.rs", 10, 10),
        ]);
        let r = evaluate(&report, &ws, &["alpha".to_owned(), "alpha*".to_owned()]).expect("evaluate");
        let names: Vec<_> = r.outcomes.iter().map(|o| o.name.as_str()).collect();
        assert_eq!(names, vec!["alpha", "alpha_macros"]);
    }

    #[test]
    fn glob_matcher_handles_wildcards() {
        assert!(super::glob_matches("alpha*", "alpha"));
        assert!(super::glob_matches("alpha*", "alpha_macros"));
        assert!(super::glob_matches("*macros", "alpha_macros"));
        assert!(super::glob_matches("*alpha*", "my_alpha_lib"));
        assert!(super::glob_matches("a?pha", "alpha"));
        assert!(!super::glob_matches("alpha", "alphax"));
        assert!(!super::glob_matches("alpha*", "beta"));
        assert!(!super::glob_matches("a?pha", "axxpha"));
        // Multiple consecutive `*` collapse.
        assert!(super::glob_matches("a**b", "ab"));
        assert!(super::glob_matches("a**b", "axyzb"));
        // Pattern with literal chars after `*` that the name doesn't satisfy.
        // Guards the `pi == p.len()` shortcut in glob_inner from being short-circuited.
        assert!(!super::glob_matches("a*b", "ac"));
        assert!(!super::glob_matches("a*b", "axyz"));
        // `?` requires exactly one remaining name char: a trailing `?`
        // with the name exhausted must not match (guards the
        // `ni >= n.len()` early-return in the `?` arm).
        assert!(!super::glob_matches("a?", "a"));
        assert!(!super::glob_matches("alpha?", "alpha"));
    }

    #[test]
    fn unattributed_files_are_counted_and_dropped() {
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 100, 80),
            make_file("/elsewhere/build-script.rs", 50, 0),
        ]);
        let ws = make_workspace(vec![make_member("alpha", "/repo/crates/alpha", Some(70.0))], None);
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.unattributed, 1);
        let alpha = &r.outcomes[0];
        assert_eq!(alpha.totals.count, 100);
        assert_eq!(alpha.status, Status::Ok);
    }

    #[test]
    fn threshold_source_propagated_through_outcome() {
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(50.0)),
                make_member("beta", "/repo/crates/beta", None),
                make_member("gamma", "/repo/crates/gamma", None),
            ],
            Some(80.0),
        );
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 10, 10),
            make_file("/repo/crates/beta/src/lib.rs", 10, 10),
            make_file("/repo/crates/gamma/src/lib.rs", 10, 10),
        ]);
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        let by_name: std::collections::HashMap<_, _> = r.outcomes.iter().map(|o| (o.name.as_str(), o)).collect();
        assert_eq!(by_name["alpha"].threshold.source, ThresholdSource::Package);
        assert_eq!(by_name["beta"].threshold.source, ThresholdSource::Workspace);
        // gamma also inherits from workspace, not default, because the
        // workspace default is set.
        assert_eq!(by_name["gamma"].threshold.source, ThresholdSource::Workspace);
    }

    #[test]
    fn exact_threshold_match_passes() {
        let totals = LineTotals { count: 100, covered: 82 };
        let threshold = Threshold {
            min_lines_percent: 82.0,
            source: ThresholdSource::Default,
        };
        assert_eq!(classify(totals, threshold), Status::Ok);
    }

    #[test]
    fn displayed_rounding_does_not_raise_measured_coverage() {
        // 81.95% renders as "82.0%", but presentation rounding must not make
        // it satisfy an 82.0 threshold.
        let totals = LineTotals {
            count: 10_000,
            covered: 8_195,
        };
        let threshold = Threshold {
            min_lines_percent: 82.0,
            source: ThresholdSource::Default,
        };
        assert_eq!(classify(totals, threshold), Status::Fail);
    }

    #[test]
    fn full_coverage_threshold_requires_every_line() {
        let totals = LineTotals {
            count: 2_000,
            covered: 1_999,
        };
        let threshold = Threshold {
            min_lines_percent: 100.0,
            source: ThresholdSource::Default,
        };
        assert_eq!(classify(totals, threshold), Status::Fail);
    }

    #[test]
    fn displayed_rounding_does_not_lower_threshold() {
        // Both values render as "82.0%", but the configured 82.04 floor is
        // still greater than the measured 82.0%.
        let totals = LineTotals { count: 100, covered: 82 };
        let threshold = Threshold {
            min_lines_percent: 82.04,
            source: ThresholdSource::Default,
        };
        assert_eq!(classify(totals, threshold), Status::Fail);
    }

    #[test]
    fn zero_threshold_opts_out_even_with_no_data() {
        // `min-lines-percent = 0.0` is the documented opt-out; a package with no
        // attributed coverage data must still pass rather than be
        // flagged as a configuration error.
        let totals = LineTotals { count: 0, covered: 0 };
        let threshold = Threshold {
            min_lines_percent: 0.0,
            source: ThresholdSource::Package,
        };
        assert_eq!(classify(totals, threshold), Status::Ok);
    }

    #[test]
    fn zero_threshold_opts_out_even_when_well_covered() {
        let totals = LineTotals { count: 100, covered: 100 };
        let threshold = Threshold {
            min_lines_percent: 0.0,
            source: ThresholdSource::Package,
        };
        assert_eq!(classify(totals, threshold), Status::Ok);
    }

    #[test]
    fn tiny_non_zero_threshold_is_not_treated_as_opt_out() {
        // Only an exact zero threshold opts a package out. A tiny but
        // non-zero configured threshold must still gate: a package with
        // no attributed coverage data is reported as NoData, not silently
        // passed.
        let totals = LineTotals { count: 0, covered: 0 };
        let threshold = Threshold {
            min_lines_percent: 1e-9,
            source: ThresholdSource::Package,
        };
        assert_eq!(classify(totals, threshold), Status::NoData);
    }

    #[test]
    fn classify_no_coverable_lines_passes_when_empty() {
        // The genuinely-empty crate: no attributed files (or files with
        // zero coverable lines) satisfies the assertion.
        assert_eq!(
            classify_no_coverable_lines(LineTotals { count: 0, covered: 0 }),
            Status::NoCoverableLines
        );
    }

    #[test]
    fn classify_no_coverable_lines_fails_when_lines_appear() {
        // Any coverable line — even a fully-covered one — violates the
        // "no coverable lines" assertion.
        assert_eq!(
            classify_no_coverable_lines(LineTotals { count: 1, covered: 1 }),
            Status::UnexpectedCoverableLines
        );
        assert_eq!(
            classify_no_coverable_lines(LineTotals { count: 10, covered: 0 }),
            Status::UnexpectedCoverableLines
        );
    }

    #[test]
    fn expect_no_coverable_lines_crate_with_no_data_passes() {
        // End-to-end: a crate declaring no coverable lines, with no
        // attributed data, passes — and does not trip the NoData config
        // error that a normal gated crate would.
        let report = make_report(vec![make_file("/repo/crates/alpha/src/lib.rs", 100, 95)]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(80.0)),
                make_member_expect_empty("beta", "/repo/crates/beta"),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Pass);
        let beta = r.outcomes.iter().find(|o| o.name == "beta").unwrap();
        assert_eq!(beta.status, Status::NoCoverableLines);
        assert_eq!(beta.threshold.source, ThresholdSource::Package);
        // The assertion path stores a fixed, never-displayed sentinel
        // threshold; pin it so a mutated literal is caught.
        assert!((beta.threshold.min_lines_percent - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn expect_no_coverable_lines_crate_with_lines_fails() {
        // A crate that declared no coverable lines but actually has some
        // fails the gate (exit 1), not a config error.
        let report = make_report(vec![
            make_file("/repo/crates/alpha/src/lib.rs", 100, 95),
            make_file("/repo/crates/beta/src/lib.rs", 5, 0),
        ]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(80.0)),
                make_member_expect_empty("beta", "/repo/crates/beta"),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Fail);
        let beta = r.outcomes.iter().find(|o| o.name == "beta").unwrap();
        assert_eq!(beta.status, Status::UnexpectedCoverableLines);
    }

    #[test]
    fn no_data_dominates_unexpected_coverable_lines() {
        // NoData (config error, exit 2) must dominate a gate failure.
        let report = make_report(vec![make_file("/repo/crates/beta/src/lib.rs", 5, 0)]);
        let ws = make_workspace(
            vec![
                // alpha is gated with a normal floor but has no data.
                make_member("alpha", "/repo/crates/alpha", Some(80.0)),
                // beta declared empty but has lines -> UnexpectedCoverableLines.
                make_member_expect_empty("beta", "/repo/crates/beta"),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::ConfigError);
    }

    #[test]
    fn opt_out_crate_does_not_force_config_error_verdict() {
        // End-to-end: an opt-out crate with no attributed coverage data
        // must not push the overall verdict to ConfigError.
        let report = make_report(vec![make_file("/repo/crates/alpha/src/lib.rs", 100, 95)]);
        let ws = make_workspace(
            vec![
                make_member("alpha", "/repo/crates/alpha", Some(80.0)),
                // `beta` is opted out and has no attributed data.
                make_member("beta", "/repo/crates/beta", Some(0.0)),
            ],
            None,
        );
        let r = evaluate(&report, &ws, &[]).expect("evaluate");
        assert_eq!(r.verdict(), Verdict::Pass);
        let beta = r.outcomes.iter().find(|o| o.name == "beta").unwrap();
        assert_eq!(beta.status, Status::Ok);
    }
}