rtk icon indicating copy to clipboard operation
rtk copied to clipboard

rtk pytest -rP/-rA lists passing tests that print output as [FAIL]

Open aeppling opened this issue 1 month ago • 6 comments

With -rP or -rA, pytest prints a PASSES section with the captured output of passing tests. rtk pytest parses that section as failures, so a passing test that prints something is listed as [FAIL].

Repro (pytest 9.1.1):

# test_pp.py
def test_print():
    print("hello")
def test_fail():
    assert 0
$ rtk pytest -rP
Pytest: 1 passed, 1 failed in 0.01s
...
1. [FAIL] test_fail
2. [FAIL] test_print      <- passed

Same on master (v1.0.1), develop and #3355. Exit code is correct, only the failures block is wrong. Found while fuzzing #3355.

aeppling avatar Oct 16 '26 13:10 aeppling

Confirmed on current develop f16becac with real pytest 9.0.3. The parser stays in Failures when pytest starts its PASSES section, so the next captured-output block becomes another failure.

The patch below flushes the real failure before entering Passes, ignores passing-test captures, then resumes the normal short summary. Actual failures, setup errors and exit codes remain intact in the tested runs.

Validation:

  • Two regression tests reproduce the bug before the fix; all 15 pytest parser tests pass with it on current develop.
  • Ten real pytest scenarios / 40 native, current-develop, fixed and combined executions cover -rP/-rA, requested -q/-v, passing captures, genuine failures, skips, xfails, colored setup errors and a passing-only control. The old code labels test_print as [FAIL] in every mixed case; the fixed code does not. Exit codes remain 0/1 as appropriate.
  • Combined current develop + #3355 (b4c642c) + #4466 (cdad612) + this patch: 24 parser tests and the full workspace test run pass (4,965 passed, 8 ignored), plus fmt and warnings-denied clippy. After #4466, git apply --3way applies this patch cleanly; ordinary context-only application needs the nearby hunk adjusted.

Linux only; I have not run pytest 9.1.1 or other platforms. This leaves the separate -qq issue #2960 unchanged.

Apply-ready patch against develop f16becac
diff --git a/src/cmds/python/pytest_cmd.rs b/src/cmds/python/pytest_cmd.rs
index dc2f5806..d0e7ae94 100644
--- a/src/cmds/python/pytest_cmd.rs
+++ b/src/cmds/python/pytest_cmd.rs
@@ -15,6 +15,7 @@ enum ParseState {
     Header,
     TestProgress,
     Failures,
+    Passes,
     Summary,
 }
 
@@ -100,8 +101,15 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
         } else if trimmed.starts_with("===") && trimmed.contains("FAILURES") {
             state = ParseState::Failures;
             continue;
-        } else if trimmed.starts_with("===") && trimmed.contains("short test summary") {
-            state = ParseState::Summary;
+        } else if trimmed.starts_with("===")
+            && (trimmed.contains("short test summary")
+                || trimmed.trim_matches('=').trim() == "PASSES")
+        {
+            state = if trimmed.trim_matches('=').trim() == "PASSES" {
+                ParseState::Passes
+            } else {
+                ParseState::Summary
+            };
             // Save current failure if any
             if !current_failure.is_empty() {
                 failures.push(current_failure.join("\n"));
@@ -158,6 +166,7 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
                     current_failure.push(trimmed.to_string());
                 }
             }
