Skip to main content

lean_ctx_patterns/
test.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use crate::ansi::strip_ansi;
4
5pub fn compress(output: &str) -> Option<String> {
6    // node:test first: its `ℹ tests N` / `# tests N` summary is the most
7    // specific signal, and its test titles may contain words other parsers
8    // key on ("passing", "pytest", "running ").
9    if let Some(r) = try_node_test(output) {
10        return Some(r);
11    }
12    if let Some(r) = try_cargo_test(output) {
13        return Some(r);
14    }
15    if let Some(r) = try_pytest(output) {
16        return Some(r);
17    }
18    if let Some(r) = try_vitest(output) {
19        return Some(r);
20    }
21    if let Some(r) = try_jest(output) {
22        return Some(r);
23    }
24    if let Some(r) = try_go_test(output) {
25        return Some(r);
26    }
27    if let Some(r) = try_rspec(output) {
28        return Some(r);
29    }
30    if let Some(r) = try_mocha(output) {
31        return Some(r);
32    }
33    None
34}
35
36fn try_cargo_test(output: &str) -> Option<String> {
37    if !output.contains("test result:") && !output.contains("running ") {
38        return None;
39    }
40    if !output.contains(" passed") {
41        return None;
42    }
43
44    let mut total_passed = 0u32;
45    let mut total_failed = 0u32;
46    let mut total_ignored = 0u32;
47    let mut total_filtered = 0u32;
48    let mut time = String::new();
49    let mut failures: Vec<String> = Vec::new();
50    let mut passed_names: Vec<String> = Vec::new();
51    let mut suites = 0u32;
52
53    for line in output.lines() {
54        let trimmed = line.trim();
55        if trimmed.starts_with("test result:") {
56            suites += 1;
57            for part in trimmed.split(';') {
58                let part = part.trim();
59                if let Some(n) = extract_cargo_counter(part, "passed") {
60                    total_passed += n;
61                } else if let Some(n) = extract_cargo_counter(part, "failed") {
62                    total_failed += n;
63                } else if let Some(n) = extract_cargo_counter(part, "ignored") {
64                    total_ignored += n;
65                } else if let Some(n) = extract_cargo_counter(part, "filtered out") {
66                    total_filtered += n;
67                }
68            }
69            if let Some(pos) = trimmed.find("finished in ") {
70                time = trimmed[pos + 12..].trim().to_string();
71            }
72        }
73        if trimmed.starts_with("test ") && trimmed.ends_with("... ok") {
74            if let Some(name) = trimmed
75                .strip_prefix("test ")
76                .and_then(|r| r.strip_suffix(" ... ok"))
77            {
78                passed_names.push(name.to_string());
79            }
80        }
81        if (trimmed.starts_with("test ") && trimmed.ends_with("... FAILED"))
82            || trimmed.starts_with("---- ")
83                && trimmed.ends_with(" ----")
84                && !trimmed.contains("output")
85        {
86            let name = if let Some(rest) = trimmed.strip_prefix("test ") {
87                rest.strip_suffix(" ... FAILED").unwrap_or(rest)
88            } else {
89                trimmed.trim_start_matches('-').trim_end_matches('-').trim()
90            };
91            if !name.is_empty() && !failures.iter().any(|f| f == name) {
92                failures.push(name.to_string());
93            }
94        }
95    }
96
97    if total_passed == 0 && total_failed == 0 {
98        return None;
99    }
100
101    let mut result = format!("cargo test: {total_passed} passed");
102    if total_failed > 0 {
103        result.push_str(&format!(", {total_failed} failed"));
104    }
105    if total_ignored > 0 {
106        result.push_str(&format!(", {total_ignored} ignored"));
107    }
108    if total_filtered > 0 {
109        result.push_str(&format!(", {total_filtered} filtered"));
110    }
111    if suites > 1 {
112        result.push_str(&format!(" ({suites} suites)"));
113    }
114    if !time.is_empty() {
115        result.push_str(&format!(" [{time}]"));
116    }
117
118    for f in failures.iter().take(10) {
119        result.push_str(&format!("\n  FAIL: {f}"));
120    }
121
122    Some(result)
123}
124
125fn extract_cargo_counter(segment: &str, keyword: &str) -> Option<u32> {
126    let pos = segment.find(keyword)?;
127    let before = segment[..pos].trim();
128    let num_str = before.split_whitespace().last()?;
129    num_str.parse::<u32>().ok()
130}
131
132fn try_pytest(output: &str) -> Option<String> {
133    if !output.contains("test session starts") && !output.contains("pytest") {
134        return None;
135    }
136
137    let mut passed = 0u32;
138    let mut failed = 0u32;
139    let mut skipped = 0u32;
140    let mut xfailed = 0u32;
141    let mut xpassed = 0u32;
142    let mut warnings = 0u32;
143    let mut time = String::new();
144    let mut failures = Vec::new();
145    let mut passed_names = Vec::new();
146
147    for line in output.lines() {
148        let trimmed = line.trim();
149        if (trimmed.contains("passed")
150            || trimmed.contains("failed")
151            || trimmed.contains("error")
152            || trimmed.contains("xfailed")
153            || trimmed.contains("xpassed")
154            || trimmed.contains("warning"))
155            && (trimmed.starts_with('=') || trimmed.starts_with('-'))
156        {
157            for word in trimmed.split_whitespace() {
158                if let Some(n) = word.strip_suffix("passed").or_else(|| {
159                    if trimmed.contains(" passed") {
160                        word.parse::<u32>().ok().map(|_| word)
161                    } else {
162                        None
163                    }
164                }) && let Ok(v) = n.trim().parse::<u32>()
165                {
166                    passed = v;
167                }
168            }
169            passed = extract_pytest_counter(trimmed, " passed").unwrap_or(passed);
170            failed = extract_pytest_counter(trimmed, " failed").unwrap_or(failed);
171            skipped = extract_pytest_counter(trimmed, " skipped").unwrap_or(skipped);
172            xfailed = extract_pytest_counter(trimmed, " xfailed").unwrap_or(xfailed);
173            xpassed = extract_pytest_counter(trimmed, " xpassed").unwrap_or(xpassed);
174            warnings = extract_pytest_counter(trimmed, " warning").unwrap_or(warnings);
175            if let Some(pos) = trimmed.find(" in ") {
176                time = trimmed[pos + 4..].trim_end_matches('=').trim().to_string();
177            }
178        }
179        if trimmed.starts_with("FAILED ") {
180            failures.push(
181                trimmed
182                    .strip_prefix("FAILED ")
183                    .unwrap_or(trimmed)
184                    .to_string(),
185            );
186        }
187        if trimmed.starts_with("PASSED ") || trimmed.ends_with(" PASSED") {
188            let name = trimmed
189                .strip_prefix("PASSED ")
190                .or_else(|| trimmed.strip_suffix(" PASSED"))
191                .unwrap_or(trimmed);
192            if name.len() <= 50 {
193                passed_names.push(name.to_string());
194            } else {
195                passed_names.push(format!("{}...", &name[..name.floor_char_boundary(47)]));
196            }
197        }
198    }
199
200    if passed == 0 && failed == 0 {
201        return None;
202    }
203
204    let mut result = format!("pytest: {passed} passed");
205    if failed > 0 {
206        result.push_str(&format!(", {failed} failed"));
207    }
208    if skipped > 0 {
209        result.push_str(&format!(", {skipped} skipped"));
210    }
211    if xfailed > 0 {
212        result.push_str(&format!(", {xfailed} xfailed"));
213    }
214    if xpassed > 0 {
215        result.push_str(&format!(", {xpassed} xpassed"));
216    }
217    if warnings > 0 {
218        result.push_str(&format!(", {warnings} warnings"));
219    }
220    if !time.is_empty() {
221        result.push_str(&format!(" ({time})"));
222    }
223
224    for f in failures.iter().take(5) {
225        result.push_str(&format!("\n  FAIL: {f}"));
226    }
227
228    if failures.is_empty() && !passed_names.is_empty() {
229        let total = passed_names.len();
230        let shown: Vec<_> = passed_names.into_iter().take(5).collect();
231        let suffix = if total > 5 {
232            format!(" ...+{} more", total - 5)
233        } else {
234            String::new()
235        };
236        result.push_str(&format!("\n  ran: {}{suffix}", shown.join(", ")));
237    }
238
239    Some(result)
240}
241
242fn extract_pytest_counter(line: &str, keyword: &str) -> Option<u32> {
243    let pos = line.find(keyword)?;
244    let before = &line[..pos];
245    let num_str = before.split_whitespace().last()?;
246    num_str.parse::<u32>().ok()
247}
248
249fn try_jest(output: &str) -> Option<String> {
250    if !output.contains("Tests:") && !output.contains("Test Suites:") {
251        return None;
252    }
253
254    let mut suites_line = String::new();
255    let mut tests_line = String::new();
256    let mut time_line = String::new();
257
258    for line in output.lines() {
259        let trimmed = line.trim();
260        if trimmed.starts_with("Test Suites:") {
261            suites_line = trimmed.to_string();
262        } else if trimmed.starts_with("Tests:") {
263            tests_line = trimmed.to_string();
264        } else if trimmed.starts_with("Time:") {
265            time_line = trimmed.to_string();
266        }
267    }
268
269    if tests_line.is_empty() {
270        return None;
271    }
272
273    let mut result = String::new();
274    if !suites_line.is_empty() {
275        result.push_str(&suites_line);
276        result.push('\n');
277    }
278    result.push_str(&tests_line);
279    if !time_line.is_empty() {
280        result.push('\n');
281        result.push_str(&time_line);
282    }
283
284    Some(result)
285}
286
287fn try_go_test(output: &str) -> Option<String> {
288    if !output.contains("--- PASS") && !output.contains("--- FAIL") && !output.contains("PASS\n") {
289        return None;
290    }
291
292    let mut passed = 0u32;
293    let mut failed = 0u32;
294    let mut failures = Vec::new();
295    let mut passed_names = Vec::new();
296    let mut packages = Vec::new();
297
298    for line in output.lines() {
299        let trimmed = line.trim();
300        if trimmed.starts_with("--- PASS:") {
301            passed += 1;
302            if let Some(name) = trimmed.strip_prefix("--- PASS: ") {
303                let name = name.split_whitespace().next().unwrap_or(name);
304                passed_names.push(name.to_string());
305            }
306        } else if trimmed.starts_with("--- FAIL:") {
307            failed += 1;
308            failures.push(
309                trimmed
310                    .strip_prefix("--- FAIL: ")
311                    .unwrap_or(trimmed)
312                    .to_string(),
313            );
314        } else if trimmed.starts_with("ok ") || trimmed.starts_with("FAIL\t") {
315            packages.push(trimmed.to_string());
316        }
317    }
318
319    if passed == 0 && failed == 0 {
320        return None;
321    }
322
323    let mut result = format!("go test: {passed} passed");
324    if failed > 0 {
325        result.push_str(&format!(", {failed} failed"));
326    }
327
328    for pkg in &packages {
329        result.push_str(&format!("\n  {pkg}"));
330    }
331
332    for f in failures.iter().take(5) {
333        result.push_str(&format!("\n  FAIL: {f}"));
334    }
335
336    if failures.is_empty() && !passed_names.is_empty() {
337        let total = passed_names.len();
338        let shown: Vec<_> = passed_names.into_iter().take(5).collect();
339        let suffix = if total > 5 {
340            format!(" ...+{} more", total - 5)
341        } else {
342            String::new()
343        };
344        result.push_str(&format!("\n  ran: {}{suffix}", shown.join(", ")));
345    }
346
347    Some(result)
348}
349
350fn try_vitest(output: &str) -> Option<String> {
351    if !output.contains("PASS") && !output.contains("FAIL") {
352        return None;
353    }
354    if !output.contains(" Tests ") && !output.contains("Test Files") {
355        return None;
356    }
357
358    let mut test_files_line = String::new();
359    let mut tests_line = String::new();
360    let mut duration_line = String::new();
361    let mut failures = Vec::new();
362
363    for line in output.lines() {
364        let trimmed = line.trim();
365        let plain = strip_ansi(trimmed);
366        if plain.contains("Test Files") {
367            test_files_line.clone_from(&plain);
368        } else if plain.starts_with("Tests") && plain.contains("passed") {
369            tests_line.clone_from(&plain);
370        } else if plain.contains("Duration") || plain.contains("Time") {
371            if plain.contains("ms") || plain.contains('s') {
372                duration_line.clone_from(&plain);
373            }
374        } else if plain.contains("FAIL")
375            && (plain.contains(".test.") || plain.contains(".spec.") || plain.contains("_test."))
376        {
377            failures.push(plain.clone());
378        }
379    }
380
381    if tests_line.is_empty() && test_files_line.is_empty() {
382        return None;
383    }
384
385    let mut result = String::new();
386    if !test_files_line.is_empty() {
387        result.push_str(&test_files_line);
388    }
389    if !tests_line.is_empty() {
390        if !result.is_empty() {
391            result.push('\n');
392        }
393        result.push_str(&tests_line);
394    }
395    if !duration_line.is_empty() {
396        result.push('\n');
397        result.push_str(&duration_line);
398    }
399
400    for f in failures.iter().take(10) {
401        result.push_str(&format!("\n  FAIL: {f}"));
402    }
403
404    Some(result)
405}
406
407fn try_rspec(output: &str) -> Option<String> {
408    if !output.contains("examples") || !output.contains("failures") {
409        return None;
410    }
411
412    for line in output.lines().rev() {
413        let trimmed = line.trim();
414        if trimmed.contains("example") && trimmed.contains("failure") {
415            return Some(format!("rspec: {trimmed}"));
416        }
417    }
418
419    None
420}
421
422/// Parses mocha's own summary counter line: `  3 passing (50ms)` or
423/// `  1 failing`. Returns `None` for anything else, so test titles or other
424/// runners' text containing the words are never read as a mocha summary.
425fn mocha_counter(line: &str, keyword: &str) -> Option<(u32, Option<String>)> {
426    let trimmed = line.trim();
427    let (count, rest) = trimmed.split_once(' ')?;
428    if count.is_empty() || !count.bytes().all(|b| b.is_ascii_digit()) {
429        return None;
430    }
431    let n = count.parse::<u32>().ok()?;
432    let rest = rest.strip_prefix(keyword)?.trim();
433    if rest.is_empty() {
434        return Some((n, None));
435    }
436    let inner = rest.strip_prefix('(')?.strip_suffix(')')?;
437    let valid_duration = !inner.is_empty()
438        && inner.starts_with(|c: char| c.is_ascii_digit())
439        && inner.chars().all(|c| c.is_ascii_alphanumeric() || c == '.');
440    valid_duration.then(|| (n, Some(inner.to_string())))
441}
442
443fn try_mocha(output: &str) -> Option<String> {
444    let mut passing: Option<u32> = None;
445    let mut failing: Option<u32> = None;
446    let mut duration = String::new();
447    let mut failures = Vec::new();
448    let mut in_failure = false;
449
450    for line in output.lines() {
451        let plain = strip_ansi(line);
452        let trimmed = plain.trim();
453        if let Some((n, d)) = mocha_counter(trimmed, "passing") {
454            passing = Some(n);
455            if let Some(d) = d {
456                duration = d;
457            }
458            continue;
459        }
460        if let Some((n, None)) = mocha_counter(trimmed, "failing") {
461            failing = Some(n);
462            in_failure = true;
463            continue;
464        }
465        if in_failure
466            && trimmed.starts_with(|c: char| c.is_ascii_digit())
467            && let Some((num, desc)) = trimmed.split_once(')')
468            && num.bytes().all(|b| b.is_ascii_digit())
469        {
470            failures.push(desc.trim().to_string());
471        }
472    }
473
474    // Fail closed: without mocha's real summary line, leave the output to
475    // generic handling instead of reporting a bogus "0 passed".
476    if passing.is_none() && failing.is_none() {
477        return None;
478    }
479    let passing = passing.unwrap_or(0);
480    let failing = failing.unwrap_or(0);
481    if failing > 0 && failures.is_empty() {
482        return None;
483    }
484
485    let mut result = format!("mocha: {passing} passed");
486    if failing > 0 {
487        result.push_str(&format!(", {failing} failed"));
488    }
489    if !duration.is_empty() {
490        result.push_str(&format!(" ({duration})"));
491    }
492
493    for f in failures.iter().take(10) {
494        result.push_str(&format!("\n  FAIL: {f}"));
495    }
496
497    Some(result)
498}
499
500#[derive(Default)]
501struct NodeTestCounts {
502    tests: Option<u32>,
503    suites: Option<u32>,
504    pass: Option<u32>,
505    fail: Option<u32>,
506    cancelled: Option<u32>,
507    skipped: Option<u32>,
508    todo: Option<u32>,
509    duration_ms: Option<String>,
510}
511
512impl NodeTestCounts {
513    /// Records one summary line body (`tests 40`, `duration_ms 52.1`).
514    fn record(&mut self, body: &str) {
515        let Some((key, value)) = body.trim().split_once(' ') else {
516            return;
517        };
518        let value = value.trim();
519        if key == "duration_ms" {
520            if !value.is_empty() && value.chars().all(|c| c.is_ascii_digit() || c == '.') {
521                self.duration_ms = Some(value.to_string());
522            }
523            return;
524        }
525        let Ok(n) = value.parse::<u32>() else {
526            return;
527        };
528        let slot = match key {
529            "tests" => &mut self.tests,
530            "suites" => &mut self.suites,
531            "pass" => &mut self.pass,
532            "fail" => &mut self.fail,
533            "cancelled" => &mut self.cancelled,
534            "skipped" => &mut self.skipped,
535            "todo" => &mut self.todo,
536            _ => return,
537        };
538        *slot = Some(n);
539    }
540}
541
542fn indent_of(line: &str) -> usize {
543    line.len() - line.trim_start().len()
544}
545
546/// node's built-in test runner (`node --test`), spec reporter (`ℹ tests N`)
547/// or TAP reporter (`# tests N`). Failed or cancelled runs keep the full
548/// failure details; without them the parser fails closed.
549fn try_node_test(output: &str) -> Option<String> {
550    if !output.contains("tests ") || !output.contains("pass ") {
551        return None;
552    }
553
554    let lines: Vec<String> = output.lines().map(strip_ansi).collect();
555    let mut spec = NodeTestCounts::default();
556    let mut tap = NodeTestCounts::default();
557    let mut failing_block_start: Option<usize> = None;
558
559    for (i, line) in lines.iter().enumerate() {
560        let trimmed = line.trim();
561        if let Some(body) = trimmed.strip_prefix('ℹ') {
562            spec.record(body);
563        } else if let Some(body) = trimmed.strip_prefix("# ") {
564            tap.record(body);
565        } else if trimmed == "✖ failing tests:" {
566            failing_block_start = Some(i);
567        }
568    }
569
570    let is_complete =
571        |c: &NodeTestCounts| c.tests.is_some() && c.pass.is_some() && c.fail.is_some();
572    let (label, counts) = if is_complete(&spec) {
573        ("node:test", spec)
574    } else if is_complete(&tap) {
575        ("node:test (tap)", tap)
576    } else {
577        return None;
578    };
579
580    let tests = counts.tests.unwrap_or(0);
581    let pass = counts.pass.unwrap_or(0);
582    let fail = counts.fail.unwrap_or(0);
583    let cancelled = counts.cancelled.unwrap_or(0);
584
585    let mut result = format!("{label}: {pass} passed");
586    if fail > 0 {
587        result.push_str(&format!(", {fail} failed"));
588    }
589    if cancelled > 0 {
590        result.push_str(&format!(", {cancelled} cancelled"));
591    }
592    if let Some(n) = counts.skipped.filter(|n| *n > 0) {
593        result.push_str(&format!(", {n} skipped"));
594    }
595    if let Some(n) = counts.todo.filter(|n| *n > 0) {
596        result.push_str(&format!(", {n} todo"));
597    }
598    result.push_str(&format!(" ({tests} tests"));
599    if let Some(n) = counts.suites.filter(|n| *n > 0) {
600        result.push_str(&format!(", {n} suites"));
601    }
602    result.push(')');
603    if let Some(d) = &counts.duration_ms {
604        result.push_str(&format!(" [{d}ms]"));
605    }
606
607    if fail == 0 && cancelled == 0 {
608        return Some(result);
609    }
610
611    // Never hide failures: keep the details verbatim or do not summarize.
612    let mut details: Vec<&str> = Vec::new();
613    if label == "node:test" {
614        let start = failing_block_start?;
615        details.extend(lines[start..].iter().map(String::as_str));
616        while details.last().is_some_and(|l| l.trim().is_empty()) {
617            details.pop();
618        }
619    } else {
620        let mut i = 0;
621        while i < lines.len() {
622            let line = &lines[i];
623            if line.trim_start().starts_with("not ok ") {
624                let indent = indent_of(line);
625                details.push(line);
626                i += 1;
627                while i < lines.len()
628                    && (lines[i].trim().is_empty() || indent_of(&lines[i]) > indent)
629                    && !lines[i].trim_start().starts_with("not ok ")
630                {
631                    if !lines[i].trim().is_empty() {
632                        details.push(&lines[i]);
633                    }
634                    i += 1;
635                }
636                continue;
637            }
638            i += 1;
639        }
640    }
641    if details.is_empty() {
642        return None;
643    }
644    for d in details {
645        result.push('\n');
646        result.push_str(d);
647    }
648    Some(result)
649}
650
651#[cfg(test)]
652mod mocha_tests {
653    use super::*;
654
655    #[test]
656    fn mocha_passing_only() {
657        let output = "  3 passing (50ms)";
658        let result = try_mocha(output).expect("should match");
659        assert!(result.contains("3 passed"));
660        assert!(result.contains("50ms"));
661    }
662
663    #[test]
664    fn mocha_with_failures() {
665        let output =
666            "  2 passing (100ms)\n  1 failing\n\n  1) Array #indexOf():\n     Error: expected -1";
667        let result = try_mocha(output).expect("should match");
668        assert!(result.contains("2 passed"));
669        assert!(result.contains("1 failed"));
670        assert!(result.contains("FAIL:"));
671    }
672}
673
674#[cfg(test)]
675mod node_test_tests {
676    use super::*;
677
678    /// Spec reporter output of the #2294 reproduction: 40 cases, case 7 fails.
679    fn issue_2294_failing_output() -> String {
680        let mut out = String::from("\n> demo@1.0.0 test\n> node --test\n\n");
681        for i in 1..=40 {
682            if i == 7 {
683                out.push_str("✖ case 7 returns the expected value (0.912ms)\n");
684                out.push_str(
685                    "  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:\n\n    assert.ok(i !== 7)\n\n      at TestContext.<anonymous> (/work/demo/a.test.js:3:83)\n      at Test.runInAsyncScope (node:async_hooks:214:14)\n      at Test.run (node:internal/test_runner/test:1047:25) {\n    generatedMessage: true,\n    code: 'ERR_ASSERTION',\n    actual: false,\n    expected: true,\n    operator: '=='\n  }\n\n",
686                );
687            } else {
688                out.push_str(&format!(
689                    "✔ case {i} returns the expected value (0.1{i}ms)\n"
690                ));
691            }
692        }
693        out.push_str(
694            "ℹ tests 40\nℹ suites 0\nℹ pass 39\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 61.204\n\n",
695        );
696        out.push_str(
697            "✖ failing tests:\n\ntest at a.test.js:3:44\n✖ case 7 returns the expected value (0.912ms)\n  AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:\n\n    assert.ok(i !== 7)\n\n      at TestContext.<anonymous> (/work/demo/a.test.js:3:83)\n  {\n    generatedMessage: true,\n    code: 'ERR_ASSERTION',\n    actual: false,\n    expected: true,\n    operator: '=='\n  }\n",
698        );
699        out
700    }
701
702    #[test]
703    fn node_test_issue_2294_failure_kept() {
704        let output = issue_2294_failing_output();
705        assert!(
706            try_mocha(&output).is_none(),
707            "node:test must not be claimed as mocha"
708        );
709        let result = compress(&output).expect("node:test summary");
710        assert!(
711            result.starts_with("node:test: 39 passed, 1 failed (40 tests) [61.204ms]"),
712            "{result}"
713        );
714        assert!(result.contains("✖ failing tests:"), "{result}");
715        assert!(
716            result.contains("✖ case 7 returns the expected value"),
717            "{result}"
718        );
719        assert!(result.contains("assert.ok(i !== 7)"), "{result}");
720        assert!(result.contains("operator: '=='"), "{result}");
721        assert!(!result.contains("mocha"), "{result}");
722        assert!(result.len() < output.len());
723    }
724
725    #[test]
726    fn node_test_title_with_passing_word_not_mocha() {
727        let output = "✔ shows 3 passing checks (0.2ms)\n✔ reports failing tests clearly (0.1ms)\nℹ tests 2\nℹ suites 0\nℹ pass 2\nℹ fail 0\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 40.5\n";
728        assert!(try_mocha(output).is_none());
729        let result = compress(output).expect("node:test summary");
730        assert_eq!(result, "node:test: 2 passed (2 tests) [40.5ms]");
731    }
732
733    #[test]
734    fn node_test_passing_run_summarized() {
735        let mut output = String::new();
736        output.push_str("▶ math\n");
737        for i in 1..=12 {
738            output.push_str(&format!("  ✔ adds case {i} (0.0{i}ms)\n"));
739        }
740        output.push_str("✔ math (2.1ms)\n﹣ later feature (0.05ms) # SKIP\n");
741        output.push_str("ℹ tests 13\nℹ suites 1\nℹ pass 12\nℹ fail 0\nℹ cancelled 0\nℹ skipped 1\nℹ todo 0\nℹ duration_ms 75.3\n");
742        let result = compress(&output).expect("node:test summary");
743        assert_eq!(
744            result,
745            "node:test: 12 passed, 1 skipped (13 tests, 1 suites) [75.3ms]"
746        );
747    }
748
749    #[test]
750    fn node_test_failure_without_details_fails_closed() {
751        // `tail` cut before the failing-tests block: do not summarize.
752        let output = "ℹ tests 3\nℹ suites 0\nℹ pass 2\nℹ fail 1\nℹ cancelled 0\nℹ skipped 0\nℹ todo 0\nℹ duration_ms 9.1\n";
753        assert!(try_node_test(output).is_none());
754        assert!(compress(output).is_none());
755    }
756
757    #[test]
758    fn node_test_tap_reporter_keeps_not_ok() {
759        let output = "TAP version 13\n# Subtest: adds\nok 1 - adds\n  ---\n  duration_ms: 0.4\n  ...\n# Subtest: subtracts\nnot ok 2 - subtracts\n  ---\n  duration_ms: 0.7\n  location: '/work/demo/a.test.js:5:1'\n  failureType: 'testCodeFailure'\n  error: 'Expected values to be strictly equal:\\n\\n1 !== 2\\n'\n  code: 'ERR_ASSERTION'\n  ...\n1..2\n# tests 2\n# suites 0\n# pass 1\n# fail 1\n# cancelled 0\n# skipped 0\n# todo 0\n# duration_ms 50.2\n";
760        let result = compress(output).expect("tap summary");
761        assert!(
762            result.starts_with("node:test (tap): 1 passed, 1 failed (2 tests) [50.2ms]"),
763            "{result}"
764        );
765        assert!(result.contains("not ok 2 - subtracts"), "{result}");
766        assert!(result.contains("1 !== 2"), "{result}");
767        assert!(!result.contains("ok 1 - adds"), "{result}");
768    }
769
770    #[test]
771    fn real_mocha_output_still_parsed() {
772        let output = "\n  Array\n    #indexOf()\n      ✔ should return -1 when the value is not present\n      1) should return the index when present\n\n\n  1 passing (9ms)\n  1 failing\n\n  1) Array\n       #indexOf()\n         should return the index when present:\n\n      AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n\n-1 !== 0\n\n      at Context.<anonymous> (test/array.spec.js:9:14)\n";
773        assert!(try_node_test(output).is_none());
774        let result = compress(output).expect("mocha summary");
775        assert!(
776            result.starts_with("mocha: 1 passed, 1 failed (9ms)"),
777            "{result}"
778        );
779        assert!(result.contains("FAIL: Array"), "{result}");
780    }
781
782    #[test]
783    fn passing_word_in_prose_not_mocha() {
784        let output = "all checks passing now\nnothing failing here\n";
785        assert!(try_mocha(output).is_none());
786        assert!(compress(output).is_none());
787    }
788}
789
790#[cfg(test)]
791mod cargo_tests {
792    use super::*;
793
794    #[test]
795    fn cargo_test_all_passing() {
796        let output = "\
797   Compiling lean-ctx v3.9.11 (/Users/test/rust)
798     Running unittests src/lib.rs (target/debug/deps/lean_ctx-abc123)
799
800running 245 tests
801test core::tokens::tests::count_empty ... ok
802test core::tokens::tests::count_hello ... ok
803test core::config::tests::default_config ... ok
804test result: ok. 245 passed; 0 failed; 3 ignored; 0 measured; 0 filtered out; finished in 4.23s
805
806     Running tests/integration.rs (target/debug/deps/integration-def456)
807
808running 12 tests
809test api_read ... ok
810test api_search ... ok
811test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.10s";
812
813        let result = try_cargo_test(output).expect("should match");
814        assert!(result.contains("257 passed"));
815        assert!(result.contains("3 ignored"));
816        assert!(result.contains("2 suites"));
817        assert!(!result.contains("FAIL"));
818    }
819
820    #[test]
821    fn cargo_test_with_failures() {
822        let output = "\
823running 50 tests
824test core::foo ... ok
825test core::bar ... FAILED
826test result: ok. 49 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 2.0s";
827
828        let result = try_cargo_test(output).expect("should match");
829        assert!(result.contains("49 passed"));
830        assert!(result.contains("1 failed"));
831        assert!(result.contains("FAIL: core::bar"));
832    }
833
834    #[test]
835    fn cargo_test_single_suite() {
836        let output = "\
837running 10 tests
838test a ... ok
839test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.5s";
840
841        let result = try_cargo_test(output).expect("should match");
842        assert!(result.contains("10 passed"));
843        assert!(!result.contains("suites"));
844    }
845
846    #[test]
847    fn non_cargo_output_rejected() {
848        let output = "hello world\nfoo bar";
849        assert!(try_cargo_test(output).is_none());
850    }
851}