1use rustc_hash::{FxHashMap, FxHashSet};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct LineHit {
12 pub line: u32,
14 pub evidence: String,
16}
17
18const TEST_CASE_ROOTS: &[&str] = &["it", "test", "specify", "xit", "xtest", "fit"];
20const SUITE_ROOTS: &[&str] = &["describe", "suite", "context"];
22const PREFIXED_ROOTS: &[&str] = &["xit", "xtest", "xdescribe", "fit", "fdescribe"];
24const TEST_CASE_MEMBERS: &[&str] = &[
26 "skip",
27 "only",
28 "each",
29 "todo",
30 "concurrent",
31 "sequential",
32 "fails",
33 "failing",
34 "fixme",
35 "skipIf",
36 "runIf",
37 "effect",
41 "live",
42 "scoped",
43 "scopedLive",
44 "prop",
45];
46const EXPECT_ASSERTION_MEMBERS: &[&str] = &["soft", "poll"];
48
49const SUPPRESSION_TOKENS: &[&str] = &[
51 "eslint-disable",
52 "oxlint-disable",
53 "biome-ignore",
54 "deno-lint-ignore",
55 "@ts-ignore",
56 "@ts-expect-error",
57 "@ts-nocheck",
58 "istanbul ignore",
59 "c8 ignore",
60 "v8 ignore",
61];
62pub(crate) const FALLOW_IGNORE_TOKEN: &str = "fallow-ignore";
63const DIFF_RISK_TOKENS: &[&str] = &[
67 "weakened-tests",
68 "added-suppression",
69 "test-only-branch",
70 "diverged-clone-sibling",
71 "added-dependency",
72];
73
74const MIN_THRESHOLD_KEYS: &[&str] = &[
76 "branches",
77 "functions",
78 "lines",
79 "statements",
80 "minScore",
81 "min-score",
82 "minCoverage",
83 "min-coverage",
84];
85const MAX_THRESHOLD_KEYS: &[&str] = &[
87 "maxCrap",
88 "max-crap",
89 "maxCyclomatic",
90 "max-cyclomatic",
91 "maxCognitive",
92 "max-cognitive",
93];
94
95#[must_use]
100pub fn added_lines<'a>(base: &str, head: &'a str) -> Vec<(u32, &'a str)> {
101 let mut remaining: FxHashMap<&str, usize> = FxHashMap::default();
102 for line in base.lines() {
103 *remaining.entry(line.trim()).or_default() += 1;
104 }
105 let mut head_counts: FxHashMap<&str, usize> = FxHashMap::default();
106 for line in head.lines() {
107 *head_counts.entry(line.trim()).or_default() += 1;
108 }
109 let mut kept: FxHashMap<&str, usize> = head_counts
111 .iter()
112 .map(|(text, count)| {
113 let in_base = remaining.get(text).copied().unwrap_or(0);
114 (*text, (*count).min(in_base))
115 })
116 .collect();
117 let mut added = Vec::new();
118 for (index, line) in head.lines().enumerate() {
119 let text = line.trim();
120 if text.is_empty() {
121 continue;
122 }
123 let keep = kept.entry(text).or_default();
124 if *keep > 0 {
125 *keep -= 1;
126 continue;
127 }
128 added.push((line_number(index), line));
129 }
130 added
131}
132
133#[must_use]
137pub fn code_identifiers(src: &str) -> FxHashSet<String> {
138 let mut found = FxHashSet::default();
139 for line in src.lines() {
140 let code = blank_string_literals(code_part(line));
141 found.extend(
142 code.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '$'))
143 .filter(|token| {
144 token
145 .bytes()
146 .next()
147 .is_some_and(|byte| !byte.is_ascii_digit())
148 })
149 .map(str::to_owned),
150 );
151 }
152 found
153}
154
155#[must_use]
157pub fn skip_only_hits(base: &str, head: &str) -> Vec<LineHit> {
158 let mut hits = Vec::new();
159 for (line, text) in added_lines(base, head) {
160 for chain in call_chains(code_part(text)) {
161 if is_skip_or_focus(&chain) {
162 hits.push(LineHit {
163 line,
164 evidence: chain.join("."),
165 });
166 break;
167 }
168 }
169 }
170 hits
171}
172
173#[must_use]
175pub fn test_case_count(src: &str) -> usize {
176 src.lines()
177 .flat_map(|line| call_chains(code_part(line)))
178 .filter(|chain| is_test_case(chain))
179 .count()
180}
181
182#[must_use]
185pub fn assertion_count(src: &str) -> usize {
186 src.lines()
187 .map(|line| {
188 let code = code_part(line);
189 let chains = call_chains(code)
190 .into_iter()
191 .filter(|chain| is_assertion(chain))
192 .count();
193 chains + member_should_count(code)
194 })
195 .sum()
196}
197
198#[must_use]
201pub fn removed_assertion_lines(base: &str, head: &str) -> (usize, usize) {
202 added_lines(head, base)
203 .into_iter()
204 .filter(|(_, line)| !code_part(line).trim().is_empty())
205 .fold((0, 0), |(asserts, code), (_, line)| {
206 (asserts + usize::from(assertion_count(line) > 0), code + 1)
207 })
208}
209
210#[must_use]
212pub fn added_suppression_hits(base: &str, head: &str) -> Vec<LineHit> {
213 added_lines(base, head)
214 .into_iter()
215 .filter_map(|(line, text)| {
216 let comment = comment_part(text)?;
217 suppression_token(comment).map(|token| LineHit {
218 line,
219 evidence: token.to_owned(),
220 })
221 })
222 .collect()
223}
224
225#[must_use]
228pub fn test_only_branch_hits(base: &str, head: &str) -> Vec<LineHit> {
229 let head_lines: Vec<&str> = head.lines().collect();
230 added_lines(base, head)
231 .into_iter()
232 .filter_map(|(line, text)| {
233 let code = code_part(text);
234 let token = test_environment_token(code)?;
235 if picks_env_file(code) || only_quiets_logs(&head_lines, line) {
236 return None;
237 }
238 Some(LineHit {
239 line,
240 evidence: token.to_owned(),
241 })
242 })
243 .collect()
244}
245
246fn picks_env_file(code: &str) -> bool {
250 ["'.env", "\".env", "`.env"]
251 .iter()
252 .any(|literal| code.contains(literal))
253}
254
255const MAX_GUARDED_LINES: usize = 12;
257
258fn only_quiets_logs(lines: &[&str], line: u32) -> bool {
261 let index = usize::try_from(line).unwrap_or(0).saturating_sub(1);
262 let Some(check) = lines.get(index) else {
263 return false;
264 };
265 let check = blank_string_literals(code_part(check));
266 if !check.contains("!=") {
267 return false;
268 }
269 if check.contains("console.") {
270 return true;
271 }
272 let mut body = lines
273 .iter()
274 .skip(index + 1)
275 .take(MAX_GUARDED_LINES)
276 .map(|line| code_part(line).trim())
277 .filter(|code| !code.is_empty() && !matches!(*code, "{" | ") {" | ")"));
278 if !body
279 .next()
280 .is_some_and(|first| first.starts_with("console."))
281 {
282 return false;
283 }
284 for code in body {
287 if code.starts_with('}') {
288 return true;
289 }
290 let continues = code.starts_with("console.")
291 || code.starts_with(['\'', '"', '`', ')', ','])
292 || code.ends_with(',');
293 if !continues {
294 return false;
295 }
296 }
297 false
298}
299
300#[must_use]
303pub fn weakened_threshold_hits(base: &str, head: &str) -> Vec<LineHit> {
304 let mut hits = Vec::new();
305 for (keys, lower_is_weaker) in [(MIN_THRESHOLD_KEYS, true), (MAX_THRESHOLD_KEYS, false)] {
306 for key in keys {
307 let base_values = numeric_values_for_key(base, key);
308 let head_values = numeric_values_for_key(head, key);
309 for ((base_value, _), (head_value, head_line)) in
310 base_values.iter().zip(head_values.iter())
311 {
312 let weaker = if lower_is_weaker {
313 head_value < base_value
314 } else {
315 head_value > base_value
316 };
317 if weaker {
318 hits.push(LineHit {
319 line: *head_line,
320 evidence: format!("{key}: {base_value} -> {head_value}"),
321 });
322 }
323 }
324 }
325 }
326 hits.sort_by_key(|hit| hit.line);
327 hits
328}
329
330#[must_use]
332pub fn is_coverage_config_path(rel_path: &str) -> bool {
333 let name = rel_path.rsplit('/').next().unwrap_or(rel_path);
334 if rel_path.contains("node_modules/") {
335 return false;
336 }
337 const EXACT: &[&str] = &[
338 "package.json",
339 ".nycrc",
340 ".nycrc.json",
341 ".nycrc.yml",
342 ".nycrc.yaml",
343 ".c8rc",
344 ".c8rc.json",
345 ".fallowrc.json",
346 ".fallowrc.jsonc",
347 "fallow.toml",
348 ".fallow.toml",
349 ];
350 const PREFIXES: &[&str] = &[
351 "vitest.config.",
352 "vitest.workspace.",
353 "vite.config.",
354 "jest.config.",
355 "karma.conf.",
356 "playwright.config.",
357 ];
358 EXACT.contains(&name) || PREFIXES.iter().any(|prefix| name.starts_with(prefix))
359}
360
361fn line_number(index: usize) -> u32 {
362 u32::try_from(index + 1).unwrap_or(u32::MAX)
363}
364
365fn code_part(line: &str) -> &str {
368 let trimmed = line.trim_start();
369 if trimmed.starts_with("//")
370 || trimmed.starts_with("/*")
371 || trimmed.starts_with('*')
372 || trimmed.starts_with("<!--")
373 {
374 return "";
375 }
376 match comment_start(line) {
377 Some(start) => &line[..start],
378 None => line,
379 }
380}
381
382fn comment_part(line: &str) -> Option<&str> {
384 let trimmed = line.trim_start();
385 if trimmed.starts_with('*') || trimmed.starts_with('#') {
386 return Some(trimmed);
387 }
388 comment_start(line).map(|start| &line[start..])
389}
390
391fn comment_start(line: &str) -> Option<usize> {
396 let code = blank_string_literals(line);
397 let bytes = code.as_bytes();
398 let mut index = 0;
399 let mut script = None;
400 while index + 1 < bytes.len() {
401 let pair = (bytes[index], bytes[index + 1]);
402 let is_line_comment = pair == (b'/', b'/') && (index == 0 || bytes[index - 1] != b':');
403 if is_line_comment || pair == (b'/', b'*') {
404 script = Some(index);
405 break;
406 }
407 index += 1;
408 }
409 let markup = line.find("<!--");
410 match (script, markup) {
411 (Some(a), Some(b)) => Some(a.min(b)),
412 (a, b) => a.or(b),
413 }
414}
415
416const fn is_ident_byte(byte: u8) -> bool {
417 byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$'
418}
419
420fn call_chains(code: &str) -> Vec<Vec<&str>> {
424 let bytes = code.as_bytes();
425 let mut chains = Vec::new();
426 let mut index = 0;
427 while index < bytes.len() {
428 let starts_ident = is_ident_byte(bytes[index])
429 && !bytes[index].is_ascii_digit()
430 && (index == 0 || (!is_ident_byte(bytes[index - 1]) && bytes[index - 1] != b'.'));
431 if !starts_ident {
432 index += 1;
433 continue;
434 }
435 let mut chain = Vec::new();
436 let mut cursor = index;
437 loop {
438 let start = cursor;
439 while cursor < bytes.len() && is_ident_byte(bytes[cursor]) {
440 cursor += 1;
441 }
442 chain.push(&code[start..cursor]);
443 if cursor + 1 < bytes.len() && bytes[cursor] == b'.' && is_ident_byte(bytes[cursor + 1])
444 {
445 cursor += 1;
446 continue;
447 }
448 break;
449 }
450 let next = code[cursor..].trim_start().bytes().next();
451 if matches!(next, Some(b'(' | b'`')) {
452 chains.push(chain);
453 }
454 index = cursor.max(index + 1);
455 }
456 chains
457}
458
459fn is_skip_or_focus(chain: &[&str]) -> bool {
460 let Some(root) = chain.first() else {
461 return false;
462 };
463 if PREFIXED_ROOTS.contains(root) {
464 return true;
465 }
466 (TEST_CASE_ROOTS.contains(root) || SUITE_ROOTS.contains(root))
467 && chain[1..]
468 .iter()
469 .any(|member| matches!(*member, "skip" | "only"))
470}
471
472fn is_test_case(chain: &[&str]) -> bool {
473 chain
474 .first()
475 .is_some_and(|root| TEST_CASE_ROOTS.contains(root))
476 && chain[1..]
477 .iter()
478 .all(|member| TEST_CASE_MEMBERS.contains(member))
479}
480
481fn is_assertion(chain: &[&str]) -> bool {
482 match chain {
483 ["expect"] | ["should" | "assert", ..] => true,
484 ["expect", member] => EXPECT_ASSERTION_MEMBERS.contains(member),
485 _ => false,
486 }
487}
488
489fn member_should_count(code: &str) -> usize {
491 code.match_indices(".should")
492 .filter(|(start, token)| {
493 let after = code.as_bytes().get(start + token.len()).copied();
494 matches!(after, Some(b'.' | b'('))
495 })
496 .count()
497}
498
499fn suppression_token(comment: &str) -> Option<&'static str> {
502 let generic = SUPPRESSION_TOKENS
503 .iter()
504 .filter_map(|token| comment.find(token).map(|at| (at, *token)))
505 .min_by_key(|(at, _)| *at);
506 let fallow = comment
507 .find(FALLOW_IGNORE_TOKEN)
508 .filter(|at| !names_only_diff_risk_rules(&comment[*at..]))
509 .map(|at| (at, FALLOW_IGNORE_TOKEN));
510 [generic, fallow]
511 .into_iter()
512 .flatten()
513 .min_by_key(|(at, _)| *at)
514 .map(|(_, token)| token)
515}
516
517fn names_only_diff_risk_rules(directive: &str) -> bool {
520 let body = directive
521 .split_once("--")
522 .map_or(directive, |(tokens, _reason)| tokens);
523 let body = body
524 .trim_end()
525 .trim_end_matches("*/")
526 .trim_end_matches("-->");
527 let mut words = body.split_whitespace();
528 words.next();
530 let tokens: Vec<&str> = words
531 .flat_map(|word| word.split(','))
532 .filter(|token| !token.is_empty())
533 .collect();
534 !tokens.is_empty() && tokens.iter().all(|token| DIFF_RISK_TOKENS.contains(token))
535}
536
537fn test_environment_token(code: &str) -> Option<&'static str> {
539 let outside = blank_string_literals(code);
544 for token in ["process.env.VITEST", "process.env.JEST_WORKER_ID"] {
545 if outside.contains(token) {
546 return Some(token);
547 }
548 }
549 let compares_test = ["'test'", "\"test\"", "`test`"]
550 .iter()
551 .any(|literal| code.contains(literal))
552 && (outside.contains("==") || outside.contains("!="));
553 (outside.contains("process.env.NODE_ENV") && compares_test).then_some("process.env.NODE_ENV")
554}
555
556fn blank_string_literals(code: &str) -> String {
561 let mut out = String::with_capacity(code.len());
562 let mut quote: Option<char> = None;
563 let mut escaped = false;
564 for c in code.chars() {
565 let Some(open) = quote else {
566 if matches!(c, '\'' | '"' | '`') {
567 quote = Some(c);
568 }
569 out.push(c);
570 continue;
571 };
572 if c == open && !escaped {
573 quote = None;
574 out.push(c);
575 continue;
576 }
577 escaped = !escaped && c == '\\';
578 out.extend(std::iter::repeat_n(' ', c.len_utf8()));
579 }
580 out
581}
582
583fn numeric_values_for_key(src: &str, key: &str) -> Vec<(f64, u32)> {
586 let mut values = Vec::new();
587 let mut line = 1u32;
588 let mut scanned = 0;
589 let mut search_from = 0;
590 while let Some(relative) = src[search_from..].find(key) {
591 let start = search_from + relative;
592 let end = start + key.len();
593 search_from = end;
594 let before = src[..start].bytes().next_back();
595 let after = src.as_bytes().get(end).copied();
596 let stands_alone = !before.is_some_and(|byte| is_ident_byte(byte) || byte == b'-')
597 && !after.is_some_and(|byte| is_ident_byte(byte) || byte == b'-');
598 if !stands_alone {
599 continue;
600 }
601 let rest = src[end..]
602 .trim_start_matches(['"', '\''])
603 .trim_start_matches([' ', '\t']);
604 let Some(rest) = rest.strip_prefix([':', '=']) else {
605 continue;
606 };
607 let rest = rest.trim_start_matches([' ', '\t', '"', '\'']);
608 let number: String = rest
609 .chars()
610 .take_while(|c| c.is_ascii_digit() || *c == '.' || *c == '-')
611 .collect();
612 let Ok(value) = number.parse::<f64>() else {
613 continue;
614 };
615 line += u32::try_from(src[scanned..start].matches('\n').count()).unwrap_or(0);
616 scanned = start;
617 values.push((value, line));
618 }
619 values
620}
621
622#[cfg(test)]
623mod tests {
624 use super::*;
625
626 #[test]
627 fn explain_text_names_every_detected_suppression_token() {
628 let full = crate::explain::AUDIT_RULES
629 .iter()
630 .find(|rule| rule.id == "fallow/added-suppression")
631 .map(|rule| rule.full)
632 .unwrap_or_default();
633 for token in SUPPRESSION_TOKENS.iter().chain([&FALLOW_IGNORE_TOKEN]) {
634 assert!(
635 full.contains(&format!("`{token}`")),
636 "the added-suppression explain text must name `{token}`"
637 );
638 }
639 }
640
641 #[test]
642 fn added_lines_ignore_moved_lines() {
643 let base = "a\nb\nc\n";
644 let head = "c\na\nb\nd\n";
645 assert_eq!(added_lines(base, head), vec![(4, "d")]);
646 }
647
648 #[test]
649 fn added_skip_and_only_markers_are_hits_at_their_line() {
650 let base = "it('a', () => {});\ntest('b', () => {});\n";
651 let head = "it.skip('a', () => {});\ntest.only('b', () => {});\nxit('c', f);\n";
652 let hits = skip_only_hits(base, head);
653 let evidence: Vec<(u32, &str)> = hits
654 .iter()
655 .map(|hit| (hit.line, hit.evidence.as_str()))
656 .collect();
657 assert_eq!(evidence, vec![(1, "it.skip"), (2, "test.only"), (3, "xit")]);
658 }
659
660 #[test]
661 fn existing_or_commented_skip_markers_are_not_hits() {
662 let base = "it.skip('a', () => {});\n";
663 let head = "// it.only('x')\nit.skip('a', () => {});\nconst profit = fit2(1);\n";
664 assert!(skip_only_hits(base, head).is_empty());
665 }
666
667 #[test]
668 fn test_case_count_counts_cases_with_modifiers_only() {
669 let src = "describe('s', () => {\n it('a', f);\n it.skip('b', f);\n test.each([1])('c', f);\n test.describe('d', f);\n submit(1);\n // it('commented', f);\n});\n";
670 assert_eq!(test_case_count(src), 3);
671 }
672
673 #[test]
674 fn test_case_count_counts_effect_vitest_members() {
675 let src = "it.effect('a', f);\nit.live('b', f);\nit.scoped('c', f);\nit.scopedLive('d', f);\nit.prop('e', arbs, f);\nit.effect.skip('f', f);\nit.effect.each([1])('g', f);\nit.effect.prop('h', arbs, f);\nit.layer(Live)('i', f);\nit.flakyTest(eff);\n";
676 assert_eq!(test_case_count(src), 8);
677 }
678
679 #[test]
680 fn test_case_count_needs_a_test_root_for_effect_vitest_members() {
681 let src = "foo.live('a', f);\ndescribe.scoped('b', f);\nlayer.effect('c', f);\n";
682 assert_eq!(test_case_count(src), 0);
683 }
684
685 #[test]
686 fn assertion_count_counts_expect_assert_and_should() {
687 let src = "expect(a).toBe(1);\nexpect.soft(b).toBe(2);\nassert.equal(c, 3);\nassert(d);\nx.should.equal(4);\nexpect.assertions(2);\n// expect(e)\n";
688 assert_eq!(assertion_count(src), 5);
689 }
690
691 #[test]
692 fn added_suppression_comments_are_hits() {
693 let base = "const a = 1;\n// eslint-disable-next-line no-console\nconsole.log(a);\n";
694 let head = "// @ts-ignore\nconst a = 1;\n// eslint-disable-next-line no-console\nconsole.log(a);\n/* istanbul ignore next */\nconst s = 'eslint-disable';\n";
695 let hits = added_suppression_hits(base, head);
696 let evidence: Vec<(u32, &str)> = hits
697 .iter()
698 .map(|hit| (hit.line, hit.evidence.as_str()))
699 .collect();
700 assert_eq!(evidence, vec![(1, "@ts-ignore"), (5, "istanbul ignore")]);
701 }
702
703 #[test]
704 fn fallow_ignore_that_names_only_diff_risk_rules_is_not_an_added_suppression() {
705 let head = "// fallow-ignore-next-line weakened-tests\nit.skip('a', f);\n// fallow-ignore-next-line unused-export\nexport const b = 1;\n// fallow-ignore-file\n";
706 let hits = added_suppression_hits("", head);
707 let lines: Vec<u32> = hits.iter().map(|hit| hit.line).collect();
708 assert_eq!(lines, vec![3, 5]);
709 }
710
711 #[test]
712 fn comment_markers_inside_string_literals_are_not_suppressions() {
713 let head = "out.push('/* eslint-disable */');\nout.push(\"// @ts-nocheck\");\nconst u = 'it\\'s'; // @ts-ignore\n<!-- eslint-disable -->\n";
714 let hits = added_suppression_hits("", head);
715 let evidence: Vec<(u32, &str)> = hits
716 .iter()
717 .map(|hit| (hit.line, hit.evidence.as_str()))
718 .collect();
719 assert_eq!(evidence, vec![(3, "@ts-ignore"), (4, "eslint-disable")]);
720 }
721
722 #[test]
723 fn multibyte_characters_before_a_comment_do_not_panic() {
724 let head = "const name = 'café'; // @ts-ignore\nconst ünï = 1;\n";
725 let hits = added_suppression_hits("", head);
726 assert_eq!(hits.len(), 1);
727 assert_eq!(hits[0].line, 1);
728 }
729
730 #[test]
731 fn quiet_logs_in_tests_are_not_hits() {
732 let head = "if (process.env.NODE_ENV !== 'test') {\n console.error(message);\n}\nif (\n status !== 'ok' &&\n process.env.NODE_ENV !== 'test'\n) {\n console.warn(\n `not scheduled`,\n );\n}\nif (process.env.NODE_ENV !== 'test') {\n sendMetrics();\n}\n";
733 let lines: Vec<u32> = test_only_branch_hits("", head)
734 .iter()
735 .map(|hit| hit.line)
736 .collect();
737 assert_eq!(lines, vec![12]);
738 }
739
740 #[test]
741 fn test_env_file_selection_is_not_a_hit() {
742 let head = "config({ path: process.env.NODE_ENV === 'test' ? '.env.test' : '.env' });\nconst key = process.env.NODE_ENV === 'test' ? 'test:' : '';\n";
743 let lines: Vec<u32> = test_only_branch_hits("", head)
744 .iter()
745 .map(|hit| hit.line)
746 .collect();
747 assert_eq!(lines, vec![2]);
748 }
749
750 #[test]
751 fn added_test_environment_branches_are_hits() {
752 let head = "if (process.env.NODE_ENV === 'test') return;\nif (process.env.NODE_ENV === 'production') x();\nconst w = process.env.JEST_WORKER_ID;\nif (process.env.VITEST) y();\n// process.env.VITEST\n";
753 let lines: Vec<u32> = test_only_branch_hits("", head)
754 .iter()
755 .map(|hit| hit.line)
756 .collect();
757 assert_eq!(lines, vec![1, 3, 4]);
758 }
759
760 #[test]
761 fn vitest_in_source_test_block_is_not_a_hit() {
762 let head = "export const add = (a, b) => a + b;\nif (import.meta.vitest) {\n const { it, expect } = import.meta.vitest;\n it('adds', () => expect(add(1, 2)).toBe(3));\n}\n";
763 assert!(test_only_branch_hits("", head).is_empty());
764 }
765
766 #[test]
767 fn test_environment_tokens_inside_strings_are_not_hits() {
768 let head = "return code.slice(a, b) === 'import.meta.vitest'\nconst m = `inside the \\`if (import.meta.vitest)\\` block`;\nconst s = \"process.env.VITEST\";\n";
769 assert!(test_only_branch_hits("", head).is_empty());
770 }
771
772 #[test]
773 fn lowered_min_threshold_and_raised_max_threshold_are_hits() {
774 let base = "thresholds: {\n lines: 90,\n branches: 80,\n},\nmaxCrap: 30,\n";
775 let head = "thresholds: {\n lines: 70,\n branches: 85,\n},\nmaxCrap: 45,\n";
776 let hits = weakened_threshold_hits(base, head);
777 let evidence: Vec<(u32, &str)> = hits
778 .iter()
779 .map(|hit| (hit.line, hit.evidence.as_str()))
780 .collect();
781 assert_eq!(
782 evidence,
783 vec![(2, "lines: 90 -> 70"), (5, "maxCrap: 30 -> 45")]
784 );
785 }
786
787 #[test]
788 fn json_thresholds_are_compared_by_key() {
789 let base = r#"{"jest": {"coverageThreshold": {"global": {"statements": 95}}}}"#;
790 let head = r#"{"jest": {"coverageThreshold": {"global": {"statements": 50}}}}"#;
791 let hits = weakened_threshold_hits(base, head);
792 assert_eq!(hits.len(), 1);
793 assert_eq!(hits[0].evidence, "statements: 95 -> 50");
794 }
795
796 #[test]
797 fn coverage_config_paths() {
798 assert!(is_coverage_config_path("vitest.config.ts"));
799 assert!(is_coverage_config_path("packages/a/jest.config.js"));
800 assert!(is_coverage_config_path("package.json"));
801 assert!(is_coverage_config_path(".nycrc.json"));
802 assert!(is_coverage_config_path(".fallowrc.json"));
803 assert!(!is_coverage_config_path("src/lines.ts"));
804 }
805}