+            ParseState::Passes => {}
             ParseState::Summary => {
                 // FAILED test lines
                 if trimmed.starts_with("FAILED") || trimmed.starts_with("ERROR") {
@@ -363,6 +372,57 @@ fn parse_duration(summary: &str) -> Option<String> {
 mod tests {
     use super::*;
 
+    #[test]
+    fn test_filter_pytest_passing_capture_is_not_a_failure() {
+        let output = r#".F                                                                       [100%]
+=================================== FAILURES ===================================
+________________________________ test_fail _____________________________________
+test_report.py:6: in test_fail
+    assert False
+E   assert False
+==================================== PASSES ====================================
+________________________________ test_print ____________________________________
+----------------------------- Captured stdout call -----------------------------
+hello from a passing test
+FAILED fabricated.py::test_from_stdout - printed text, not a result
+1 failed, 1 passed in 0.01s"#;
+
+        let result = filter_pytest_output(output);
+        assert!(result.contains("1 passed, 1 failed"), "{result}");
+        assert!(result.contains("[FAIL] test_fail"), "{result}");
+        assert!(result.contains("E   assert False"), "{result}");
+        assert!(!result.contains("test_print"), "{result}");
+        assert!(!result.contains("fabricated.py"), "{result}");
+        assert!(!result.contains("hello from"), "{result}");
+    }
+
+    #[test]
+    fn test_filter_pytest_report_all_retains_actual_failure_summary() {
+        let output = r#".F                                                                       [100%]
+=================================== FAILURES ===================================
+________________________________ test_fail _____________________________________
+test_report.py:6: in test_fail
+    assert False
+E   assert False
+==================================== PASSES ====================================
+________________________________ test_print ____________________________________
+----------------------------- Captured stdout call -----------------------------
+hello from a passing test
+=========================== short test summary info ============================
+PASSED test_report.py::test_print
+FAILED test_report.py::test_fail - assert False
+========================= 1 failed, 1 passed in 0.01s =========================="#;
+
+        let result = filter_pytest_output(output);
+        assert!(result.contains("1 passed, 1 failed"), "{result}");
+        assert!(result.contains("[FAIL] test_fail"), "{result}");
+        assert!(
+            result.contains("[FAIL] test_report.py::test_fail"),
+            "{result}"
+        );
+        assert!(!result.contains("test_print"), "{result}");
+    }
+
     #[test]
     fn test_filter_pytest_all_pass() {
         let output = r#"=== test session starts ===

Protocol-zero-0 avatar Oct 16 '26 15:10 Protocol-zero-0

wshm · Automated triage by AI

🔍 Automated Triage

🐛 Category bug
🟡 Priority medium
🎯 Confidence 95%

Summary

rtk pytest misparses the pytest -rP/-rA PASSES section as failures, mislabeling printing passing tests as [FAIL]

This looks like a simple fix that could be auto-resolved. Repo maintainers can use /wshm fix to attempt it.

📁 Relevant files
  • src/pytest/parser.rs

Suggested Actions

  1. Reproduce with the provided test_pp.py and pytest 9.1.1 using -rP/-rA
  2. Fix the pytest output parser to distinguish the PASSES section from FAILURES before classifying results
  3. Add a regression test covering -rP/-rA output with a printing passing test
  4. Check interaction with #2399 and #3355 since this was found while fuzzing #3355

Triaged automatically by wshm · This is an automated analysis, not a human review.

rtk-wshm-sync-bot avatar Oct 16 '26 16:10 rtk-wshm-sync-bot

Same mechanism with XPASSES, and here no user flag is needed: rtk injects -rxX, so an xfail test that passes and prints something gets an XPASSES section with a ___ test_xp ___ header, and that is listed as [FAIL] test_xp:

@pytest.mark.xfail(reason="fixed upstream?")
def test_xp():
    print("xp out")

rtk pytest prints 2. [FAIL] test_xp next to the real failure (v1.0.1 and develop alike). #4621 stops at PASSES and warnings summary, so XPASSES would need adding to that banner list. In my repro the [FAIL] went away with #4621 only because a warnings summary came first.

KuSh avatar Oct 21 '26 11:10 KuSh

Confirmed on current develop 5ab62913 with real pytest 9.0.3: the default injected -rxX reproduces [FAIL] test_xp beside the real failure. -rX and -rA reproduce it too.

The updated patch below supersedes my earlier PASSES-only patch. It flushes the current failure before entering PASSES, XPASSES, XFAILURES or warnings summary, ignores capture-only blocks there, and resumes the normal short summary. Section titles are matched exactly, so XFAILURES does not match FAILURES; a generic === application diagnostics === printed by a failing test does not end failure parsing. This also keeps the two-real-failure counterexample from my #4621 review covered.

Validation against 5ab62913:

  • 20 real pytest scenarios / 60 raw, unmodified-develop and patched CLI executions: default reporting, -rxX, -rX, -rx, -rP, -rA; mixed outcomes, XPASS-only, strict XPASS, plus -q/-v application-banner controls. The patch removes the false failure blocks while retaining real failures, XFAIL/XPASS summary entries, strict-XPASS failure status and native exit codes.
  • Two new regression tests; 24 pytest parser tests pass. Full workspace tests: 5,032 passed, 8 ignored; fmt and warnings-denied all-targets clippy pass.
  • Linux / pytest 9.0.3 only; no claim of pytest 9.1.1 or cross-platform validation for this patch. Exact pytest section banners printed by an application remain ambiguous to a text parser.

No competing PR opened; this is an apply-ready update for the existing #4600/#4621 integration decision.

Updated patch against develop 5ab62913
diff --git a/src/cmds/python/pytest_cmd.rs b/src/cmds/python/pytest_cmd.rs
index f609ecda..f48cbabb 100644
--- a/src/cmds/python/pytest_cmd.rs
+++ b/src/cmds/python/pytest_cmd.rs
@@ -23,6 +23,7 @@ enum ParseState {
     Header,
     TestProgress,
     Failures,
+    CapturedReports,
     Summary,
 }
 
@@ -101,19 +102,29 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
     for line in output.lines() {
         let trimmed = line.trim();
 
+        // Match pytest section titles exactly: XFAILURES is a report, not FAILURES.
+        let section = trimmed.trim_matches('=').trim();
+
         // State transitions
         if trimmed.starts_with("===") && trimmed.contains("test session starts") {
             state = ParseState::Header;
             continue;
         // pytest prints setup/teardown/collection errors in an ERRORS section
         // shaped like FAILURES, so both feed the same failure blocks.
-        } else if trimmed.starts_with("===")
-            && (trimmed.contains("FAILURES") || trimmed.contains("ERRORS"))
-        {
+        } else if trimmed.starts_with("===") && matches!(section, "FAILURES" | "ERRORS") {
             state = ParseState::Failures;
             continue;
-        } else if trimmed.starts_with("===") && trimmed.contains("short test summary") {
-            state = ParseState::Summary;
+        } else if trimmed.starts_with("===")
+            && matches!(
+                section,
+                "short test summary info" | "PASSES" | "XPASSES" | "XFAILURES" | "warnings summary"
+            )
+        {
+            state = if section == "short test summary info" {
+                ParseState::Summary
+            } else {
+                ParseState::CapturedReports
+            };
             // Save current failure if any
             if !current_failure.is_empty() {
                 failures.push(current_failure.join("\n"));
@@ -154,6 +165,7 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
                     current_failure.push(trimmed.to_string());
                 }
             }
+            ParseState::CapturedReports => {}
             ParseState::Summary => {
                 // FAILED test lines
                 if trimmed.starts_with("FAILED") || trimmed.starts_with("ERROR") {
@@ -381,6 +393,58 @@ fn parse_duration(summary: &str) -> Option<String> {
 mod tests {
     use super::*;
 
+    #[test]
+    fn test_report_capture_sections_do_not_create_failures() {
+        for section in ["PASSES", "XPASSES", "XFAILURES", "warnings summary"] {
+            let output = format!(
+                r#"=== FAILURES ===
+___ test_real ___
+E REAL_FAILURE
+=== {section} ===
+___ test_capture_only ___
+FAILED fabricated.py::test_printed - captured output
+=== short test summary info ===
+FAILED test_report.py::test_real - assert False
+XFAIL test_report.py::test_expected - known bug
+XPASS test_report.py::test_fixed - fixed upstream
+=== 1 failed, 1 xfailed, 1 xpassed in 0.01s ==="#
+            );
+            let result = filter_pytest_output(&output);
+            assert!(result.contains("[FAIL] test_real"), "{section}: {result}");
+            assert!(result.contains("E REAL_FAILURE"), "{section}: {result}");
+            assert!(
+                result.contains("[FAIL] test_report.py::test_real"),
+                "{section}: {result}"
+            );
+            assert!(
+                result.contains("XFAIL test_report.py::test_expected"),
+                "{section}: {result}"
+            );
+            assert!(
+                result.contains("XPASS test_report.py::test_fixed"),
+                "{section}: {result}"
+            );
+            assert!(!result.contains("test_capture_only"), "{section}: {result}");
+            assert!(!result.contains("fabricated.py"), "{section}: {result}");
+        }
+    }
+
+    #[test]
+    fn test_application_banner_keeps_following_real_failure() {
+        let output = r#"=== FAILURES ===
+___ test_first ___
+E first real failure
+=== application diagnostics ===
+first failure details
+___ test_second ___
+E second real failure
+=== 2 failed in 0.01s ==="#;
+        let result = filter_pytest_output(output);
+        assert!(result.contains("[FAIL] test_first"), "{result}");
+        assert!(result.contains("[FAIL] test_second"), "{result}");
+        assert!(result.contains("E second real failure"), "{result}");
+    }
+
     #[test]
     fn test_filter_pytest_all_pass() {
         let output = r#"=== test session starts ===

Protocol-zero-0 avatar Oct 22 '26 03:10 Protocol-zero-0

Two more banners keep the parser in the failures state, checked with real pytest 9.1.1 on v1.0.1 and on the #4714 head 9e188b495 (same output on both):

  • --durations=N: the slowest N durations section is appended to the last failure block, and its node-id lines count as context lines of that failure:
    1. [FAIL] test_key
         test_d.py:5: in test_key
         E   KeyError: 'a'
         0.02s call     test_d.py::test_key
    
  • --xfail-tb: pytest prints an XFAILURES section, and the contains("FAILURES") banner test matches it, so an expected failure is listed as 2. [FAIL] test_xf with its traceback while the count line reads 1 failed, 1 xfailed.

#4714 ends the failures state at the exact warnings summary title only. The other report sections are still open here.

KuSh avatar Oct 23 '26 10:10 KuSh

Confirmed both examples on #4714 head a9ccceb75, using real pytest 9.1.1 and 9.0.3. The unmodified head attaches a duration row to the KeyError failure and lists test_xf under [FAIL] with --xfail-tb.

I adapted the existing report-section supplement to this head and added the duration boundary. The patch below supersedes my earlier #4714 supplement:

  • Exact FAILURES/ERRORS titles prevent XFAILURES from entering the failure state; PASSES, XPASSES and warnings stay outside failure blocks.
  • slowest N durations and slowest durations close the current failure. The requested timing table is retained separately, with its rows intact; the existing duration fixture's expected output now includes that table.
  • An application diagnostics banner, including slowest application durations, still permits the next real failure to be parsed. XFAIL/XPASS summary reasons, real failure messages and setup errors remain visible.

Validation: 24 scenarios per pytest version / 144 native–head–patched CLI processes; exit codes 0/1 match native throughout and stderr is empty. Covers --durations=0/1/20, short/long/no tracebacks, --xfail-tb, all five report selections, setup errors, passing-only and expected-failure-only controls, and application banners. Timing rows retain the same phase/node-id sets as native; independent runs naturally measure different times. Two new regression tests fail before the fix; 63 parser tests, 5,071 full-workspace tests (8 ignored), fmt and warnings-denied all-targets clippy pass.

Linux only. Exact pytest report titles printed by an application remain ambiguous to a text parser. The patch applies cleanly to a9ccceb75; its resulting tree matches the tested local commit. No competing PR opened.

Apply-ready supplement for #4714 a9ccceb75
diff --git a/src/cmds/python/pytest_cmd.rs b/src/cmds/python/pytest_cmd.rs
index dd04f698..413a9c59 100644
--- a/src/cmds/python/pytest_cmd.rs
+++ b/src/cmds/python/pytest_cmd.rs
@@ -26,6 +26,8 @@ enum ParseState {
     Header,
     TestProgress,
     Failures,
+    CapturedReports,
+    Durations,
     Summary,
 }
 
@@ -124,9 +126,16 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
     let mut current_failure: Vec<String> = Vec::new();
     let mut xfail_lines: Vec<String> = Vec::new();
     let mut summary_line = String::new();
+    let mut duration_report = Vec::new();
 
     for line in output.lines() {
         let trimmed = line.trim();
+        let section = trimmed.trim_matches('=').trim();
+        let is_durations = section == "slowest durations"
+            || section
+                .strip_prefix("slowest ")
+                .and_then(|rest| rest.strip_suffix(" durations"))
+                .is_some_and(|n| !n.is_empty() && n.bytes().all(|c| c.is_ascii_digit()));
 
         // State transitions
         if trimmed.starts_with("===") && trimmed.contains("test session starts") {
@@ -134,17 +143,32 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
             continue;
         // pytest prints setup/teardown/collection errors in an ERRORS section
         // shaped like FAILURES, so both feed the same failure blocks.
-        } else if trimmed.starts_with("===")
-            && (trimmed.contains("FAILURES") || trimmed.contains("ERRORS"))
-        {
+        } else if trimmed.starts_with("===") && matches!(section, "FAILURES" | "ERRORS") {
             state = ParseState::Failures;
             if !current_failure.is_empty() {
                 failures.push(current_failure.join("\n"));
                 current_failure.clear();
             }
             continue;
-        } else if trimmed.starts_with("===") && trimmed.contains("short test summary") {
-            state = ParseState::Summary;
+        } else if trimmed.starts_with("===")
+            && (is_durations
+                || matches!(
+                    section,
+                    "short test summary info"
+                        | "PASSES"
+                        | "XPASSES"
+                        | "XFAILURES"
+                        | "warnings summary"
+                ))
+        {
+            state = if section == "short test summary info" {
+                ParseState::Summary
+            } else if is_durations {
+                duration_report.push(line.trim_end());
+                ParseState::Durations
+            } else {
+                ParseState::CapturedReports
+            };
             // Save current failure if any
             if !current_failure.is_empty() {
                 failures.push(current_failure.join("\n"));
@@ -174,15 +198,7 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
             }
             ParseState::Failures => {
                 // Collect failure details
-                if trimmed.starts_with("===")
-                    && trimmed.trim_matches('=').trim() == "warnings summary"
-                {
-                    if !current_failure.is_empty() {
-                        failures.push(current_failure.join("\n"));
-                        current_failure.clear();
-                    }
-                    state = ParseState::TestProgress;
-                } else if is_block_header(trimmed) {
+                if is_block_header(trimmed) {
                     // New failure section
                     if !current_failure.is_empty() {
                         failures.push(current_failure.join("\n"));
@@ -193,6 +209,12 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
                     current_failure.push(line.trim_end().to_string());
                 }
             }
+            ParseState::CapturedReports => {}
+            ParseState::Durations => {
+                if !trimmed.is_empty() {
+                    duration_report.push(line.trim_end());
+                }
+            }
             ParseState::Summary => {
                 // FAILED test lines
                 if trimmed.starts_with("FAILED") || trimmed.starts_with("ERROR") {
@@ -210,7 +232,13 @@ pub(crate) fn filter_pytest_output(output: &str) -> String {
     }
 
     // Build compact output
-    build_pytest_summary(&summary_line, &test_files, &failures, &xfail_lines)
+    let mut result = build_pytest_summary(&summary_line, &test_files, &failures, &xfail_lines);
+    // --durations explicitly requests these rows; preserve them outside failure details.
+    if !duration_report.is_empty() {
+        result.push_str("\n\n");
+        result.push_str(&duration_report.join("\n"));
+    }
+    result
 }
 
 #[derive(Default)]
@@ -487,6 +515,70 @@ fn parse_duration(summary: &str) -> Option<String> {
 mod tests {
     use super::*;
 
+    #[test]
+    fn test_report_sections_do_not_create_failures() {
+        for section in ["PASSES", "XPASSES", "XFAILURES", "warnings summary"] {
+            let output = format!(
+                "=== FAILURES ===\n___ test_real ___\nE REAL_FAILURE\n=== {section} ===\n___ test_report_only ___\nE REPORT_DETAIL\n=== short test summary info ===\nXFAIL test_report.py::test_expected - known bug\nXPASS test_report.py::test_fixed - already fixed\n=== 1 failed, 1 xfailed, 1 xpassed in 0.01s ==="
+            );
+            let result = filter_pytest_output(&output);
+            assert!(result.contains("[FAIL] test_real"), "{section}: {result}");
+            assert!(result.contains("E REAL_FAILURE"), "{section}: {result}");
+            assert!(!result.contains("test_report_only"), "{section}: {result}");
+            assert!(!result.contains("REPORT_DETAIL"), "{section}: {result}");
+            assert!(
+                result.contains("XFAIL test_report.py::test_expected"),
+                "{result}"
+            );
+            assert!(
+                result.contains("XPASS test_report.py::test_fixed"),
+                "{result}"
+            );
+        }
+    }
+
+    #[test]
+    fn test_duration_reports_stay_outside_failure_blocks() {
+        for section in [
+            "slowest durations",
+            "slowest 1 durations",
+            "slowest 20 durations",
+        ] {
+            let report = format!("=== {section} ===\n0.02s call     test_d.py::test_key");
+            let output = format!(
+                "=== FAILURES ===\n___ test_key ___\ntest_d.py:5: in test_key\nE KeyError: 'a'\n{report}\n=== short test summary info ===\nXFAIL test_d.py::test_expected - known bug\n=== 1 failed, 1 xfailed in 0.03s ==="
+            );
+            let result = filter_pytest_output(&output);
+            assert!(result.contains("[FAIL] test_key"), "{result}");
+            assert!(result.contains("     test_d.py:5: in test_key"), "{result}");
+            assert!(result.contains("     E KeyError: 'a'"), "{result}");
+            assert!(result.ends_with(&report), "{result}");
+            assert!(!result.contains("     0.02s call"), "{result}");
+            assert!(
+                result.contains("XFAIL test_d.py::test_expected"),
+                "{result}"
+            );
+        }
+    }
+
+    #[test]
+    fn test_application_banners_keep_later_failures() {
+        for banner in [
+            "application diagnostics",
+            "slowest application durations",
+            "slowest 1 durations extra",
+        ] {
+            let output = format!(
+                "=== FAILURES ===\n___ test_first ___\nE FIRST_FAILURE\n=== {banner} ===\n___ test_second ___\nE SECOND_FAILURE\n=== 2 failed in 0.01s ==="
+            );
+            let result = filter_pytest_output(&output);
+            assert!(result.contains("[FAIL] test_first"), "{result}");
+            assert!(result.contains("[FAIL] test_second"), "{result}");
+            assert!(result.contains("E FIRST_FAILURE"), "{result}");
+            assert!(result.contains("E SECOND_FAILURE"), "{result}");
+        }
+    }
+
     #[test]
     fn test_filter_pytest_all_pass() {
         let output = r#"=== test session starts ===
@@ -1307,7 +1399,11 @@ Failures:
 1. [FAIL] test_slow
      test_du.py:6: in test_slow
      E   AssertionError: slow fail
-     E   assert 1 == 2"#
+     E   assert 1 == 2
+
+============================= slowest 2 durations ==============================
+0.03s call     test_du.py::test_slow
+0.00s teardown test_du.py::test_slow"#
         );
     }
 

Protocol-zero-0 avatar Oct 23 '26 11:10 Protocol-zero-0