Skip to main content

tokencompact_builtins/
test_failures.rs

1use crate::Location;
2
3const MAX_LOG_FAILURES: usize = 20;
4const MAX_TEST_NAME_BYTES: usize = 512;
5const MAX_FAILURE_MESSAGE_BYTES: usize = 1_000;
6const MAX_FAILURE_DETAIL_BYTES: usize = 256;
7const MAX_GTEST_DETAILS: usize = 8;
8const MAX_GO_DETAILS: usize = 6;
9const MAX_GO_BLOCKS: usize = MAX_LOG_FAILURES * 4;
10
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct TestFailureEvidence {
13    pub name: String,
14    pub message: String,
15    pub location: Option<Location>,
16}
17
18/// Streaming, bounded extraction of concrete failed-test evidence from test logs.
19///
20/// Supported structured formats include Rust libtest, GoogleTest, and Go's
21/// standard test output. Keeping these state machines in the reducer makes
22/// selection deterministic without retaining an entire potentially large test
23/// log in memory.
24#[derive(Default)]
25pub struct TestFailureAccumulator {
26    failed_names: Vec<String>,
27    failures: Vec<TestFailureEvidence>,
28    current: Option<RustFailureBlock>,
29    gtest_running_name: Option<String>,
30    gtest_current: Option<GtestFailureBlock>,
31    go_running_name: Option<String>,
32    go_panic_name: Option<String>,
33    go_blocks: Vec<GoFailureBlock>,
34}
35
36#[derive(Default)]
37struct RustFailureBlock {
38    name: String,
39    location: Option<Location>,
40    assertion: Option<String>,
41    panic_message: Option<String>,
42    details: Vec<String>,
43    saw_panic: bool,
44}
45
46#[derive(Default)]
47struct GtestFailureBlock {
48    name: String,
49    location: Option<Location>,
50    details: Vec<String>,
51}
52
53#[derive(Default, Eq, PartialEq)]
54struct GoFailureBlock {
55    name: String,
56    location: Option<Location>,
57    location_rank: u8,
58    assertion: Option<String>,
59    panic_message: Option<String>,
60    details: Vec<String>,
61    failed: bool,
62}
63
64impl TestFailureAccumulator {
65    pub fn observe_line(&mut self, line: &str) {
66        let line = line.trim();
67        if line.is_empty() {
68            return;
69        }
70
71        if let Some(name) = go_running_name(line) {
72            self.compact_go_blocks();
73            self.go_running_name = Some(bounded_text(name, MAX_TEST_NAME_BYTES));
74            self.go_panic_name = None;
75            return;
76        }
77
78        if let Some(name) = go_failed_status_name(line) {
79            self.observe_go_failure_status(name);
80            return;
81        }
82
83        if is_go_nonfailure_status(line) && self.go_running_name.is_some() {
84            self.go_panic_name = None;
85            self.go_running_name = None;
86            return;
87        }
88
89        if let Some(message) = go_panic_message(line)
90            && self.observe_go_panic(message)
91        {
92            return;
93        }
94
95        if let Some((location, message, stack_frame)) = go_test_location(line)
96            && self.observe_go_location(location, message, stack_frame)
97        {
98            return;
99        }
100
101        if self.observe_go_detail(line) {
102            return;
103        }
104
105        if let Some(name) = gtest_running_name(line) {
106            self.finish_gtest_current();
107            self.gtest_running_name = Some(bounded_text(name, MAX_TEST_NAME_BYTES));
108            return;
109        }
110
111        if let Some(location) = gtest_failure_location(line) {
112            self.finish_gtest_current();
113            self.gtest_current = Some(GtestFailureBlock {
114                name: self
115                    .gtest_running_name
116                    .clone()
117                    .unwrap_or_else(|| "<unknown gtest>".to_owned()),
118                location,
119                ..GtestFailureBlock::default()
120            });
121            return;
122        }
123
124        if let Some(name) = gtest_failed_name(line) {
125            if self
126                .gtest_running_name
127                .as_deref()
128                .is_some_and(|running| running == name)
129            {
130                self.finish_gtest_current();
131                self.gtest_running_name = None;
132            }
133            return;
134        }
135
136        if let Some(current) = self.gtest_current.as_mut() {
137            if current.details.len() < MAX_GTEST_DETAILS && !is_gtest_framework_status(line) {
138                current
139                    .details
140                    .push(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
141            }
142            return;
143        }
144
145        if let Some(name) = rust_failed_status_name(line) {
146            push_unique_bounded(
147                &mut self.failed_names,
148                name,
149                MAX_LOG_FAILURES,
150                MAX_TEST_NAME_BYTES,
151            );
152        }
153
154        if let Some(name) = rust_failure_block_name(line) {
155            self.finish_current();
156            self.current = Some(RustFailureBlock {
157                name: bounded_text(name, MAX_TEST_NAME_BYTES),
158                ..RustFailureBlock::default()
159            });
160            return;
161        }
162
163        if let Some((name, location)) = rust_panic(line) {
164            let replace = self
165                .current
166                .as_ref()
167                .is_some_and(|current| !current.name.is_empty() && current.name != name);
168            if replace {
169                self.finish_current();
170            }
171            let current = self.current.get_or_insert_with(RustFailureBlock::default);
172            current.name = bounded_text(name, MAX_TEST_NAME_BYTES);
173            current.location = location;
174            current.saw_panic = true;
175            return;
176        }
177
178        if is_failure_heading(line) {
179            self.finish_current();
180            return;
181        }
182
183        let Some(current) = self.current.as_mut() else {
184            return;
185        };
186        let lower = line.to_ascii_lowercase();
187        if lower.contains("assertion") && lower.contains(" failed") {
188            current.assertion = Some(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
189        } else if is_assertion_detail(&lower) {
190            if current.details.len() < 4 {
191                current
192                    .details
193                    .push(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
194            }
195        } else if current.saw_panic
196            && current.panic_message.is_none()
197            && !lower.starts_with("note:")
198            && !lower.starts_with("stack backtrace:")
199            && !lower.starts_with("test result:")
200        {
201            current.panic_message = Some(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
202        }
203    }
204
205    #[must_use]
206    pub fn finish(mut self) -> Vec<TestFailureEvidence> {
207        self.finish_current();
208        self.finish_gtest_current();
209        self.finish_go_failures();
210        for name in self.failed_names {
211            if self.failures.len() >= MAX_LOG_FAILURES {
212                break;
213            }
214            if self.failures.iter().any(|failure| failure.name == name) {
215                continue;
216            }
217            self.failures.push(TestFailureEvidence {
218                message: format!("Rust test {name} failed"),
219                name,
220                location: None,
221            });
222        }
223        self.failures
224    }
225
226    fn finish_current(&mut self) {
227        let Some(current) = self.current.take() else {
228            return;
229        };
230        if current.name.is_empty() || self.failures.len() >= MAX_LOG_FAILURES {
231            return;
232        }
233        let mut message = format!("Rust test {} failed", current.name);
234        if let Some(location) = &current.location {
235            message.push_str(" at ");
236            message.push_str(&location.path);
237            if let Some(line) = location.line {
238                message.push(':');
239                message.push_str(&line.to_string());
240            }
241            if let Some(column) = location.column {
242                message.push(':');
243                message.push_str(&column.to_string());
244            }
245        }
246        if let Some(reason) = current.assertion.or(current.panic_message) {
247            message.push_str(": ");
248            message.push_str(&reason);
249        }
250        for detail in current.details {
251            message.push_str("; ");
252            message.push_str(&detail);
253        }
254        self.failures.push(TestFailureEvidence {
255            name: current.name,
256            message: bounded_text(&message, MAX_FAILURE_MESSAGE_BYTES),
257            location: current.location,
258        });
259    }
260
261    fn finish_gtest_current(&mut self) {
262        let Some(current) = self.gtest_current.take() else {
263            return;
264        };
265        if current.name.is_empty() || self.failures.len() >= MAX_LOG_FAILURES {
266            return;
267        }
268        let mut message = format!("C++ test {} failed", current.name);
269        if !current.details.is_empty() {
270            message.push_str(": ");
271            for (index, detail) in current.details.iter().enumerate() {
272                if index > 0 {
273                    if message.ends_with(':') {
274                        message.push(' ');
275                    } else {
276                        message.push_str("; ");
277                    }
278                }
279                message.push_str(detail);
280            }
281        }
282        self.failures.push(TestFailureEvidence {
283            name: current.name,
284            message: bounded_text(&message, MAX_FAILURE_MESSAGE_BYTES),
285            location: current.location,
286        });
287    }
288
289    fn observe_go_failure_status(&mut self, name: &str) {
290        let name = bounded_text(name, MAX_TEST_NAME_BYTES);
291        let index = self
292            .go_blocks
293            .iter()
294            .rposition(|block| block.name == name && !block.failed)
295            .or_else(|| self.push_go_block(&name));
296        if let Some(index) = index {
297            self.go_blocks[index].failed = true;
298        }
299        self.go_running_name = Some(name.clone());
300        self.go_panic_name = Some(name);
301    }
302
303    fn observe_go_panic(&mut self, message: &str) -> bool {
304        let Some(name) = self
305            .go_panic_name
306            .clone()
307            .or_else(|| self.go_running_name.clone())
308        else {
309            return false;
310        };
311        let Some(index) = self.go_block_index(&name, true) else {
312            return true;
313        };
314        let block = &mut self.go_blocks[index];
315        if block.panic_message.is_none() {
316            block.panic_message = Some(bounded_text(message, MAX_FAILURE_DETAIL_BYTES));
317        }
318        self.go_panic_name = Some(name);
319        true
320    }
321
322    fn observe_go_location(
323        &mut self,
324        location: Location,
325        message: Option<&str>,
326        stack_frame: bool,
327    ) -> bool {
328        let panic_context = self.go_panic_name.is_some();
329        let Some(name) = self
330            .go_panic_name
331            .clone()
332            .or_else(|| self.go_running_name.clone())
333        else {
334            return false;
335        };
336        if stack_frame && is_go_runtime_path(&location.path) {
337            return true;
338        }
339        let Some(index) = self.go_block_index(&name, panic_context) else {
340            return true;
341        };
342        let block = &mut self.go_blocks[index];
343        let rank = if stack_frame && !location.path.ends_with("_test.go") {
344            1
345        } else {
346            0
347        };
348        if block.location.is_none() || rank < block.location_rank {
349            block.location = Some(location);
350            block.location_rank = rank;
351        }
352        if let Some(message) = message.filter(|message| !message.is_empty()) {
353            if block.assertion.is_none() {
354                block.assertion = Some(bounded_text(message, MAX_FAILURE_DETAIL_BYTES));
355            } else if is_go_assertion_detail(message) {
356                push_unique_bounded(
357                    &mut block.details,
358                    message,
359                    MAX_GO_DETAILS,
360                    MAX_FAILURE_DETAIL_BYTES,
361                );
362            }
363        }
364        true
365    }
366
367    fn observe_go_detail(&mut self, line: &str) -> bool {
368        let panic_context = self.go_panic_name.is_some();
369        let Some(name) = self
370            .go_panic_name
371            .clone()
372            .or_else(|| self.go_running_name.clone())
373        else {
374            return false;
375        };
376        if is_go_framework_noise(line) || looks_like_go_stack_frame(line) {
377            return false;
378        }
379        let existing = self
380            .go_blocks
381            .iter()
382            .rposition(|block| block.name == name && (panic_context || !block.failed));
383        if !is_go_assertion_detail(line)
384            && !existing.is_some_and(|index| {
385                let block = &self.go_blocks[index];
386                block.location.is_some() && block.assertion.is_none()
387            })
388        {
389            return false;
390        }
391        let Some(index) = existing.or_else(|| self.push_go_block(&name)) else {
392            return false;
393        };
394        let block = &mut self.go_blocks[index];
395        if is_go_assertion_detail(line) {
396            if block.assertion.is_none() {
397                block.assertion = Some(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
398            } else {
399                push_unique_bounded(
400                    &mut block.details,
401                    line,
402                    MAX_GO_DETAILS,
403                    MAX_FAILURE_DETAIL_BYTES,
404                );
405            }
406            return true;
407        }
408        if block.location.is_some() && block.assertion.is_none() {
409            block.assertion = Some(bounded_text(line, MAX_FAILURE_DETAIL_BYTES));
410            return true;
411        }
412        false
413    }
414
415    fn go_block_index(&mut self, name: &str, include_failed: bool) -> Option<usize> {
416        self.go_blocks
417            .iter()
418            .rposition(|block| block.name == name && (include_failed || !block.failed))
419            .or_else(|| self.push_go_block(name))
420    }
421
422    fn push_go_block(&mut self, name: &str) -> Option<usize> {
423        if self.go_blocks.len() >= MAX_GO_BLOCKS {
424            self.compact_go_blocks();
425            if self.go_blocks.len() >= MAX_GO_BLOCKS {
426                return None;
427            }
428        }
429        self.go_blocks.push(GoFailureBlock {
430            name: bounded_text(name, MAX_TEST_NAME_BYTES),
431            location_rank: u8::MAX,
432            ..GoFailureBlock::default()
433        });
434        Some(self.go_blocks.len() - 1)
435    }
436
437    fn compact_go_blocks(&mut self) {
438        let mut unique = Vec::with_capacity(self.go_blocks.len());
439        for block in std::mem::take(&mut self.go_blocks) {
440            if block.failed
441                && unique
442                    .iter()
443                    .any(|current: &GoFailureBlock| current.failed && current == &block)
444            {
445                continue;
446            }
447            unique.push(block);
448        }
449        self.go_blocks = unique;
450    }
451
452    fn finish_go_failures(&mut self) {
453        for block in std::mem::take(&mut self.go_blocks)
454            .into_iter()
455            .filter(|block| block.failed)
456        {
457            if self.failures.len() >= MAX_LOG_FAILURES {
458                break;
459            }
460            let mut message = if block.panic_message.is_some() {
461                format!("Go test {} panicked", block.name)
462            } else {
463                format!("Go test {} failed", block.name)
464            };
465            if let Some(location) = &block.location {
466                message.push_str(" at ");
467                message.push_str(&location.path);
468                if let Some(line) = location.line {
469                    message.push(':');
470                    message.push_str(&line.to_string());
471                }
472                if let Some(column) = location.column {
473                    message.push(':');
474                    message.push_str(&column.to_string());
475                }
476            }
477            if let Some(reason) = block.panic_message.or(block.assertion) {
478                message.push_str(": ");
479                message.push_str(&reason);
480            }
481            for detail in block.details {
482                message.push_str("; ");
483                message.push_str(&detail);
484            }
485            let evidence = TestFailureEvidence {
486                name: block.name,
487                message: bounded_text(&message, MAX_FAILURE_MESSAGE_BYTES),
488                location: block.location,
489            };
490            if !self.failures.iter().any(|current| current == &evidence) {
491                self.failures.push(evidence);
492            }
493        }
494    }
495}
496
497fn rust_failed_status_name(line: &str) -> Option<&str> {
498    line.strip_prefix("test ")?
499        .strip_suffix(" ... FAILED")
500        .filter(|name| !name.is_empty())
501}
502
503fn gtest_running_name(line: &str) -> Option<&str> {
504    line.strip_prefix("[ RUN      ] ")
505        .filter(|name| !name.is_empty())
506}
507
508fn gtest_failed_name(line: &str) -> Option<&str> {
509    let name = line.strip_prefix("[  FAILED  ] ")?;
510    let name = name.rsplit_once(" (").map_or(name, |(name, duration)| {
511        duration
512            .strip_suffix(')')
513            .filter(|duration| duration.ends_with(" ms"))
514            .map_or(name, |_| name)
515    });
516    (!name.is_empty()).then_some(name)
517}
518
519fn go_running_name(line: &str) -> Option<&str> {
520    line.strip_prefix("=== RUN")
521        .map(str::trim)
522        .filter(|name| !name.is_empty())
523}
524
525fn go_failed_status_name(line: &str) -> Option<&str> {
526    let name = line.strip_prefix("--- FAIL:")?.trim();
527    let name = name.rsplit_once(" (").map_or(name, |(name, duration)| {
528        duration.strip_suffix(')').map_or(name, |_| name)
529    });
530    (!name.is_empty()).then_some(name)
531}
532
533fn is_go_nonfailure_status(line: &str) -> bool {
534    line.starts_with("--- PASS:") || line.starts_with("--- SKIP:")
535}
536
537fn go_panic_message(line: &str) -> Option<&str> {
538    let message = line.strip_prefix("panic:")?.trim();
539    let message = [" [recovered, repanicked]", " [recovered]"]
540        .into_iter()
541        .find_map(|suffix| message.strip_suffix(suffix))
542        .unwrap_or(message)
543        .trim();
544    (!message.is_empty()).then_some(message)
545}
546
547fn go_test_location(line: &str) -> Option<(Location, Option<&str>, bool)> {
548    let marker = line.rfind(".go:")?;
549    let path_end = marker + ".go".len();
550    let raw_path = line[..path_end].trim();
551    let error_trace = raw_path.strip_prefix("Error Trace:").map(str::trim);
552    let path = error_trace.unwrap_or(raw_path);
553    if path.is_empty() {
554        return None;
555    }
556
557    let remainder = &line[path_end + 1..];
558    let digit_count = remainder.bytes().take_while(u8::is_ascii_digit).count();
559    if digit_count == 0 {
560        return None;
561    }
562    let line_number = remainder[..digit_count].parse::<u32>().ok()?;
563    let mut remainder = &remainder[digit_count..];
564    let mut column = None;
565    let mut stack_frame = error_trace.is_none() && !remainder.starts_with(':');
566    let mut message = None;
567    if let Some(after_colon) = remainder.strip_prefix(':') {
568        remainder = after_colon;
569        let column_digits = remainder.bytes().take_while(u8::is_ascii_digit).count();
570        if column_digits > 0 && remainder[column_digits..].starts_with(':') {
571            column = remainder[..column_digits].parse::<u32>().ok();
572            remainder = &remainder[column_digits + 1..];
573        }
574        let text = remainder.trim();
575        if !text.is_empty() {
576            stack_frame = text.starts_with("+0x");
577            if !stack_frame {
578                message = Some(text);
579            }
580        }
581    }
582
583    Some((
584        Location {
585            path: bounded_text(&compact_test_path(path), MAX_FAILURE_DETAIL_BYTES),
586            line: Some(line_number),
587            column,
588        },
589        message,
590        stack_frame,
591    ))
592}
593
594fn is_go_runtime_path(path: &str) -> bool {
595    let absolute = path.starts_with('/') || path.as_bytes().get(1) == Some(&b':');
596    absolute
597        && ["/src/runtime/", "/src/testing/"]
598            .iter()
599            .any(|component| path.contains(component))
600}
601
602fn is_go_assertion_detail(line: &str) -> bool {
603    let lower = line.to_ascii_lowercase();
604    [
605        "got:",
606        "want:",
607        "expected:",
608        "actual:",
609        "error:",
610        "fatal:",
611        "message:",
612        "messages:",
613        "diff:",
614    ]
615    .iter()
616    .any(|prefix| lower.starts_with(prefix))
617}
618
619fn is_go_framework_noise(line: &str) -> bool {
620    let lower = line.to_ascii_lowercase();
621    line.starts_with("=== ")
622        || line.starts_with("--- ")
623        || line.starts_with("goroutine ")
624        || line.starts_with("created by ")
625        || lower == "pass"
626        || lower == "fail"
627        || lower.starts_with("ok\t")
628        || lower.starts_with("?\t")
629        || lower.starts_with("coverage:")
630        || lower.starts_with("exit status ")
631}
632
633fn looks_like_go_stack_frame(line: &str) -> bool {
634    (line.contains('(') && line.split_whitespace().count() == 1)
635        || line.starts_with("testing.")
636        || line.starts_with("runtime.")
637}
638
639fn gtest_failure_location(line: &str) -> Option<Option<Location>> {
640    let location = line.strip_suffix(": Failure")?;
641    if location == "unknown file" {
642        return Some(None);
643    }
644    let (path, line_number) = location.rsplit_once(':')?;
645    let line_number = line_number.parse::<u32>().ok()?;
646    (!path.is_empty()).then(|| {
647        Some(Location {
648            path: compact_test_path(path),
649            line: Some(line_number),
650            column: None,
651        })
652    })
653}
654
655fn compact_test_path(path: &str) -> String {
656    let path = path.trim_matches('"').replace('\\', "/");
657    path.strip_prefix("./").unwrap_or(&path).to_owned()
658}
659
660fn is_gtest_framework_status(line: &str) -> bool {
661    [
662        "[==========]",
663        "[----------]",
664        "[  PASSED  ]",
665        "[  SKIPPED ]",
666    ]
667    .iter()
668    .any(|prefix| line.starts_with(prefix))
669}
670
671fn rust_failure_block_name(line: &str) -> Option<&str> {
672    let body = line.strip_prefix("---- ")?.strip_suffix(" ----")?;
673    body.strip_suffix(" stdout")
674        .or_else(|| body.strip_suffix(" stderr"))
675        .filter(|name| !name.is_empty())
676}
677
678fn rust_panic(line: &str) -> Option<(&str, Option<Location>)> {
679    let rest = line.strip_prefix("thread '")?;
680    let marker = " panicked at ";
681    let marker_index = rest.find(marker)?;
682    let thread = &rest[..marker_index];
683    let quote = thread.rfind('\'')?;
684    let name = &thread[..quote];
685    if name.is_empty() {
686        return None;
687    }
688    let location = parse_location(&rest[marker_index + marker.len()..]);
689    Some((name, location))
690}
691
692fn parse_location(value: &str) -> Option<Location> {
693    let value = value.trim().trim_end_matches(':');
694    let mut parts = value.rsplitn(3, ':');
695    let column = parts.next()?.parse::<u32>().ok()?;
696    let line = parts.next()?.parse::<u32>().ok()?;
697    let path = parts.next()?.trim();
698    if path.is_empty() {
699        return None;
700    }
701    Some(Location {
702        path: bounded_text(path, MAX_FAILURE_DETAIL_BYTES),
703        line: Some(line),
704        column: Some(column),
705    })
706}
707
708fn is_assertion_detail(lower: &str) -> bool {
709    ["left:", "right:", "expected:", "actual:"]
710        .iter()
711        .any(|prefix| lower.starts_with(prefix))
712}
713
714fn is_failure_heading(line: &str) -> bool {
715    matches!(
716        line.trim().to_ascii_lowercase().as_str(),
717        "failure:" | "failures:"
718    )
719}
720
721fn push_unique_bounded(
722    values: &mut Vec<String>,
723    value: &str,
724    maximum_items: usize,
725    maximum_bytes: usize,
726) {
727    if values.len() >= maximum_items {
728        return;
729    }
730    let value = bounded_text(value, maximum_bytes);
731    if !values.contains(&value) {
732        values.push(value);
733    }
734}
735
736fn bounded_text(value: &str, maximum_bytes: usize) -> String {
737    if value.len() <= maximum_bytes {
738        return value.to_owned();
739    }
740    let ellipsis_bytes = '…'.len_utf8();
741    if maximum_bytes < ellipsis_bytes {
742        let mut boundary = maximum_bytes;
743        while !value.is_char_boundary(boundary) {
744            boundary -= 1;
745        }
746        return value[..boundary].to_owned();
747    }
748    let mut boundary = maximum_bytes - ellipsis_bytes;
749    while !value.is_char_boundary(boundary) {
750        boundary -= 1;
751    }
752    format!("{}…", &value[..boundary])
753}
754
755#[cfg(test)]
756mod tests {
757    use super::*;
758
759    #[test]
760    fn extracts_rust_test_name_assertion_values_and_location() {
761        let mut accumulator = TestFailureAccumulator::default();
762        for line in [
763            "running 3 tests",
764            "test build::tests::successful_root_cause_test ... ok",
765            "test test::tests::parses_direct_testsuite_root ... FAILED",
766            "failures:",
767            "---- test::tests::parses_direct_testsuite_root stdout ----",
768            "thread 'test::tests::parses_direct_testsuite_root' panicked at src/test.rs:101:9:",
769            "assertion `left == right` failed",
770            "left: \"one\"",
771            "right: \"expected\"",
772        ] {
773            accumulator.observe_line(line);
774        }
775
776        let failures = accumulator.finish();
777        assert_eq!(failures.len(), 1);
778        assert_eq!(
779            failures[0].name,
780            "test::tests::parses_direct_testsuite_root"
781        );
782        assert!(
783            failures[0]
784                .message
785                .contains("assertion `left == right` failed")
786        );
787        assert!(failures[0].message.contains("left: \"one\""));
788        assert_eq!(
789            failures[0].location,
790            Some(Location {
791                path: "src/test.rs".into(),
792                line: Some(101),
793                column: Some(9),
794            })
795        );
796        assert!(!failures[0].message.contains("successful_root_cause_test"));
797    }
798
799    #[test]
800    fn falls_back_to_failed_rust_status_without_a_panic_block() {
801        let mut accumulator = TestFailureAccumulator::default();
802        accumulator.observe_line("test tests::failed_without_output ... FAILED");
803        let failures = accumulator.finish();
804        assert_eq!(failures.len(), 1);
805        assert_eq!(failures[0].name, "tests::failed_without_output");
806        assert_eq!(
807            failures[0].message,
808            "Rust test tests::failed_without_output failed"
809        );
810    }
811
812    #[test]
813    fn extracts_gtest_assertion_details_and_locations() {
814        let mut accumulator = TestFailureAccumulator::default();
815        for line in [
816            "[ RUN      ] InvoiceTest.IncludesServiceFee",
817            "mcp/cpp_fixture/assertion_failure_test.cc:8: Failure",
818            "Expected equality of these values:",
819            "CalculateInvoiceTotal(40, 2)",
820            "Which is: 42",
821            "41",
822            "invoice total should include the service fee",
823            "[  FAILED  ] InvoiceTest.IncludesServiceFee (0 ms)",
824        ] {
825            accumulator.observe_line(line);
826        }
827        let failures = accumulator.finish();
828        assert_eq!(failures.len(), 1);
829        assert_eq!(failures[0].name, "InvoiceTest.IncludesServiceFee");
830        assert!(failures[0].message.contains("Which is: 42"));
831        assert_eq!(
832            failures[0].location,
833            Some(Location {
834                path: "mcp/cpp_fixture/assertion_failure_test.cc".into(),
835                line: Some(8),
836                column: None,
837            })
838        );
839    }
840
841    #[test]
842    fn extracts_gtest_cpp_exceptions_without_unknown_file_noise() {
843        let mut accumulator = TestFailureAccumulator::default();
844        for line in [
845            "[ RUN      ] InvoiceTest.RejectsMissingCurrency",
846            "unknown file: Failure",
847            "C++ exception with description \"invoice currency was not configured\" thrown in the test body.",
848            "[  FAILED  ] InvoiceTest.RejectsMissingCurrency (0 ms)",
849        ] {
850            accumulator.observe_line(line);
851        }
852        let failures = accumulator.finish();
853        assert_eq!(failures.len(), 1);
854        assert!(
855            failures[0]
856                .message
857                .contains("invoice currency was not configured")
858        );
859        assert_eq!(failures[0].location, None);
860        assert!(!failures[0].message.contains("unknown file"));
861    }
862
863    #[test]
864    fn bounds_go_failure_items_names_locations_and_messages() {
865        let mut accumulator = TestFailureAccumulator::default();
866        let path = format!("{}failure_test.go", "very-long-segment/".repeat(24));
867        for index in 0..25 {
868            let name = format!("Test{index:02}_{}", "name".repeat(160));
869            accumulator.observe_line(&format!("=== RUN   {name}"));
870            accumulator.observe_line(&format!("{path}:7: assertion {}", "message".repeat(80)));
871            accumulator.observe_line(&format!("--- FAIL: {name} (0.00s)"));
872        }
873        let failures = accumulator.finish();
874        assert_eq!(failures.len(), MAX_LOG_FAILURES);
875        for failure in failures {
876            assert!(failure.name.len() <= MAX_TEST_NAME_BYTES);
877            assert!(failure.message.len() <= MAX_FAILURE_MESSAGE_BYTES);
878            assert!(failure.location.unwrap().path.len() <= MAX_FAILURE_DETAIL_BYTES);
879        }
880    }
881
882    #[test]
883    fn repeated_go_fanout_does_not_consume_the_unique_failure_budget() {
884        let mut accumulator = TestFailureAccumulator::default();
885        for _ in 0..(MAX_GO_BLOCKS + 5) {
886            for line in [
887                "=== RUN   TestRepeated",
888                "repeat_test.go:4: got false; want true",
889                "--- FAIL: TestRepeated (0.00s)",
890            ] {
891                accumulator.observe_line(line);
892            }
893        }
894        for line in [
895            "=== RUN   TestUnique",
896            "unique_test.go:8: fatal: unique failure",
897            "--- FAIL: TestUnique (0.00s)",
898        ] {
899            accumulator.observe_line(line);
900        }
901        let failures = accumulator.finish();
902        assert_eq!(failures.len(), 2);
903        assert_eq!(failures[0].name, "TestRepeated");
904        assert_eq!(failures[1].name, "TestUnique");
905    }
906}