1use std::path::Path;
41
42use fallow_output::{
43 AuditFindingAttribution, AuditGateExemption, CoverageSource, DEFAULT_COGNITIVE_CRITICAL,
44 DEFAULT_COGNITIVE_HIGH, DEFAULT_CYCLOMATIC_CRITICAL, DEFAULT_CYCLOMATIC_HIGH,
45 ExceededThreshold, FindingSeverity, WorsenedMetric, WorsenedMetricKind,
46 compute_finding_severity,
47};
48use fallow_types::output_dead_code::EffectiveSeverity;
49use rustc_hash::{FxHashMap, FxHashSet};
50
51use crate::audit_keys::{health_finding_key, remap_key_for_renames};
52
53#[derive(Debug, Clone, Copy, PartialEq)]
55pub struct ComplexityMetrics {
56 pub line: u32,
58 pub cyclomatic: u16,
60 pub cognitive: u16,
62 pub crap: Option<f64>,
64 pub line_count: u32,
66 pub exceeded: ExceededThreshold,
68 pub severity: FindingSeverity,
70 pub crap_estimated: bool,
72}
73
74impl ComplexityMetrics {
75 #[must_use]
77 pub const fn of(finding: &fallow_output::ComplexityViolation) -> Self {
78 Self {
79 line: finding.line,
80 cyclomatic: finding.cyclomatic,
81 cognitive: finding.cognitive,
82 crap: finding.crap,
83 line_count: finding.line_count,
84 exceeded: finding.exceeded,
85 severity: finding.severity,
86 crap_estimated: crap_is_estimated(finding),
87 }
88 }
89
90 const fn base_metrics(&self) -> fallow_output::AuditBaseMetrics {
93 fallow_output::AuditBaseMetrics {
94 cyclomatic: self.cyclomatic,
95 cognitive: self.cognitive,
96 crap: self.crap,
97 line_count: self.line_count,
98 }
99 }
100
101 fn same_values(&self, other: &Self) -> bool {
104 self.cyclomatic == other.cyclomatic
105 && self.cognitive == other.cognitive
106 && self.crap.map(f64::to_bits) == other.crap.map(f64::to_bits)
107 }
108
109 fn same_values_and_lines(&self, other: &Self) -> bool {
112 self.same_values(other) && self.line_count == other.line_count
113 }
114
115 const fn same_structure(&self, other: &Self) -> bool {
119 self.cyclomatic == other.cyclomatic && self.cognitive == other.cognitive
120 }
121
122 const fn same_structure_and_lines(&self, other: &Self) -> bool {
125 self.same_structure(other) && self.line_count == other.line_count
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Default)]
131pub struct ComplexityClass {
132 pub introduced: bool,
135 pub worsened_metrics: Vec<WorsenedMetric>,
138 pub exceeded_metric_grew: bool,
142 pub base: Option<fallow_output::AuditBaseMetrics>,
145}
146
147impl ComplexityClass {
148 #[must_use]
151 pub fn is_worsened(&self) -> bool {
152 !self.introduced && !self.worsened_metrics.is_empty()
153 }
154
155 #[must_use]
157 pub fn attribution(&self) -> AuditFindingAttribution {
158 if self.introduced {
159 AuditFindingAttribution::Introduced
160 } else if self.worsened_metrics.is_empty() {
161 AuditFindingAttribution::Inherited
162 } else {
163 AuditFindingAttribution::Worsened
164 }
165 }
166
167 pub fn clear_worsened_for_off(&mut self) {
172 if !self.introduced && !self.exceeded_metric_grew {
173 self.worsened_metrics.clear();
174 }
175 }
176
177 fn of_match(
178 head: &fallow_output::ComplexityViolation,
179 base: Option<&ComplexityMetrics>,
180 ) -> Self {
181 base.map_or(
182 Self {
183 introduced: true,
184 worsened_metrics: Vec::new(),
185 exceeded_metric_grew: false,
186 base: None,
187 },
188 |base| {
189 let exceeded_metric_grew = exceeded_metric_increased(head, base);
190 Self {
191 introduced: newly_exceeded_metric_grew(head, base)
192 || (exceeded_metric_grew && severity_tier_rose(head, base)),
193 worsened_metrics: grown_metrics(head, base),
194 exceeded_metric_grew,
195 base: Some(base.base_metrics()),
196 }
197 },
198 )
199 }
200}
201
202fn grown_metrics(
208 head: &fallow_output::ComplexityViolation,
209 base: &ComplexityMetrics,
210) -> Vec<WorsenedMetric> {
211 let mut grown = Vec::new();
212 let mut push = |metric, base: f64, head: f64| {
213 if head > base {
214 grown.push(WorsenedMetric { metric, base, head });
215 }
216 };
217 push(
218 WorsenedMetricKind::Cyclomatic,
219 f64::from(base.cyclomatic),
220 f64::from(head.cyclomatic),
221 );
222 push(
223 WorsenedMetricKind::Cognitive,
224 f64::from(base.cognitive),
225 f64::from(head.cognitive),
226 );
227 if let (Some(base_crap), Some(head_crap)) = (base.crap, head.crap) {
228 push(WorsenedMetricKind::Crap, base_crap, head_crap);
229 }
230 if line_count_grew(base.line_count, head.line_count) {
231 grown.push(WorsenedMetric {
232 metric: WorsenedMetricKind::LineCount,
233 base: f64::from(base.line_count),
234 head: f64::from(head.line_count),
235 });
236 }
237 grown
238}
239
240const LINE_COUNT_MIN_GROWTH_LINES: u32 = 5;
242
243fn line_count_grew(base: u32, head: u32) -> bool {
251 head.saturating_sub(base) >= LINE_COUNT_MIN_GROWTH_LINES
252}
253
254pub type ComplexityBaseline = FxHashMap<String, Vec<ComplexityMetrics>>;
257
258#[must_use]
260pub fn complexity_baseline(
261 report: &fallow_output::HealthReport,
262 root: &Path,
263) -> ComplexityBaseline {
264 let mut baseline = ComplexityBaseline::default();
265 for finding in &report.findings {
266 baseline
267 .entry(health_finding_key(finding, root))
268 .or_default()
269 .push(ComplexityMetrics::of(finding));
270 }
271 sort_by_line(&mut baseline);
272 baseline
273}
274
275#[must_use]
277pub fn complexity_baseline_keys(baseline: &ComplexityBaseline) -> FxHashSet<String> {
278 baseline.keys().cloned().collect()
279}
280
281#[must_use]
287#[expect(
288 clippy::implicit_hasher,
289 reason = "fallow standardizes on FxHashMap across audit attribution keys"
290)]
291pub fn remap_complexity_baseline_for_renames(
292 baseline: ComplexityBaseline,
293 renames: &FxHashMap<String, String>,
294) -> ComplexityBaseline {
295 let mut remapped = ComplexityBaseline::default();
296 for (key, findings) in baseline {
297 remapped
298 .entry(remap_key_for_renames(&key, renames))
299 .or_default()
300 .extend(findings);
301 }
302 sort_by_line(&mut remapped);
303 remapped
304}
305
306fn sort_by_line(baseline: &mut ComplexityBaseline) {
307 for findings in baseline.values_mut() {
308 findings.sort_by_key(|metrics| metrics.line);
309 }
310}
311
312fn exceeded_metric_increased(
317 head: &fallow_output::ComplexityViolation,
318 base: &ComplexityMetrics,
319) -> bool {
320 let exceeded = head.exceeded;
321 (exceeded.includes_cyclomatic() && head.cyclomatic > base.cyclomatic)
322 || (exceeded.includes_cognitive() && head.cognitive > base.cognitive)
323 || (exceeded.includes_crap() && measured_crap_grew(head, base))
324 || (exceeded.is_file_lines() && line_count_grew(base.line_count, head.line_count))
325}
326
327fn newly_exceeded_metric_grew(
331 head: &fallow_output::ComplexityViolation,
332 base: &ComplexityMetrics,
333) -> bool {
334 let (now, before) = (head.exceeded, base.exceeded);
335 (now.includes_cyclomatic()
336 && !before.includes_cyclomatic()
337 && head.cyclomatic > base.cyclomatic)
338 || (now.includes_cognitive()
339 && !before.includes_cognitive()
340 && head.cognitive > base.cognitive)
341 || (now.includes_crap() && !before.includes_crap() && measured_crap_grew(head, base))
342}
343
344fn measured_crap_grew(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
348 crap_is_comparable(head, base)
349 && matches!((head.crap, base.crap), (Some(head), Some(base)) if head > base)
350}
351
352fn crap_is_comparable(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
353 head.crap.is_some() && base.crap.is_some() && !crap_is_estimated(head) && !base.crap_estimated
354}
355
356fn severity_tier_rose(head: &fallow_output::ComplexityViolation, base: &ComplexityMetrics) -> bool {
362 if crap_is_comparable(head, base) {
363 return head.severity > base.severity;
364 }
365 complexity_tier(head.cognitive, head.cyclomatic)
366 > complexity_tier(base.cognitive, base.cyclomatic)
367}
368
369fn complexity_tier(cognitive: u16, cyclomatic: u16) -> FindingSeverity {
370 compute_finding_severity(
371 cognitive,
372 cyclomatic,
373 None,
374 DEFAULT_COGNITIVE_HIGH,
375 DEFAULT_COGNITIVE_CRITICAL,
376 DEFAULT_CYCLOMATIC_HIGH,
377 DEFAULT_CYCLOMATIC_CRITICAL,
378 )
379}
380
381#[must_use]
384pub const fn crap_is_estimated(finding: &fallow_output::ComplexityViolation) -> bool {
385 matches!(
386 finding.coverage_source,
387 Some(CoverageSource::Estimated | CoverageSource::EstimatedComponentInherited)
388 )
389}
390
391#[must_use]
394pub const fn exceeds_only_estimated_crap(finding: &fallow_output::ComplexityViolation) -> bool {
395 matches!(finding.exceeded, ExceededThreshold::Crap) && crap_is_estimated(finding)
396}
397
398pub fn demote_estimated_crap_gates(findings: &mut [fallow_output::HealthFinding]) {
406 for finding in findings {
407 if exceeds_only_estimated_crap(finding)
408 && finding.effective_severity == Some(EffectiveSeverity::Error)
409 {
410 finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
411 }
412 }
413}
414
415pub fn exempt_test_file_gates(findings: &mut [fallow_output::HealthFinding], root: &Path) {
423 for finding in findings {
424 let relative = finding.path.strip_prefix(root).unwrap_or(&finding.path);
425 if fallow_engine::test_paths::is_test_path(root, relative) {
426 finding.violation.effective_severity = Some(EffectiveSeverity::Warn);
427 finding.gate_exemption = Some(AuditGateExemption::TestFile);
428 }
429 }
430}
431
432#[must_use]
435pub fn classify_complexity_findings(
436 findings: &[fallow_output::HealthFinding],
437 root: &Path,
438 base: &ComplexityBaseline,
439) -> Vec<bool> {
440 classify_complexity_attribution(findings, root, base)
441 .into_iter()
442 .map(|class| class.introduced)
443 .collect()
444}
445
446#[must_use]
478pub fn classify_complexity_attribution(
479 findings: &[fallow_output::HealthFinding],
480 root: &Path,
481 base: &ComplexityBaseline,
482) -> Vec<ComplexityClass> {
483 classify_with_moves(findings, root, base, None)
484}
485
486#[must_use]
521pub fn classify_complexity_attribution_with_moves(
522 findings: &[fallow_output::HealthFinding],
523 root: &Path,
524 base: &ComplexityBaseline,
525 changed_paths: &ChangedPaths,
526) -> Vec<ComplexityClass> {
527 classify_with_moves(findings, root, base, Some(changed_paths))
528}
529
530#[derive(Debug, Clone, Default)]
533pub struct ChangedPaths {
534 pub changed: FxHashSet<String>,
536 pub deleted: FxHashSet<String>,
538}
539
540const VALUE_RULES: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 4] = [
542 ComplexityMetrics::same_values_and_lines,
543 ComplexityMetrics::same_values,
544 ComplexityMetrics::same_structure_and_lines,
545 ComplexityMetrics::same_structure,
546];
547
548const PLACEHOLDER_RULES: [fn(&ComplexityMetrics, &ComplexityMetrics) -> bool; 2] = [
551 ComplexityMetrics::same_values_and_lines,
552 ComplexityMetrics::same_structure_and_lines,
553];
554
555fn classify_with_moves(
556 findings: &[fallow_output::HealthFinding],
557 root: &Path,
558 base: &ComplexityBaseline,
559 changed_paths: Option<&ChangedPaths>,
560) -> Vec<ComplexityClass> {
561 let mut groups: FxHashMap<String, Vec<usize>> = FxHashMap::default();
562 for (index, finding) in findings.iter().enumerate() {
563 groups
564 .entry(health_finding_key(finding, root))
565 .or_default()
566 .push(index);
567 }
568 let mut matches: Vec<Option<&ComplexityMetrics>> = vec![None; findings.len()];
569 let mut unused_bases: FxHashMap<&str, Vec<&ComplexityMetrics>> = FxHashMap::default();
570 for (key, mut heads) in groups {
571 let Some((base_key, bases)) = base.get_key_value(&key) else {
572 continue;
573 };
574 heads.sort_by_key(|&index| (findings[index].line, findings[index].col));
575 let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> = bases.iter().map(Some).collect();
576 match_by_rules(
577 findings,
578 &heads,
579 &mut unmatched_bases,
580 &mut matches,
581 &VALUE_RULES,
582 );
583 let mut remaining_bases = unmatched_bases.into_iter().flatten();
584 for &index in &heads {
585 if matches[index].is_none() {
586 matches[index] = remaining_bases.next();
587 }
588 }
589 unused_bases.insert(base_key.as_str(), remaining_bases.collect());
590 }
591 if let Some(changed_paths) = changed_paths {
592 match_moved_functions(findings, base, changed_paths, &unused_bases, &mut matches);
593 }
594 findings
595 .iter()
596 .zip(matches)
597 .map(|(finding, base)| ComplexityClass::of_match(finding, base))
598 .collect()
599}
600
601fn match_by_rules<'a>(
606 findings: &[fallow_output::HealthFinding],
607 heads: &[usize],
608 unmatched_bases: &mut [Option<&'a ComplexityMetrics>],
609 matches: &mut [Option<&'a ComplexityMetrics>],
610 rules: &[fn(&ComplexityMetrics, &ComplexityMetrics) -> bool],
611) {
612 for rule in rules {
613 for &index in heads {
614 if matches[index].is_some() {
615 continue;
616 }
617 let head = ComplexityMetrics::of(&findings[index]);
618 if let Some(slot) = unmatched_bases
619 .iter_mut()
620 .find(|slot| slot.is_some_and(|base| rule(base, &head)))
621 {
622 matches[index] = slot.take();
623 }
624 }
625 }
626}
627
628fn match_moved_functions<'a>(
636 findings: &[fallow_output::HealthFinding],
637 base: &'a ComplexityBaseline,
638 changed_paths: &ChangedPaths,
639 unused_bases: &FxHashMap<&str, Vec<&'a ComplexityMetrics>>,
640 matches: &mut [Option<&'a ComplexityMetrics>],
641) {
642 let mut heads_by_name: FxHashMap<&str, Vec<usize>> = FxHashMap::default();
643 for (index, finding) in findings.iter().enumerate() {
644 if matches[index].is_none() {
645 heads_by_name
646 .entry(finding.name.as_str())
647 .or_default()
648 .push(index);
649 }
650 }
651 if heads_by_name.is_empty() {
652 return;
653 }
654 let mut bases_by_name: FxHashMap<&str, Vec<(&str, &ComplexityMetrics)>> = FxHashMap::default();
655 for (key, bases) in base {
656 let Some((path, name)) = changed_path_and_name(key, &changed_paths.changed) else {
657 continue;
658 };
659 if !heads_by_name.contains_key(name) {
660 continue;
661 }
662 let candidates = bases_by_name.entry(name).or_default();
663 match unused_bases.get(key.as_str()) {
664 Some(unused) => candidates.extend(unused.iter().map(|metrics| (path, *metrics))),
665 None => candidates.extend(bases.iter().map(|metrics| (path, metrics))),
666 }
667 }
668 for (name, mut heads) in heads_by_name {
669 let Some(mut bases) = bases_by_name.remove(name) else {
670 continue;
671 };
672 heads.sort_by(|&left, &right| {
673 let (left, right) = (&findings[left], &findings[right]);
674 (&left.path, left.line, left.col).cmp(&(&right.path, right.line, right.col))
675 });
676 bases.sort_by_key(|(path, metrics)| (*path, metrics.line));
677 let mut unmatched_bases: Vec<Option<&ComplexityMetrics>> =
678 bases.iter().map(|(_, metrics)| Some(*metrics)).collect();
679 let placeholder = name.starts_with('<');
680 let rules: &[fn(&ComplexityMetrics, &ComplexityMetrics) -> bool] = if placeholder {
681 &PLACEHOLDER_RULES
682 } else {
683 &VALUE_RULES
684 };
685 match_by_rules(findings, &heads, &mut unmatched_bases, matches, rules);
686 if placeholder {
687 continue;
688 }
689 let mut remaining_heads = heads.iter().filter(|&&index| matches[index].is_none());
690 let mut remaining_bases = unmatched_bases
691 .into_iter()
692 .zip(&bases)
693 .filter(|(_, (path, _))| changed_paths.deleted.contains(*path))
694 .filter_map(|(metrics, _)| metrics);
695 if let (Some(&head), None, Some(base), None) = (
696 remaining_heads.next(),
697 remaining_heads.next(),
698 remaining_bases.next(),
699 remaining_bases.next(),
700 ) {
701 matches[head] = Some(base);
702 }
703 }
704}
705
706fn changed_path_and_name<'a>(
710 key: &'a str,
711 changed_paths: &FxHashSet<String>,
712) -> Option<(&'a str, &'a str)> {
713 let rest = key.strip_prefix("complexity:")?;
714 rest.match_indices(':').find_map(|(at, _)| {
715 let (path, name) = (&rest[..at], &rest[at + 1..]);
716 changed_paths.contains(path).then_some((path, name))
717 })
718}
719
720#[must_use]
724pub fn classify_complexity_findings_against_all<'a>(
725 findings: &[fallow_output::HealthFinding],
726 root: &Path,
727 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
728) -> Vec<bool> {
729 classify_complexity_attribution_against_all(findings, root, bases)
730 .into_iter()
731 .map(|class| class.introduced)
732 .collect()
733}
734
735#[must_use]
744pub fn classify_complexity_attribution_against_all<'a>(
745 findings: &[fallow_output::HealthFinding],
746 root: &Path,
747 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
748) -> Vec<ComplexityClass> {
749 classify_against_all(findings, root, bases, None)
750}
751
752#[must_use]
757pub fn classify_complexity_attribution_against_all_with_moves<'a>(
758 findings: &[fallow_output::HealthFinding],
759 root: &Path,
760 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
761 changed_paths: &ChangedPaths,
762) -> Vec<ComplexityClass> {
763 classify_against_all(findings, root, bases, Some(changed_paths))
764}
765
766fn classify_against_all<'a>(
767 findings: &[fallow_output::HealthFinding],
768 root: &Path,
769 bases: impl IntoIterator<Item = &'a ComplexityBaseline>,
770 changed_paths: Option<&ChangedPaths>,
771) -> Vec<ComplexityClass> {
772 let per_base: Vec<Vec<ComplexityClass>> = bases
773 .into_iter()
774 .map(|base| classify_with_moves(findings, root, base, changed_paths))
775 .collect();
776 (0..findings.len())
777 .map(|index| {
778 let classes = per_base.iter().map(|classes| &classes[index]);
779 let inherited = classes
780 .clone()
781 .filter(|class| !class.introduced)
782 .min_by_key(|class| class.worsened_metrics.len());
783 inherited.cloned().unwrap_or_else(|| ComplexityClass {
784 introduced: true,
785 exceeded_metric_grew: false,
786 base: None,
787 worsened_metrics: classes
788 .map(|class| &class.worsened_metrics)
789 .find(|metrics| !metrics.is_empty())
790 .cloned()
791 .unwrap_or_default(),
792 })
793 })
794 .collect()
795}
796
797#[must_use]
803pub fn complexity_ledger_keys(
804 findings: &[fallow_output::HealthFinding],
805 root: &Path,
806) -> Vec<String> {
807 let mut seen: FxHashMap<String, usize> = FxHashMap::default();
808 findings
809 .iter()
810 .map(|finding| {
811 let key = health_finding_key(finding, root);
812 let occurrence = seen.entry(key.clone()).or_default();
813 *occurrence += 1;
814 if *occurrence == 1 {
815 key
816 } else {
817 format!("{key}#{occurrence}")
818 }
819 })
820 .collect()
821}
822
823#[cfg(test)]
824mod tests {
825 use std::path::PathBuf;
826
827 use fallow_output::{
828 ComplexityViolation, ExceededThreshold, FindingSeverity, HealthFinding, HealthReport,
829 };
830
831 use super::*;
832
833 const MAX: u16 = 15;
834
835 fn root() -> PathBuf {
836 PathBuf::from("/project")
837 }
838
839 fn finding(name: &str, line: u32, cyclomatic: u16, cognitive: u16) -> HealthFinding {
840 HealthFinding::from(ComplexityViolation {
841 path: root().join("src/index.js"),
842 name: name.to_string(),
843 line,
844 col: 0,
845 cyclomatic,
846 standard_cyclomatic: None,
847 cognitive,
848 line_count: 30,
849 param_count: 1,
850 react_hook_count: 0,
851 react_jsx_max_depth: 0,
852 react_prop_count: 0,
853 react_hook_profile: None,
854 exceeded: ExceededThreshold::from_bools(cyclomatic > MAX, cognitive > MAX, false),
855 effective_severity: None,
856 severity: FindingSeverity::High,
857 crap: None,
858 mutation: None,
859 coverage_pct: None,
860 coverage_tier: None,
861 coverage_source: None,
862 inherited_from: None,
863 component_rollup: None,
864 contributions: Vec::new(),
865 effective_thresholds: None,
866 threshold_source: None,
867 max_file_lines: None,
868 })
869 }
870
871 fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
872 complexity_baseline(
873 &HealthReport {
874 findings,
875 ..HealthReport::default()
876 },
877 &root(),
878 )
879 }
880
881 fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
882 classify_complexity_findings(head, &root(), &baseline(base))
883 }
884
885 #[test]
886 fn identity_key_excludes_category_and_line() {
887 let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
888 assert_eq!(key, "complexity:src/index.js:hotspot");
889 }
890
891 #[test]
892 fn issue_cases() {
893 assert_eq!(
895 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
896 [false]
897 );
898 assert_eq!(
900 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
901 [false]
902 );
903 assert_eq!(
905 classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
906 [false]
907 );
908 assert_eq!(
910 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
911 [false]
912 );
913 assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
915 }
916
917 #[test]
918 fn only_exceeded_metrics_can_introduce() {
919 assert_eq!(
922 classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
923 [false]
924 );
925 assert_eq!(
927 classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
928 [true]
929 );
930 }
931
932 #[test]
933 fn a_finding_that_any_base_has_is_inherited() {
934 let primary = baseline(vec![]);
935 let merged = baseline(vec![finding("f", 1, 17, 16)]);
936 let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
937 assert_eq!(
938 classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
939 [false, true]
940 );
941 assert_eq!(
944 classify_complexity_findings_against_all(
945 &[finding("f", 1, 31, 17)],
946 &root(),
947 [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
948 ),
949 [true]
950 );
951 }
952
953 fn finding_in(path: &str, name: &str, cyclomatic: u16, cognitive: u16) -> HealthFinding {
954 let mut finding = finding(name, 1, cyclomatic, cognitive);
955 finding.violation.path = root().join(path);
956 finding
957 }
958
959 fn changed(paths: &[&str]) -> ChangedPaths {
962 let changed: FxHashSet<String> = paths.iter().map(|path| (*path).to_string()).collect();
963 let deleted = ["src/old.js", "src/a.js", "src/b.js"]
964 .into_iter()
965 .filter(|path| changed.contains(*path))
966 .map(str::to_string)
967 .collect();
968 ChangedPaths { changed, deleted }
969 }
970
971 fn classify_moves(
972 base: Vec<HealthFinding>,
973 head: &[HealthFinding],
974 changed_paths: &[&str],
975 ) -> Vec<AuditFindingAttribution> {
976 classify_complexity_attribution_with_moves(
977 head,
978 &root(),
979 &baseline(base),
980 &changed(changed_paths),
981 )
982 .iter()
983 .map(ComplexityClass::attribution)
984 .collect()
985 }
986
987 #[test]
988 fn moved_function_compares_with_its_base_finding() {
989 use AuditFindingAttribution::{Inherited, Introduced, Worsened};
990 let base = || vec![finding_in("src/old.js", "f", 17, 16)];
991 let both = ["src/old.js", "src/new.js"];
992
993 assert_eq!(
994 classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
995 [Inherited]
996 );
997 assert_eq!(
998 classify_moves(base(), &[finding_in("src/new.js", "f", 18, 17)], &both),
999 [Worsened]
1000 );
1001 assert_eq!(
1003 classify(base(), &[finding_in("src/new.js", "f", 17, 16)]),
1004 [true]
1005 );
1006 assert_eq!(
1009 classify_moves(
1010 base(),
1011 &[finding_in("src/new.js", "f", 17, 16)],
1012 &["src/new.js"]
1013 ),
1014 [Introduced]
1015 );
1016 }
1017
1018 #[test]
1019 fn grown_function_does_not_take_the_base_finding_of_a_kept_file() {
1020 use AuditFindingAttribution::{Inherited, Introduced};
1021 let base = || vec![finding_in("src/kept.js", "f", 17, 16)];
1022 let both = ["src/kept.js", "src/new.js"];
1023 assert_eq!(
1026 classify_moves(base(), &[finding_in("src/new.js", "f", 16, 16)], &both),
1027 [Introduced]
1028 );
1029 assert_eq!(
1031 classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
1032 [Inherited]
1033 );
1034 }
1035
1036 #[test]
1037 fn one_of_two_same_named_functions_moves() {
1038 use AuditFindingAttribution::Inherited;
1039 let mut second = finding_in("src/kept.js", "run", 21, 20);
1040 second.violation.line = 40;
1041 let base = vec![finding_in("src/kept.js", "run", 17, 16), second];
1042 let head = [
1043 finding_in("src/kept.js", "run", 17, 16),
1044 finding_in("src/new.js", "run", 21, 20),
1045 ];
1046 assert_eq!(
1047 classify_moves(base, &head, &["src/kept.js", "src/new.js"]),
1048 [Inherited, Inherited]
1049 );
1050 }
1051
1052 #[test]
1053 fn moved_function_does_not_take_a_base_finding_that_is_in_use() {
1054 use AuditFindingAttribution::{Inherited, Introduced};
1055 let head = [
1056 finding_in("src/old.js", "f", 17, 16),
1057 finding_in("src/new.js", "f", 17, 16),
1058 ];
1059 assert_eq!(
1060 classify_moves(
1061 vec![finding_in("src/old.js", "f", 17, 16)],
1062 &head,
1063 &["src/old.js", "src/new.js"]
1064 ),
1065 [Inherited, Introduced]
1066 );
1067 }
1068
1069 #[test]
1070 fn same_named_moved_functions_pair_by_values_only() {
1071 use AuditFindingAttribution::{Inherited, Introduced};
1072 let base = || {
1073 vec![
1074 finding_in("src/a.js", "run", 17, 16),
1075 finding_in("src/b.js", "run", 21, 20),
1076 ]
1077 };
1078 let paths = ["src/a.js", "src/b.js", "src/c.js", "src/d.js"];
1079 assert_eq!(
1081 classify_moves(
1082 base(),
1083 &[
1084 finding_in("src/c.js", "run", 21, 20),
1085 finding_in("src/d.js", "run", 17, 16),
1086 ],
1087 &paths
1088 ),
1089 [Inherited, Inherited]
1090 );
1091 assert_eq!(
1093 classify_moves(
1094 base(),
1095 &[
1096 finding_in("src/c.js", "run", 22, 21),
1097 finding_in("src/d.js", "run", 18, 17),
1098 ],
1099 &paths
1100 ),
1101 [Introduced, Introduced]
1102 );
1103 }
1104
1105 #[test]
1106 fn moved_placeholder_name_needs_equal_values_and_lines() {
1107 use AuditFindingAttribution::{Inherited, Introduced};
1108 let base = || vec![finding_in("src/old.js", "<arrow>", 17, 16)];
1109 let both = ["src/old.js", "src/new.js"];
1110 assert_eq!(
1111 classify_moves(
1112 base(),
1113 &[finding_in("src/new.js", "<arrow>", 17, 16)],
1114 &both
1115 ),
1116 [Inherited]
1117 );
1118 assert_eq!(
1119 classify_moves(
1120 base(),
1121 &[finding_in("src/new.js", "<arrow>", 18, 17)],
1122 &both
1123 ),
1124 [Introduced]
1125 );
1126 }
1127
1128 #[test]
1129 fn moved_function_name_can_contain_a_colon() {
1130 assert_eq!(
1131 classify_moves(
1132 vec![finding_in("src/old.js", "it: parses", 17, 16)],
1133 &[finding_in("src/new.js", "it: parses", 17, 16)],
1134 &["src/old.js", "src/new.js"]
1135 ),
1136 [AuditFindingAttribution::Inherited]
1137 );
1138 }
1139
1140 #[test]
1141 fn line_shift_keeps_the_match() {
1142 assert_eq!(
1143 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
1144 [false]
1145 );
1146 }
1147
1148 fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
1149 let mut finding = finding("f", 1, 16, 5);
1150 finding.violation.exceeded = ExceededThreshold::Crap;
1151 finding.violation.crap = crap;
1152 finding.violation.coverage_source = source;
1153 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1154 finding
1155 }
1156
1157 #[test]
1158 fn crap_without_base_value_is_not_an_increase() {
1159 let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
1162 assert_eq!(
1163 classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
1164 [false]
1165 );
1166 assert_eq!(
1168 classify(
1169 vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
1170 std::slice::from_ref(&head)
1171 ),
1172 [false]
1173 );
1174 assert_eq!(
1175 classify(
1176 vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
1177 &[head]
1178 ),
1179 [false]
1180 );
1181 }
1182
1183 #[test]
1184 fn estimated_crap_growth_is_worsened_not_introduced() {
1185 let estimated = Some(CoverageSource::Estimated);
1186 let classes = attribution(
1187 vec![crap_finding(Some(40.0), estimated)],
1188 &[crap_finding(Some(50.0), estimated)],
1189 );
1190 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1191 assert_eq!(
1192 classes[0].worsened_metrics,
1193 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1194 );
1195 let mut base = crap_finding(Some(40.0), estimated);
1197 base.violation.exceeded = ExceededThreshold::CognitiveCrap;
1198 base.violation.cognitive = 20;
1199 let mut head = base.clone();
1200 head.violation.cognitive = 21;
1201 head.violation.crap = Some(50.0);
1202 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
1203 head.violation.cognitive = 25;
1205 assert_eq!(classify(vec![base], &[head]), [true]);
1206 }
1207
1208 #[test]
1209 fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
1210 let project = root().join("tests").join("project");
1213 let at = |relative: &str| {
1214 let mut finding = finding("f", 1, 16, 5);
1215 finding.violation.path = project.join(relative);
1216 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1217 finding
1218 };
1219 let mut findings = [
1220 at("src/__tests__/app.js"),
1221 at("src/app.spec.ts"),
1222 at("src/app.test.tsx"),
1223 at("src/__mocks__/api.js"),
1224 at("src/app.js"),
1225 at("src/latest.js"),
1226 ];
1227 exempt_test_file_gates(&mut findings, &project);
1228 let marks: Vec<_> = findings
1229 .iter()
1230 .map(|finding| (finding.effective_severity, finding.gate_exemption))
1231 .collect();
1232 let exempt = (
1233 Some(EffectiveSeverity::Warn),
1234 Some(AuditGateExemption::TestFile),
1235 );
1236 let gated = (Some(EffectiveSeverity::Error), None);
1237 assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
1238 }
1239
1240 #[test]
1241 fn estimated_crap_only_findings_get_warn_gate_severity() {
1242 let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1243 both.violation.exceeded = ExceededThreshold::CognitiveCrap;
1244 let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1245 warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
1246 let mut findings = [
1247 crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
1248 crap_finding(
1249 Some(50.0),
1250 Some(CoverageSource::EstimatedComponentInherited),
1251 ),
1252 crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
1253 both,
1254 warn_rule,
1255 ];
1256 demote_estimated_crap_gates(&mut findings);
1257 let severities: Vec<_> = findings
1258 .iter()
1259 .map(|finding| finding.effective_severity)
1260 .collect();
1261 assert_eq!(
1262 severities,
1263 [
1264 Some(EffectiveSeverity::Warn),
1265 Some(EffectiveSeverity::Warn),
1266 Some(EffectiveSeverity::Error),
1267 Some(EffectiveSeverity::Error),
1268 Some(EffectiveSeverity::Warn),
1269 ]
1270 );
1271 }
1272
1273 #[test]
1274 fn same_named_findings_match_unchanged_values_first() {
1275 let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
1276 assert_eq!(
1278 classify(
1279 base.clone(),
1280 &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
1281 ),
1282 [false, false]
1283 );
1284 assert_eq!(
1286 classify(base.clone(), &[finding("run", 1, 21, 20)]),
1287 [false]
1288 );
1289 assert_eq!(
1291 classify(
1292 base.clone(),
1293 &[
1294 finding("run", 1, 30, 30),
1295 finding("run", 20, 17, 16),
1296 finding("run", 50, 21, 20)
1297 ]
1298 ),
1299 [true, false, false]
1300 );
1301 assert_eq!(
1303 classify(
1304 base.clone(),
1305 &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
1306 ),
1307 [false, false]
1308 );
1309 assert_eq!(
1311 classify(
1312 base,
1313 &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
1314 ),
1315 [true, false]
1316 );
1317 }
1318
1319 fn arrow(
1321 line: u32,
1322 cyclomatic: u16,
1323 cognitive: u16,
1324 crap: Option<f64>,
1325 source: CoverageSource,
1326 ) -> HealthFinding {
1327 let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
1328 finding.violation.cyclomatic = cyclomatic;
1329 finding.violation.cognitive = cognitive;
1330 finding.violation.crap = crap;
1331 finding.violation.coverage_source = crap.map(|_| source);
1332 finding.violation.exceeded = ExceededThreshold::from_bools(
1333 cyclomatic > MAX,
1334 cognitive > MAX,
1335 crap.is_some_and(|crap| crap >= 30.0),
1336 );
1337 finding
1338 }
1339
1340 #[test]
1341 fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
1342 let estimated = CoverageSource::Estimated;
1347 let measured = CoverageSource::Istanbul;
1348 let base = [
1349 (122, 36, 37, 1332.0),
1350 (284, 26, 28, 702.0),
1351 (352, 9, 6, 90.0),
1352 (560, 7, 6, 56.0),
1353 (637, 30, 42, 930.0),
1354 (732, 13, 5, 182.0),
1355 (872, 13, 12, 182.0),
1356 (889, 6, 2, 42.0),
1357 (945, 5, 3, 30.0),
1358 (972, 16, 4, 272.0),
1359 (1017, 11, 13, 132.0),
1360 (1184, 14, 15, 210.0),
1361 (1202, 12, 5, 156.0),
1362 ]
1363 .into_iter()
1364 .map(|(line, cyclomatic, cognitive, crap)| {
1365 arrow(line, cyclomatic, cognitive, Some(crap), estimated)
1366 })
1367 .collect();
1368 let head = [
1369 arrow(128, 36, 37, Some(36.0), measured),
1370 arrow(294, 27, 29, None, measured),
1371 arrow(663, 30, 42, Some(30.0), measured),
1372 ];
1373 let classes = attribution(base, &head);
1374 assert!(!classes[0].introduced);
1375 assert!(!classes[2].introduced, "{:?}", classes[2]);
1376 assert!(classes[2].worsened_metrics.is_empty());
1377 }
1378
1379 #[test]
1380 fn crap_growth_of_an_unchanged_arrow_still_compares() {
1381 let measured = CoverageSource::Istanbul;
1382 let classes = attribution(
1383 vec![
1384 arrow(10, 9, 6, Some(40.0), measured),
1385 arrow(40, 30, 42, Some(30.0), measured),
1386 ],
1387 &[arrow(40, 30, 42, Some(60.0), measured)],
1388 );
1389 assert_eq!(
1390 classes[0].worsened_metrics,
1391 [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
1392 );
1393 }
1394
1395 fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
1396 finding.violation.line_count = line_count;
1397 finding
1398 }
1399
1400 fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
1401 classify_complexity_attribution(head, &root(), &baseline(base))
1402 }
1403
1404 fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
1405 WorsenedMetric {
1406 metric: kind,
1407 base,
1408 head,
1409 }
1410 }
1411
1412 #[test]
1413 fn grown_line_count_is_worsened_not_introduced() {
1414 let classes = attribution(
1415 vec![with_lines(finding("f", 1, 17, 16), 80)],
1416 &[with_lines(finding("f", 1, 17, 16), 300)],
1417 );
1418 assert!(!classes[0].introduced);
1419 assert!(classes[0].is_worsened());
1420 assert_eq!(
1421 classes[0].worsened_metrics,
1422 [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1423 );
1424 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1425 }
1426
1427 #[test]
1428 fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1429 let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1431 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1432 assert_eq!(
1433 classes[0].worsened_metrics,
1434 [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1435 );
1436 }
1437
1438 #[test]
1439 fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1440 let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1442 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1443 assert!(classes[0].exceeded_metric_grew);
1444 assert_eq!(
1445 classes[0].worsened_metrics,
1446 [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1447 );
1448 let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1450 assert!(!below[0].exceeded_metric_grew);
1451 }
1452
1453 #[test]
1454 fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1455 let mut head = finding("f", 1, 18, 10);
1459 head.violation.exceeded = ExceededThreshold::Both;
1460 assert_eq!(
1461 classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1462 [false]
1463 );
1464 head.violation.cognitive = 11;
1466 assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1467 }
1468
1469 #[test]
1470 fn measured_crap_tier_crossing_is_introduced() {
1471 let istanbul = Some(CoverageSource::Istanbul);
1472 let mut base = crap_finding(Some(40.0), istanbul);
1473 base.violation.severity = FindingSeverity::Moderate;
1474 let mut head = crap_finding(Some(120.0), istanbul);
1475 head.violation.severity = FindingSeverity::Critical;
1476 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1477 let estimated = Some(CoverageSource::Estimated);
1479 base.violation.coverage_source = estimated;
1480 head.violation.coverage_source = estimated;
1481 assert_eq!(classify(vec![base], &[head]), [false]);
1482 }
1483
1484 #[test]
1485 fn grown_exceeded_metric_is_introduced_with_values() {
1486 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1487 assert_eq!(
1488 classes[0].attribution(),
1489 AuditFindingAttribution::Introduced
1490 );
1491 assert_eq!(
1492 classes[0].worsened_metrics,
1493 [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1494 );
1495 assert!(!classes[0].is_worsened());
1496 }
1497
1498 #[test]
1499 fn improved_and_moved_functions_are_inherited() {
1500 let improved = attribution(
1501 vec![with_lines(finding("f", 1, 30, 30), 90)],
1502 &[with_lines(finding("f", 1, 20, 18), 60)],
1503 );
1504 assert_eq!(
1505 improved[0].attribution(),
1506 AuditFindingAttribution::Inherited
1507 );
1508 assert!(improved[0].worsened_metrics.is_empty());
1509 let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1510 assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1511 }
1512
1513 #[test]
1514 fn new_function_is_introduced_without_values() {
1515 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1516 assert_eq!(
1517 classes[0].attribution(),
1518 AuditFindingAttribution::Introduced
1519 );
1520 assert!(classes[0].worsened_metrics.is_empty());
1521 }
1522
1523 #[test]
1524 fn crap_compares_only_when_both_sides_have_a_score() {
1525 let mut head = finding("f", 1, 20, 5);
1526 head.violation.crap = Some(50.0);
1527 let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1528 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1529 let mut base = finding("f", 1, 20, 5);
1530 base.violation.crap = Some(40.0);
1531 let classes = attribution(vec![base], &[head]);
1532 assert_eq!(
1533 classes[0].worsened_metrics,
1534 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1535 );
1536 }
1537
1538 #[test]
1539 fn same_named_findings_prefer_the_base_with_equal_line_count() {
1540 let base = vec![
1542 with_lines(finding("run", 1, 17, 16), 10),
1543 with_lines(finding("run", 30, 17, 16), 40),
1544 ];
1545 let head = [
1546 with_lines(finding("run", 1, 17, 16), 40),
1547 with_lines(finding("run", 50, 17, 16), 25),
1548 ];
1549 let classes = attribution(base, &head);
1550 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1553 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1554 }
1555
1556 #[test]
1557 fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1558 let base = vec![
1561 with_lines(finding("run", 1, 17, 16), 40),
1562 with_lines(finding("run", 50, 17, 16), 10),
1563 ];
1564 let head = [
1565 with_lines(finding("run", 1, 17, 16), 30),
1566 with_lines(finding("run", 20, 17, 16), 40),
1567 ];
1568 let classes = attribution(base, &head);
1569 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1570 assert_eq!(
1571 classes[0].worsened_metrics,
1572 [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1573 );
1574 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1575 assert!(classes[1].worsened_metrics.is_empty());
1576 }
1577
1578 #[test]
1579 fn small_line_growth_is_not_worsened() {
1580 let classes = attribution(
1582 vec![with_lines(finding("f", 1, 17, 16), 80)],
1583 &[with_lines(finding("f", 1, 17, 16), 84)],
1584 );
1585 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1586 assert!(classes[0].worsened_metrics.is_empty());
1587 }
1588
1589 #[test]
1590 fn line_growth_needs_five_lines_at_any_function_size() {
1591 let short = attribution(
1593 vec![with_lines(finding("f", 1, 17, 16), 20)],
1594 &[with_lines(finding("f", 1, 17, 16), 24)],
1595 );
1596 assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1597 let grown = attribution(
1598 vec![with_lines(finding("f", 1, 17, 16), 20)],
1599 &[with_lines(finding("f", 1, 17, 16), 25)],
1600 );
1601 assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1602 let long = attribution(
1604 vec![with_lines(finding("f", 1, 17, 16), 300)],
1605 &[with_lines(finding("f", 1, 17, 16), 309)],
1606 );
1607 assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1608 }
1609
1610 #[test]
1611 fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1612 let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1613 let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1614 let head = [with_lines(finding("f", 1, 17, 16), 60)];
1615 let classes =
1616 classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1617 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1618 let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1619 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1620 }
1621
1622 #[test]
1623 fn rename_moves_the_base_findings() {
1624 let base = baseline(vec![finding("f", 1, 17, 16)]);
1625 let renames =
1626 FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1627 let remapped = remap_complexity_baseline_for_renames(base, &renames);
1628 assert!(remapped.contains_key("complexity:src/moved.js:f"));
1629 assert!(!remapped.contains_key("complexity:src/index.js:f"));
1630 }
1631
1632 #[test]
1633 fn ledger_keys_count_same_named_findings_separately() {
1634 let keys = complexity_ledger_keys(
1635 &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1636 &root(),
1637 );
1638 assert_eq!(
1639 keys,
1640 [
1641 "complexity:src/index.js:run",
1642 "complexity:src/index.js:run#2"
1643 ]
1644 );
1645 }
1646}