Print each failing test's error lines, which pytest-xdist leaves out of the short summary

This commit is contained in:
2026-11-12 08:41:13 +01:00
parent e4e3d8cff0
commit e86a0cbc0c
3 changed files with 69 additions and 15 deletions
+33 -8
View File
@@ -4,9 +4,9 @@ usage: run-tests [<pytest args>...]
It runs pytest, pinned with pytest-xdist in four workers through uvx, on the arguments given,
adding the repo's bin/ folder where none of them names a path that exists. It saves the whole
output to a new file and prints pytest's short test summary, a line per failing test with its
error, then pytest's summary line, then `Full log: <path>`. Where pytest printed no summary line,
it prints the log's last lines in their place.
output to a new file. It prints each failing test's name, its first error lines and where it
failed, then pytest's short test summary and summary line, then `Full log: <path>`. Where pytest
printed no summary line, it prints the log's last lines in their place.
Exit 0 where every test passed, 1 otherwise, or where pytest cannot start, saying why.
"""
@@ -21,9 +21,13 @@ import tempfile
BIN = pathlib.Path(__file__).resolve().parents[1]
# README.md → Test names these pins, and ci.sh runs this command, so they live here alone.
PYTEST = ["uvx", "--python", shutil.which("python3") or sys.executable, "--with", "pytest-xdist==3.8.0", "pytest==9.2.0", "-n", "4"]
SUMMARY_HEADER = re.compile(r"^=+ short test summary info =+$")
SECTION = re.compile(r"^=+ (.+) =+$")
TEST_HEADER = re.compile(r"^_+ .+ _+$")
# A traceback's last line, such as `bin/x/test_x.py:12: AssertionError`.
LOCATION = re.compile(r"^\S+:\d+: \S")
# pytest's last line, such as `==== 2 failed, 1 passed in 0.31s ====`, or without the rules under -q.
SUMMARY_LINE = re.compile(r"^(=+ )?(no tests ran|\d+ \w+).* in [\d.]+s\b.*$")
ERROR_LINES = 10
LOG_TAIL = 20
@@ -35,14 +39,35 @@ def pytest_args(argv: list[str]) -> list[str]:
def report(log: str) -> list[str]:
"""The short test summary and the summary line from pytest's output, or [] where it printed no summary line."""
"""What to print of pytest's output: each failing test's header, error lines and location, then the short test summary and the summary line; [] where pytest printed no summary line.
The error lines come from the FAILURES and ERRORS sections, since pytest-xdist leaves them out of the short summary's lines."""
lines = log.splitlines()
ends = [index for index, line in enumerate(lines) if SUMMARY_LINE.match(line)]
if not ends:
return []
end = ends[-1]
starts = [index for index, line in enumerate(lines[:end]) if SUMMARY_HEADER.match(line)]
return lines[starts[-1] + 1:end + 1] if starts else [lines[end]]
printed: list[str] = []
section = ""
errors = 0
for line in lines[:ends[-1]]:
heading = SECTION.match(line)
if heading:
section = heading.group(1)
elif section in ("FAILURES", "ERRORS"):
if TEST_HEADER.match(line):
errors = 0
printed.append(line)
elif line.startswith("E "):
errors += 1
if errors <= ERROR_LINES:
printed.append(line)
elif LOCATION.match(line):
if errors > ERROR_LINES:
printed.append(f"E … {errors - ERROR_LINES} more lines in the log")
printed.append(line)
elif section == "short test summary info":
printed.append(line)
return [*printed, lines[ends[-1]]]
def run(argv: list[str], pytest: list[str] = PYTEST, cwd: str | None = None) -> int:
+13 -7
View File
@@ -3,6 +3,7 @@ import importlib.util
import io
import os
import pathlib
import re
import sys
import tempfile
import unittest
@@ -14,7 +15,8 @@ from run_tests import main
BIN = pathlib.Path(__file__).resolve().parents[1]
# The suite runs under pytest, and `python3 -m unittest` may run it where pytest is not installed.
HAS_PYTEST = importlib.util.find_spec("pytest") is not None
PYTEST_HERE = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider", "-p", "no:xdist"]
HAS_XDIST = importlib.util.find_spec("xdist") is not None
PYTEST_HERE = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider"]
class PytestArgs(unittest.TestCase):
@@ -60,17 +62,21 @@ class Run(unittest.TestCase):
self.assertIn("noise from a passing test", self.log_named(output).read_text())
def test_a_failing_run_prints_each_failing_test_with_its_error(self):
# pytest-xdist drops the error from the short summary's lines, so the run takes it from the FAILURES section.
workers = ["-n", "2"] if HAS_XDIST else []
with tempfile.TemporaryDirectory() as folder:
pathlib.Path(folder, "test_bad.py").write_text("def test_ok():\n\tpass\n\ndef test_bad():\n\tassert 1 == 2, 'one is not two'\n\ndef test_worse():\n\traise KeyError('missing')\n")
code, output = self.run_in(folder, PYTEST_HERE, folder)
pathlib.Path(folder, "test_bad.py").write_text("def test_ok():\n\tpass\n\ndef test_bad():\n\tassert 1 == 2, 'one is not two'\n\ndef test_long():\n\traise ValueError('\\n'.join(map(str, range(30))))\n")
code, output = self.run_in(folder, PYTEST_HERE, *workers, folder)
self.assertEqual(code, 1)
self.assertRegex(output, r"FAILED .*test_bad\.py::test_bad - AssertionError: one is not two")
self.assertRegex(output, r"FAILED .*test_bad\.py::test_worse - KeyError: 'missing'")
self.assertRegex(output, r"(?m)^_+ test_bad _+\nE +AssertionError: one is not two\n(E .*\n)*.*test_bad\.py:5: AssertionError$")
self.assertRegex(output, r"(?m)^FAILED .*test_bad\.py::test_bad\b")
self.assertRegex(output, r"(?m)^E +… \d+ more lines in the log$")
self.assertEqual(len(re.findall(r"(?m)^E ", output)), 2 + main.ERROR_LINES + 1)
self.assertRegex(output, r"=+ 2 failed, 1 passed in .* =+\n")
self.assertNotIn("def test_ok", output)
self.assertNotIn("def test_bad", output)
self.assertIn("def test_bad", self.log_named(output).read_text())
def test_a_run_that_cannot_start_says_so_and_prints_the_logs_last_lines(self):
def test_a_run_that_cannot_start_says_so(self):
with tempfile.TemporaryDirectory() as folder:
code, output = self.run_in(folder, [os.path.join(folder, "no-such-uvx")])
self.assertEqual(code, 1)