Skip to content

fix(pytest): stop false 'No tests collected' on ANSI and double-quiet output - #2963

Closed
xuing wants to merge 1 commit into
rtk-ai:developfrom
xuing:fix/pytest-summary-ansi-and-double-quiet
Closed

xuing wants to merge 1 commit into
rtk-ai:developfrom
xuing:fix/pytest-summary-ansi-and-double-quiet

Conversation

@xuing

@xuing xuing commented Jul 12, 2026

Copy link
Copy Markdown

Summary

  • filter_pytest_output now strips ANSI before parsing — a colored \x1b[32m30 passed no longer parses to zero, and a colored 1 failed no longer drops out of the counts (a failing run was being reported as all-passed)
  • With no summary line at all (rtk's injected -q + a project's addopts = -q → -qq, which prints none), the filter now falls back to the raw output instead of claiming Pytest: No tests collected — per the Never Block principle: if the filter can't tell what happened, don't invent an answer
  • no tests ran in … is recognized as a genuine summary line, so a truly empty run still reports No tests collected exactly as before

Fixes #2960

Implementation notes

Test plan

  • test_filter_pytest_ansi_colored_summary — colored all-pass summary parses (was No tests collected)
  • test_filter_pytest_ansi_colored_failure_count_preserved — colored 1 failed, 1 passed keeps the failure (was Pytest: 1 passed)
  • test_filter_pytest_double_quiet_passthrough — no summary line → raw output, never No tests collected
  • Existing test_filter_pytest_no_tests (truly empty run) and test_filter_pytest_quiet_mode_failures (bug: rtk pytest -q incorrectly reports "Pytest: No tests collected" when tests are actually executed #565's regression test) still pass
  • End-to-end against a real project (addopts = -q, 20 passing tests): before Pytest: No tests collected, after the real pytest output
  • End-to-end with a colored failing run: before Pytest: 1 passed, after Pytest: 1 passed, 1 failed (exit 1 preserved)
  • cargo fmt --check && cargo clippy --all-targets && cargo test — 2441 passed, 0 failed, no new warnings

… output

Two unreported triggers made the summary parser report 'Pytest: No tests
collected' (and discard collected FAILURES) for runs that executed tests:

- ANSI: pytest colors output under FORCE_COLOR/PY_COLORS/CI; the wrapped
  count (\x1b[32m30 passed) fails the numeric parse. Worst case a colored
  '1 failed' silently drops the failure count, reporting a failing run as
  all-passed. Fixed by stripping escapes (core::utils::strip_ansi) before
  parsing.
- Double-quiet: rtk injects -q; a project with 'addopts = -q' in pytest.ini
  ends up at -qq, where pytest prints no final summary line at all. With no
  summary the filter cannot know what happened — fall back to the raw
  output (Never Block) instead of claiming nothing was collected. 'no tests
  ran in …' is now recognized as the one genuine no-tests summary, so the
  existing behavior for truly-empty runs is unchanged.

Related: rtk-ai#565 fixed the bare-quiet-summary variant; rtk-ai#2850/rtk-ai#2346 address the
collection-error variant — the passthrough here also stops those cases from
being masked until dedicated parsing lands.

Co-Authored-By: Claude Fable 5 <[email protected]>
Copilot AI review requested due to automatic review settings July 12, 2026 07:24
@CLAassistant

CLAassistant commented Jul 12, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens RTK’s pytest output filter to avoid false “No tests collected” summaries by stripping ANSI escape sequences before parsing and by falling back to passthrough when pytest prints no summary line (e.g., -qq).

Changes:

  • Strip ANSI escape codes prior to parsing pytest summary counts to prevent colored counts from parsing as zero.
  • Treat no tests ran in ... as a legitimate “empty run” summary line.
  • If no summary line is detected at all, return passthrough output instead of inventing Pytest: No tests collected, and add regression tests for these cases.

Review notes (requires change):

  • The new passthrough path (if summary_line.is_empty() { return output.trim_end().to_string(); }) does not actually return the raw output anymore because output is already replaced by strip_ansi(output) earlier. If the intent is “Never Block / raw output”, this should preserve the original input for passthrough (keep both raw_output and stripped_output).

@rtk-release-bot

Copy link
Copy Markdown
Contributor

This pull request has been automatically marked as stale due to 90 days of inactivity. If this pull request is still relevant, please leave any comment (for example, "bump"), and we'll keep it open. Your contribution is very much appreciated — we're sorry we haven't been able to review it yet.

@Protocol-zero-0 Protocol-zero-0 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ANSI fix and no-summary fallback work in the ordinary cases, but the fallback can still be bypassed by captured test output, so #2960 is not fully covered on 8db01c3.

With pytest 9.0.3, this minimal project reproduces it:

# pytest.ini
[pytest]
addopts = -q
# test_sample.py
def test_fail():
    print("no tests ran in 0.01s")
    assert False

rtk pytest -q --tb=short -rxX prints only Pytest: No tests collected and exits 1. The new contains("no tests ran") branch accepts the captured line as the session summary, so summary_line is nonempty and the fallback discards the real failure. Replacing the printed text with 99 passed in 0.01s yields only Pytest: 99 passed, also exit 1. That success-shaped variant also reproduces with explicit -qq.

Please validate the candidate's position in the complete output before treating it as a session summary, and preserve the failure output when there is no trusted terminal summary. Add regressions for both captured strings with config-driven double quiet and explicit quiet flags. ANSI removal alone is not enough to establish that a line came from pytest's summary.

Integration note: I reran the same cases against #3355 at b4c642c. Its anchored parser rejects the captured no tests ran case, but still accepts the captured success line when no real stats line follows. Neither PR alone closes that quiet-output gap; keep this fallback work coordinated with #3355 rather than treating one as a complete substitute for the other.

Validation: eight real pytest scenarios across raw pytest and both exact-head binaries (24 executions), identical exit codes in every comparison. Ordinary double-quiet pass/failure, colored mixed pass/failure, collection error and genuine empty collection were included. This head's 12 focused parser tests and fmt pass. Linux only; no full-suite, cross-platform or combined-tree validation in this review.

@KuSh

KuSh commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

Thank you for this fix. Stripping ANSI codes before parsing landed in #4465 (merged 2026-10-07), so a colored summary now parses on develop. The fallback for runs with no summary line now lives in the pytest run step, which since #3061 (merged 2026-07-24) passes raw output through based on pytest's exit code, and #3355 (merged 2026-10-19) pins the parser itself to report 'No tests collected' for summary-less input, so this change no longer fits the current code. A passing -qq run still prints 'No tests collected' at exit 0; that is tracked in #2960 and #4094 proposes it on the current model. Piping -qq output through rtk pipe --filter pytest has the same gap with no exit code to go on, and an issue or a narrow PR for it would be welcome. If I missed a part of this PR, please comment and it can be reopened.

@KuSh KuSh closed this Oct 23, 2026
@Protocol-zero-0

Copy link
Copy Markdown
Contributor

@KuSh I followed up on the stdin-only gap in your closure comment. This apply-ready patch is based on develop 0ac602b4d24fd017640211781b8d068742c37e4d.

rtk pipe --filter pytest has no producer exit code. It now requires a stats-shaped final nonblank line before compacting; otherwise it returns the original input byte-for-byte, including ANSI and failure details. The existing banner-based pytest auto-detection uses the same adapter. The pure parser and rtk pytest runner are unchanged, keeping this separate from #4094.

The baseline reduced 160 passing tests at -qq to Pytest: No tests collected. A failing test printing 99 passed in 0.01s was reduced to that false success summary. Both now preserve the complete original stream. Normal terminal summaries still compact.

Validation on Linux with real pytest 9.0.3 and 9.1.1: 30 native pytest executions and 136 base/patched pipe executions, including four derived interrupted/trailing-diagnostic streams. Covered explicit/config-driven quiet, colored progress, captured summary lookalikes, fixture/collection errors, empty/deselected suites and normal summaries. Five CLI regression tests: baseline four fail / one control passes; patched all five pass. The 48 pipe and 22 pytest unit tests pass, as do the full workspace (5,106 passed / 8 ignored), root/proxy fmt and warnings-denied all-targets clippy.

One separate inherited behavior surfaced: without a pytest banner, generic auto-detection can select grep for quiet tracebacks; that output is identical in baseline and patched. Use the explicit pytest filter for these streams. This patch does not infer test counts from dots or recover the producer's exit status, and a terminal lookalike from arbitrary plugin output remains ambiguous. No other-platform or pending-PR combination validation.

Apply-ready patch, including CLI regressions
diff --git a/src/cmds/python/pytest_cmd.rs b/src/cmds/python/pytest_cmd.rs
index f609ecda..1243db52 100644
--- a/src/cmds/python/pytest_cmd.rs
+++ b/src/cmds/python/pytest_cmd.rs
@@ -85,6 +85,28 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
 const PYTEST_NO_TESTS: &str = "Pytest: No tests collected";
 const PYTEST_EXIT_NO_TESTS: i32 = 5;
 
+/// Stdin has no pytest exit code: only compact a recognized terminal summary.
+pub(crate) fn filter_pytest_stdin(output: &str) -> String {
+    let cleaned = strip_ansi(output);
+    let has_terminal_summary = cleaned
+        .lines()
+        .rev()
+        .find(|line| !line.trim().is_empty())
+        .is_some_and(|line| PYTEST_SUMMARY_RE.is_match(line.trim()));
+    if !has_terminal_summary {
+        // Quiet runs, startup errors and incomplete streams can all omit stats.
+        // Preserve the original bytes, including ANSI, rather than infer a result.
+        return output.to_string();
+    }
+
+    let filtered = filter_pytest_output(output);
+    if filtered == PYTEST_NO_TESTS {
+        output.to_string()
+    } else {
+        filtered
+    }
+}
+
 pub(crate) fn filter_pytest_output(output: &str) -> String {
     // pytest colors its summary even when piped (force-color CI/venv setups), and the
     // `N passed` / FAILURES anchors below never match through ANSI codes. The parser owns
diff --git a/src/cmds/system/pipe_cmd.rs b/src/cmds/system/pipe_cmd.rs
index e5161c6d..b7f075bb 100644
--- a/src/cmds/system/pipe_cmd.rs
+++ b/src/cmds/system/pipe_cmd.rs
@@ -12,7 +12,7 @@ const MAX_PIPE_DIRS: usize = CAP_LIST;
 pub fn resolve_filter(name: &str) -> Option<fn(&str) -> String> {
     match name {
         "cargo-test" | "cargo" => Some(crate::cmds::rust::cargo_cmd::filter_cargo_test),
-        "pytest" => Some(crate::cmds::python::pytest_cmd::filter_pytest_output),
+        "pytest" => Some(crate::cmds::python::pytest_cmd::filter_pytest_stdin),
         "go-test" => Some(go_test_wrapper),
         "go-build" => Some(crate::cmds::go::go_cmd::filter_go_build),
         "ctest" => Some(crate::cmds::system::ctest_cmd::filter_ctest_output),
@@ -181,7 +181,7 @@ pub fn auto_detect_filter(input: &str) -> fn(&str) -> String {
     }
 
     if first_1k.contains("=== test session starts") {
-        return crate::cmds::python::pytest_cmd::filter_pytest_output;
+        return crate::cmds::python::pytest_cmd::filter_pytest_stdin;
     }
 
     if crate::cmds::system::ctest_cmd::looks_like_ctest_output(first_1k) {
diff --git a/tests/pytest_pipe_test.rs b/tests/pytest_pipe_test.rs
new file mode 100644
index 00000000..5657d07b
--- /dev/null
+++ b/tests/pytest_pipe_test.rs
@@ -0,0 +1,92 @@
+use std::io::Write;
+use std::process::Stdio;
+
+mod common;
+
+fn pipe(input: &str, explicit: bool) -> String {
+    let mut cmd = common::rtk_command();
+    cmd.arg("pipe");
+    if explicit {
+        cmd.args(["--filter", "pytest"]);
+    }
+    let mut child = cmd
+        .stdin(Stdio::piped())
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .spawn()
+        .expect("start rtk pipe");
+    child
+        .stdin
+        .take()
+        .unwrap()
+        .write_all(input.as_bytes())
+        .unwrap();
+    let output = child.wait_with_output().unwrap();
+    assert!(output.status.success(), "{output:?}");
+    assert!(output.stderr.is_empty(), "{output:?}");
+    String::from_utf8(output.stdout).unwrap()
+}
+
+#[test]
+fn summaryless_quiet_progress_is_verbatim() {
+    // A sufficiently long progress line exposes the bug even through never_worse.
+    for input in [
+        format!("{} [100%]\n", ".".repeat(120)),
+        format!("\x1b[32m{} [100%]\x1b[0m\n", ".".repeat(120)),
+    ] {
+        assert_eq!(pipe(&input, true), input);
+    }
+}
+
+#[test]
+fn summaryless_failure_is_verbatim_in_explicit_and_auto_modes() {
+    let input = "================ test session starts ================\n\
+                 collected 1 item\n\
+                 tests/test_sample.py F [100%]\n\
+                 ==================== FAILURES ====================\n\
+                 ____________________ test_fail ____________________\n\
+                 E   AssertionError: PIPE_FAILURE_MUST_SURVIVE\n";
+    for explicit in [true, false] {
+        assert_eq!(pipe(input, explicit), input);
+    }
+}
+
+#[test]
+fn captured_summary_before_failure_tail_is_not_a_result() {
+    let input = "================ test session starts ================\n\
+                 collected 1 item\n\
+                 ==================== FAILURES ====================\n\
+                 ____________________ test_fail ____________________\n\
+                 ---------------- Captured stdout call ----------------\n\
+                 99 passed in 0.01s\n\
+                 ================ short test summary info ================\n\
+                 FAILED tests/test_sample.py::test_fail - AssertionError\n";
+    for explicit in [true, false] {
+        assert_eq!(pipe(input, explicit), input);
+    }
+}
+
+#[test]
+fn empty_collection_and_unrecognized_text_are_verbatim() {
+    for input in [
+        "",
+        "   \n\n",
+        "================ test session starts ================\nno tests ran in 0.01s\n",
+        "pytest: error: unrecognized arguments: --unknown-option-with-details\n",
+        "================ test session starts ================\n1 warning in 0.01s\n",
+    ] {
+        assert_eq!(pipe(input, true), input);
+    }
+}
+
+#[test]
+fn terminal_summary_still_compacts_in_explicit_and_auto_modes() {
+    let input = "================ test session starts ================\n\
+                 platform linux -- Python 3.13, pytest-9.1.1\n\
+                 collected 120 items\n\
+                 tests/test_sample.py .................................. [100%]\n\
+                 \x1b[32m================ 120 passed in 0.12s ================\x1b[0m\n\n";
+    for explicit in [true, false] {
+        assert_eq!(pipe(input, explicit), "Pytest: 120 passed in 0.12s");
+    }
+}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pytest filter reports "No tests collected" for runs that executed tests; a colored '1 failed' vanishes from the summary

5 participants