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 override_comment_line: None,
868 max_file_lines: None,
869 })
870 }
871
872 fn baseline(findings: Vec<HealthFinding>) -> ComplexityBaseline {
873 complexity_baseline(
874 &HealthReport {
875 findings,
876 ..HealthReport::default()
877 },
878 &root(),
879 )
880 }
881
882 fn classify(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<bool> {
883 classify_complexity_findings(head, &root(), &baseline(base))
884 }
885
886 #[test]
887 fn identity_key_excludes_category_and_line() {
888 let key = health_finding_key(&finding("hotspot", 4, 17, 16), &root());
889 assert_eq!(key, "complexity:src/index.js:hotspot");
890 }
891
892 #[test]
893 fn issue_cases() {
894 assert_eq!(
896 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 17, 16)]),
897 [false]
898 );
899 assert_eq!(
901 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 18, 17)]),
902 [false]
903 );
904 assert_eq!(
906 classify(vec![finding("f", 1, 18, 17)], &[finding("f", 1, 17, 16)]),
907 [false]
908 );
909 assert_eq!(
911 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 16, 15)]),
912 [false]
913 );
914 assert_eq!(classify(vec![], &[finding("f", 1, 17, 16)]), [true]);
916 }
917
918 #[test]
919 fn only_exceeded_metrics_can_introduce() {
920 assert_eq!(
923 classify(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]),
924 [false]
925 );
926 assert_eq!(
928 classify(vec![finding("f", 1, 20, 14)], &[finding("f", 1, 19, 16)]),
929 [true]
930 );
931 }
932
933 #[test]
934 fn a_finding_that_any_base_has_is_inherited() {
935 let primary = baseline(vec![]);
936 let merged = baseline(vec![finding("f", 1, 17, 16)]);
937 let head = [finding("f", 1, 17, 16), finding("g", 9, 17, 16)];
938 assert_eq!(
939 classify_complexity_findings_against_all(&head, &root(), [&primary, &merged]),
940 [false, true]
941 );
942 assert_eq!(
945 classify_complexity_findings_against_all(
946 &[finding("f", 1, 31, 17)],
947 &root(),
948 [&baseline(vec![finding("f", 1, 17, 16)]), &merged]
949 ),
950 [true]
951 );
952 }
953
954 fn finding_in(path: &str, name: &str, cyclomatic: u16, cognitive: u16) -> HealthFinding {
955 let mut finding = finding(name, 1, cyclomatic, cognitive);
956 finding.violation.path = root().join(path);
957 finding
958 }
959
960 fn changed(paths: &[&str]) -> ChangedPaths {
963 let changed: FxHashSet<String> = paths.iter().map(|path| (*path).to_string()).collect();
964 let deleted = ["src/old.js", "src/a.js", "src/b.js"]
965 .into_iter()
966 .filter(|path| changed.contains(*path))
967 .map(str::to_string)
968 .collect();
969 ChangedPaths { changed, deleted }
970 }
971
972 fn classify_moves(
973 base: Vec<HealthFinding>,
974 head: &[HealthFinding],
975 changed_paths: &[&str],
976 ) -> Vec<AuditFindingAttribution> {
977 classify_complexity_attribution_with_moves(
978 head,
979 &root(),
980 &baseline(base),
981 &changed(changed_paths),
982 )
983 .iter()
984 .map(ComplexityClass::attribution)
985 .collect()
986 }
987
988 #[test]
989 fn moved_function_compares_with_its_base_finding() {
990 use AuditFindingAttribution::{Inherited, Introduced, Worsened};
991 let base = || vec![finding_in("src/old.js", "f", 17, 16)];
992 let both = ["src/old.js", "src/new.js"];
993
994 assert_eq!(
995 classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
996 [Inherited]
997 );
998 assert_eq!(
999 classify_moves(base(), &[finding_in("src/new.js", "f", 18, 17)], &both),
1000 [Worsened]
1001 );
1002 assert_eq!(
1004 classify(base(), &[finding_in("src/new.js", "f", 17, 16)]),
1005 [true]
1006 );
1007 assert_eq!(
1010 classify_moves(
1011 base(),
1012 &[finding_in("src/new.js", "f", 17, 16)],
1013 &["src/new.js"]
1014 ),
1015 [Introduced]
1016 );
1017 }
1018
1019 #[test]
1020 fn grown_function_does_not_take_the_base_finding_of_a_kept_file() {
1021 use AuditFindingAttribution::{Inherited, Introduced};
1022 let base = || vec![finding_in("src/kept.js", "f", 17, 16)];
1023 let both = ["src/kept.js", "src/new.js"];
1024 assert_eq!(
1027 classify_moves(base(), &[finding_in("src/new.js", "f", 16, 16)], &both),
1028 [Introduced]
1029 );
1030 assert_eq!(
1032 classify_moves(base(), &[finding_in("src/new.js", "f", 17, 16)], &both),
1033 [Inherited]
1034 );
1035 }
1036
1037 #[test]
1038 fn one_of_two_same_named_functions_moves() {
1039 use AuditFindingAttribution::Inherited;
1040 let mut second = finding_in("src/kept.js", "run", 21, 20);
1041 second.violation.line = 40;
1042 let base = vec![finding_in("src/kept.js", "run", 17, 16), second];
1043 let head = [
1044 finding_in("src/kept.js", "run", 17, 16),
1045 finding_in("src/new.js", "run", 21, 20),
1046 ];
1047 assert_eq!(
1048 classify_moves(base, &head, &["src/kept.js", "src/new.js"]),
1049 [Inherited, Inherited]
1050 );
1051 }
1052
1053 #[test]
1054 fn moved_function_does_not_take_a_base_finding_that_is_in_use() {
1055 use AuditFindingAttribution::{Inherited, Introduced};
1056 let head = [
1057 finding_in("src/old.js", "f", 17, 16),
1058 finding_in("src/new.js", "f", 17, 16),
1059 ];
1060 assert_eq!(
1061 classify_moves(
1062 vec![finding_in("src/old.js", "f", 17, 16)],
1063 &head,
1064 &["src/old.js", "src/new.js"]
1065 ),
1066 [Inherited, Introduced]
1067 );
1068 }
1069
1070 #[test]
1071 fn same_named_moved_functions_pair_by_values_only() {
1072 use AuditFindingAttribution::{Inherited, Introduced};
1073 let base = || {
1074 vec![
1075 finding_in("src/a.js", "run", 17, 16),
1076 finding_in("src/b.js", "run", 21, 20),
1077 ]
1078 };
1079 let paths = ["src/a.js", "src/b.js", "src/c.js", "src/d.js"];
1080 assert_eq!(
1082 classify_moves(
1083 base(),
1084 &[
1085 finding_in("src/c.js", "run", 21, 20),
1086 finding_in("src/d.js", "run", 17, 16),
1087 ],
1088 &paths
1089 ),
1090 [Inherited, Inherited]
1091 );
1092 assert_eq!(
1094 classify_moves(
1095 base(),
1096 &[
1097 finding_in("src/c.js", "run", 22, 21),
1098 finding_in("src/d.js", "run", 18, 17),
1099 ],
1100 &paths
1101 ),
1102 [Introduced, Introduced]
1103 );
1104 }
1105
1106 #[test]
1107 fn moved_placeholder_name_needs_equal_values_and_lines() {
1108 use AuditFindingAttribution::{Inherited, Introduced};
1109 let base = || vec![finding_in("src/old.js", "<arrow>", 17, 16)];
1110 let both = ["src/old.js", "src/new.js"];
1111 assert_eq!(
1112 classify_moves(
1113 base(),
1114 &[finding_in("src/new.js", "<arrow>", 17, 16)],
1115 &both
1116 ),
1117 [Inherited]
1118 );
1119 assert_eq!(
1120 classify_moves(
1121 base(),
1122 &[finding_in("src/new.js", "<arrow>", 18, 17)],
1123 &both
1124 ),
1125 [Introduced]
1126 );
1127 }
1128
1129 #[test]
1130 fn moved_function_name_can_contain_a_colon() {
1131 assert_eq!(
1132 classify_moves(
1133 vec![finding_in("src/old.js", "it: parses", 17, 16)],
1134 &[finding_in("src/new.js", "it: parses", 17, 16)],
1135 &["src/old.js", "src/new.js"]
1136 ),
1137 [AuditFindingAttribution::Inherited]
1138 );
1139 }
1140
1141 #[test]
1142 fn line_shift_keeps_the_match() {
1143 assert_eq!(
1144 classify(vec![finding("f", 1, 17, 16)], &[finding("f", 40, 17, 16)]),
1145 [false]
1146 );
1147 }
1148
1149 fn crap_finding(crap: Option<f64>, source: Option<CoverageSource>) -> HealthFinding {
1150 let mut finding = finding("f", 1, 16, 5);
1151 finding.violation.exceeded = ExceededThreshold::Crap;
1152 finding.violation.crap = crap;
1153 finding.violation.coverage_source = source;
1154 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1155 finding
1156 }
1157
1158 #[test]
1159 fn crap_without_base_value_is_not_an_increase() {
1160 let head = crap_finding(Some(50.0), Some(CoverageSource::Istanbul));
1163 assert_eq!(
1164 classify(vec![crap_finding(None, None)], std::slice::from_ref(&head)),
1165 [false]
1166 );
1167 assert_eq!(
1169 classify(
1170 vec![crap_finding(Some(40.0), Some(CoverageSource::Istanbul))],
1171 std::slice::from_ref(&head)
1172 ),
1173 [false]
1174 );
1175 assert_eq!(
1176 classify(
1177 vec![crap_finding(Some(60.0), Some(CoverageSource::Istanbul))],
1178 &[head]
1179 ),
1180 [false]
1181 );
1182 }
1183
1184 #[test]
1185 fn estimated_crap_growth_is_worsened_not_introduced() {
1186 let estimated = Some(CoverageSource::Estimated);
1187 let classes = attribution(
1188 vec![crap_finding(Some(40.0), estimated)],
1189 &[crap_finding(Some(50.0), estimated)],
1190 );
1191 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1192 assert_eq!(
1193 classes[0].worsened_metrics,
1194 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1195 );
1196 let mut base = crap_finding(Some(40.0), estimated);
1198 base.violation.exceeded = ExceededThreshold::CognitiveCrap;
1199 base.violation.cognitive = 20;
1200 let mut head = base.clone();
1201 head.violation.cognitive = 21;
1202 head.violation.crap = Some(50.0);
1203 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [false]);
1204 head.violation.cognitive = 25;
1206 assert_eq!(classify(vec![base], &[head]), [true]);
1207 }
1208
1209 #[test]
1210 fn test_file_findings_get_warn_gate_severity_and_the_exemption() {
1211 let project = root().join("tests").join("project");
1214 let at = |relative: &str| {
1215 let mut finding = finding("f", 1, 16, 5);
1216 finding.violation.path = project.join(relative);
1217 finding.violation.effective_severity = Some(EffectiveSeverity::Error);
1218 finding
1219 };
1220 let mut findings = [
1221 at("src/__tests__/app.js"),
1222 at("src/app.spec.ts"),
1223 at("src/app.test.tsx"),
1224 at("src/__mocks__/api.js"),
1225 at("src/app.js"),
1226 at("src/latest.js"),
1227 ];
1228 exempt_test_file_gates(&mut findings, &project);
1229 let marks: Vec<_> = findings
1230 .iter()
1231 .map(|finding| (finding.effective_severity, finding.gate_exemption))
1232 .collect();
1233 let exempt = (
1234 Some(EffectiveSeverity::Warn),
1235 Some(AuditGateExemption::TestFile),
1236 );
1237 let gated = (Some(EffectiveSeverity::Error), None);
1238 assert_eq!(marks, [exempt, exempt, exempt, exempt, gated, gated]);
1239 }
1240
1241 #[test]
1242 fn estimated_crap_only_findings_get_warn_gate_severity() {
1243 let mut both = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1244 both.violation.exceeded = ExceededThreshold::CognitiveCrap;
1245 let mut warn_rule = crap_finding(Some(50.0), Some(CoverageSource::Estimated));
1246 warn_rule.violation.effective_severity = Some(EffectiveSeverity::Warn);
1247 let mut findings = [
1248 crap_finding(Some(50.0), Some(CoverageSource::Estimated)),
1249 crap_finding(
1250 Some(50.0),
1251 Some(CoverageSource::EstimatedComponentInherited),
1252 ),
1253 crap_finding(Some(50.0), Some(CoverageSource::Istanbul)),
1254 both,
1255 warn_rule,
1256 ];
1257 demote_estimated_crap_gates(&mut findings);
1258 let severities: Vec<_> = findings
1259 .iter()
1260 .map(|finding| finding.effective_severity)
1261 .collect();
1262 assert_eq!(
1263 severities,
1264 [
1265 Some(EffectiveSeverity::Warn),
1266 Some(EffectiveSeverity::Warn),
1267 Some(EffectiveSeverity::Error),
1268 Some(EffectiveSeverity::Error),
1269 Some(EffectiveSeverity::Warn),
1270 ]
1271 );
1272 }
1273
1274 #[test]
1275 fn same_named_findings_match_unchanged_values_first() {
1276 let base = vec![finding("run", 1, 17, 16), finding("run", 30, 21, 20)];
1277 assert_eq!(
1279 classify(
1280 base.clone(),
1281 &[finding("run", 1, 17, 16), finding("run", 30, 21, 20)]
1282 ),
1283 [false, false]
1284 );
1285 assert_eq!(
1287 classify(base.clone(), &[finding("run", 1, 21, 20)]),
1288 [false]
1289 );
1290 assert_eq!(
1292 classify(
1293 base.clone(),
1294 &[
1295 finding("run", 1, 30, 30),
1296 finding("run", 20, 17, 16),
1297 finding("run", 50, 21, 20)
1298 ]
1299 ),
1300 [true, false, false]
1301 );
1302 assert_eq!(
1304 classify(
1305 base.clone(),
1306 &[finding("run", 1, 18, 17), finding("run", 30, 21, 20)]
1307 ),
1308 [false, false]
1309 );
1310 assert_eq!(
1312 classify(
1313 base,
1314 &[finding("run", 1, 30, 17), finding("run", 30, 21, 20)]
1315 ),
1316 [true, false]
1317 );
1318 }
1319
1320 fn arrow(
1322 line: u32,
1323 cyclomatic: u16,
1324 cognitive: u16,
1325 crap: Option<f64>,
1326 source: CoverageSource,
1327 ) -> HealthFinding {
1328 let mut finding = finding("<arrow>", line, MAX + 1, MAX + 1);
1329 finding.violation.cyclomatic = cyclomatic;
1330 finding.violation.cognitive = cognitive;
1331 finding.violation.crap = crap;
1332 finding.violation.coverage_source = crap.map(|_| source);
1333 finding.violation.exceeded = ExceededThreshold::from_bools(
1334 cyclomatic > MAX,
1335 cognitive > MAX,
1336 crap.is_some_and(|crap| crap >= 30.0),
1337 );
1338 finding
1339 }
1340
1341 #[test]
1342 fn unchanged_arrow_keeps_its_base_when_only_crap_changes() {
1343 let estimated = CoverageSource::Estimated;
1348 let measured = CoverageSource::Istanbul;
1349 let base = [
1350 (122, 36, 37, 1332.0),
1351 (284, 26, 28, 702.0),
1352 (352, 9, 6, 90.0),
1353 (560, 7, 6, 56.0),
1354 (637, 30, 42, 930.0),
1355 (732, 13, 5, 182.0),
1356 (872, 13, 12, 182.0),
1357 (889, 6, 2, 42.0),
1358 (945, 5, 3, 30.0),
1359 (972, 16, 4, 272.0),
1360 (1017, 11, 13, 132.0),
1361 (1184, 14, 15, 210.0),
1362 (1202, 12, 5, 156.0),
1363 ]
1364 .into_iter()
1365 .map(|(line, cyclomatic, cognitive, crap)| {
1366 arrow(line, cyclomatic, cognitive, Some(crap), estimated)
1367 })
1368 .collect();
1369 let head = [
1370 arrow(128, 36, 37, Some(36.0), measured),
1371 arrow(294, 27, 29, None, measured),
1372 arrow(663, 30, 42, Some(30.0), measured),
1373 ];
1374 let classes = attribution(base, &head);
1375 assert!(!classes[0].introduced);
1376 assert!(!classes[2].introduced, "{:?}", classes[2]);
1377 assert!(classes[2].worsened_metrics.is_empty());
1378 }
1379
1380 #[test]
1381 fn crap_growth_of_an_unchanged_arrow_still_compares() {
1382 let measured = CoverageSource::Istanbul;
1383 let classes = attribution(
1384 vec![
1385 arrow(10, 9, 6, Some(40.0), measured),
1386 arrow(40, 30, 42, Some(30.0), measured),
1387 ],
1388 &[arrow(40, 30, 42, Some(60.0), measured)],
1389 );
1390 assert_eq!(
1391 classes[0].worsened_metrics,
1392 [metric(WorsenedMetricKind::Crap, 30.0, 60.0)]
1393 );
1394 }
1395
1396 fn with_lines(mut finding: HealthFinding, line_count: u32) -> HealthFinding {
1397 finding.violation.line_count = line_count;
1398 finding
1399 }
1400
1401 fn attribution(base: Vec<HealthFinding>, head: &[HealthFinding]) -> Vec<ComplexityClass> {
1402 classify_complexity_attribution(head, &root(), &baseline(base))
1403 }
1404
1405 fn metric(kind: WorsenedMetricKind, base: f64, head: f64) -> WorsenedMetric {
1406 WorsenedMetric {
1407 metric: kind,
1408 base,
1409 head,
1410 }
1411 }
1412
1413 #[test]
1414 fn grown_line_count_is_worsened_not_introduced() {
1415 let classes = attribution(
1416 vec![with_lines(finding("f", 1, 17, 16), 80)],
1417 &[with_lines(finding("f", 1, 17, 16), 300)],
1418 );
1419 assert!(!classes[0].introduced);
1420 assert!(classes[0].is_worsened());
1421 assert_eq!(
1422 classes[0].worsened_metrics,
1423 [metric(WorsenedMetricKind::LineCount, 80.0, 300.0)]
1424 );
1425 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1426 }
1427
1428 #[test]
1429 fn grown_metric_that_the_finding_does_not_exceed_is_worsened() {
1430 let classes = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1432 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1433 assert_eq!(
1434 classes[0].worsened_metrics,
1435 [metric(WorsenedMetricKind::Cognitive, 5.0, 9.0)]
1436 );
1437 }
1438
1439 #[test]
1440 fn grown_exceeded_metric_in_the_same_tier_is_worsened() {
1441 let classes = attribution(vec![finding("f", 1, 100, 16)], &[finding("f", 1, 103, 16)]);
1443 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1444 assert!(classes[0].exceeded_metric_grew);
1445 assert_eq!(
1446 classes[0].worsened_metrics,
1447 [metric(WorsenedMetricKind::Cyclomatic, 100.0, 103.0)]
1448 );
1449 let below = attribution(vec![finding("f", 1, 20, 5)], &[finding("f", 1, 20, 9)]);
1451 assert!(!below[0].exceeded_metric_grew);
1452 }
1453
1454 #[test]
1455 fn severity_tier_uses_the_base_values_not_todays_thresholds() {
1456 let mut head = finding("f", 1, 18, 10);
1460 head.violation.exceeded = ExceededThreshold::Both;
1461 assert_eq!(
1462 classify(vec![finding("f", 1, 17, 10)], &[head.clone()]),
1463 [false]
1464 );
1465 head.violation.cognitive = 11;
1467 assert_eq!(classify(vec![finding("f", 1, 17, 10)], &[head]), [true]);
1468 }
1469
1470 #[test]
1471 fn measured_crap_tier_crossing_is_introduced() {
1472 let istanbul = Some(CoverageSource::Istanbul);
1473 let mut base = crap_finding(Some(40.0), istanbul);
1474 base.violation.severity = FindingSeverity::Moderate;
1475 let mut head = crap_finding(Some(120.0), istanbul);
1476 head.violation.severity = FindingSeverity::Critical;
1477 assert_eq!(classify(vec![base.clone()], &[head.clone()]), [true]);
1478 let estimated = Some(CoverageSource::Estimated);
1480 base.violation.coverage_source = estimated;
1481 head.violation.coverage_source = estimated;
1482 assert_eq!(classify(vec![base], &[head]), [false]);
1483 }
1484
1485 #[test]
1486 fn grown_exceeded_metric_is_introduced_with_values() {
1487 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 1, 40, 16)]);
1488 assert_eq!(
1489 classes[0].attribution(),
1490 AuditFindingAttribution::Introduced
1491 );
1492 assert_eq!(
1493 classes[0].worsened_metrics,
1494 [metric(WorsenedMetricKind::Cyclomatic, 17.0, 40.0)]
1495 );
1496 assert!(!classes[0].is_worsened());
1497 }
1498
1499 #[test]
1500 fn improved_and_moved_functions_are_inherited() {
1501 let improved = attribution(
1502 vec![with_lines(finding("f", 1, 30, 30), 90)],
1503 &[with_lines(finding("f", 1, 20, 18), 60)],
1504 );
1505 assert_eq!(
1506 improved[0].attribution(),
1507 AuditFindingAttribution::Inherited
1508 );
1509 assert!(improved[0].worsened_metrics.is_empty());
1510 let moved = attribution(vec![finding("f", 1, 17, 16)], &[finding("f", 400, 17, 16)]);
1511 assert_eq!(moved[0].attribution(), AuditFindingAttribution::Inherited);
1512 }
1513
1514 #[test]
1515 fn new_function_is_introduced_without_values() {
1516 let classes = attribution(vec![finding("f", 1, 17, 16)], &[finding("g", 1, 17, 16)]);
1517 assert_eq!(
1518 classes[0].attribution(),
1519 AuditFindingAttribution::Introduced
1520 );
1521 assert!(classes[0].worsened_metrics.is_empty());
1522 }
1523
1524 #[test]
1525 fn crap_compares_only_when_both_sides_have_a_score() {
1526 let mut head = finding("f", 1, 20, 5);
1527 head.violation.crap = Some(50.0);
1528 let classes = attribution(vec![finding("f", 1, 20, 5)], std::slice::from_ref(&head));
1529 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1530 let mut base = finding("f", 1, 20, 5);
1531 base.violation.crap = Some(40.0);
1532 let classes = attribution(vec![base], &[head]);
1533 assert_eq!(
1534 classes[0].worsened_metrics,
1535 [metric(WorsenedMetricKind::Crap, 40.0, 50.0)]
1536 );
1537 }
1538
1539 #[test]
1540 fn same_named_findings_prefer_the_base_with_equal_line_count() {
1541 let base = vec![
1543 with_lines(finding("run", 1, 17, 16), 10),
1544 with_lines(finding("run", 30, 17, 16), 40),
1545 ];
1546 let head = [
1547 with_lines(finding("run", 1, 17, 16), 40),
1548 with_lines(finding("run", 50, 17, 16), 25),
1549 ];
1550 let classes = attribution(base, &head);
1551 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1554 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Worsened);
1555 }
1556
1557 #[test]
1558 fn an_exact_match_of_a_later_head_is_not_taken_by_an_earlier_head() {
1559 let base = vec![
1562 with_lines(finding("run", 1, 17, 16), 40),
1563 with_lines(finding("run", 50, 17, 16), 10),
1564 ];
1565 let head = [
1566 with_lines(finding("run", 1, 17, 16), 30),
1567 with_lines(finding("run", 20, 17, 16), 40),
1568 ];
1569 let classes = attribution(base, &head);
1570 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1571 assert_eq!(
1572 classes[0].worsened_metrics,
1573 [metric(WorsenedMetricKind::LineCount, 10.0, 30.0)]
1574 );
1575 assert_eq!(classes[1].attribution(), AuditFindingAttribution::Inherited);
1576 assert!(classes[1].worsened_metrics.is_empty());
1577 }
1578
1579 #[test]
1580 fn small_line_growth_is_not_worsened() {
1581 let classes = attribution(
1583 vec![with_lines(finding("f", 1, 17, 16), 80)],
1584 &[with_lines(finding("f", 1, 17, 16), 84)],
1585 );
1586 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1587 assert!(classes[0].worsened_metrics.is_empty());
1588 }
1589
1590 #[test]
1591 fn line_growth_needs_five_lines_at_any_function_size() {
1592 let short = attribution(
1594 vec![with_lines(finding("f", 1, 17, 16), 20)],
1595 &[with_lines(finding("f", 1, 17, 16), 24)],
1596 );
1597 assert_eq!(short[0].attribution(), AuditFindingAttribution::Inherited);
1598 let grown = attribution(
1599 vec![with_lines(finding("f", 1, 17, 16), 20)],
1600 &[with_lines(finding("f", 1, 17, 16), 25)],
1601 );
1602 assert_eq!(grown[0].attribution(), AuditFindingAttribution::Worsened);
1603 let long = attribution(
1605 vec![with_lines(finding("f", 1, 17, 16), 300)],
1606 &[with_lines(finding("f", 1, 17, 16), 309)],
1607 );
1608 assert_eq!(long[0].attribution(), AuditFindingAttribution::Worsened);
1609 }
1610
1611 #[test]
1612 fn a_base_with_the_same_values_keeps_the_finding_inherited() {
1613 let primary = baseline(vec![with_lines(finding("f", 1, 17, 16), 20)]);
1614 let merged = baseline(vec![with_lines(finding("f", 1, 17, 16), 60)]);
1615 let head = [with_lines(finding("f", 1, 17, 16), 60)];
1616 let classes =
1617 classify_complexity_attribution_against_all(&head, &root(), [&primary, &merged]);
1618 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Inherited);
1619 let classes = classify_complexity_attribution_against_all(&head, &root(), [&primary]);
1620 assert_eq!(classes[0].attribution(), AuditFindingAttribution::Worsened);
1621 }
1622
1623 #[test]
1624 fn rename_moves_the_base_findings() {
1625 let base = baseline(vec![finding("f", 1, 17, 16)]);
1626 let renames =
1627 FxHashMap::from_iter([("src/index.js".to_string(), "src/moved.js".to_string())]);
1628 let remapped = remap_complexity_baseline_for_renames(base, &renames);
1629 assert!(remapped.contains_key("complexity:src/moved.js:f"));
1630 assert!(!remapped.contains_key("complexity:src/index.js:f"));
1631 }
1632
1633 #[test]
1634 fn ledger_keys_count_same_named_findings_separately() {
1635 let keys = complexity_ledger_keys(
1636 &[finding("run", 1, 17, 16), finding("run", 30, 17, 16)],
1637 &root(),
1638 );
1639 assert_eq!(
1640 keys,
1641 [
1642 "complexity:src/index.js:run",
1643 "complexity:src/index.js:run#2"
1644 ]
1645 );
1646 }
1647}