From 2786ed2cc8d93ebf3470a52677a722b7f4dc4030 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Tue, 7 Jul 2026 10:06:50 -0400 Subject: [PATCH 1/2] perf(capture): skip reading the capture file when nothing was written FDCapture.snap() did seek/read/seek/truncate through the TextIOWrapper on every test phase even when the test produced no output. Since the tmpfile is unbuffered, a single fstat can prove it is empty and skip all of that. For suites of many small quiet tests this removes ~6 of these cycles per test (2 streams x 3 phases); on pypa/packaging (62k tests) it cuts the total runtime by about 8%. Assisted-by: ClaudeCode:claude-fable-5 Signed-off-by: Henry Schreiner --- src/_pytest/capture.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/_pytest/capture.py b/src/_pytest/capture.py index f9f8f9e4a28..b914bc2831c 100644 --- a/src/_pytest/capture.py +++ b/src/_pytest/capture.py @@ -566,6 +566,9 @@ class FDCaptureBinary(FDCaptureBase[bytes]): def snap(self) -> bytes: self._assert_state("snap", ("started", "suspended")) + # Avoid seek/read/truncate in the common case of no output. + if os.fstat(self.tmpfile.fileno()).st_size == 0: + return self.EMPTY_BUFFER self.tmpfile.seek(0) res = self.tmpfile.buffer.read() self.tmpfile.seek(0) @@ -588,6 +591,9 @@ class FDCapture(FDCaptureBase[str]): def snap(self) -> str: self._assert_state("snap", ("started", "suspended")) + # Avoid seek/read/truncate in the common case of no output. + if os.fstat(self.tmpfile.fileno()).st_size == 0: + return self.EMPTY_BUFFER self.tmpfile.seek(0) res = self.tmpfile.read() self.tmpfile.seek(0) From ed25347e12d7bb6413b638505691a1622c033772 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Tue, 7 Jul 2026 10:35:13 -0400 Subject: [PATCH 2/2] docs: add changelog entry and AUTHORS for #14687 Assisted-by: ClaudeCode:claude-fable-5 --- AUTHORS | 1 + changelog/14687.improvement.rst | 1 + 2 files changed, 2 insertions(+) create mode 100644 changelog/14687.improvement.rst diff --git a/AUTHORS b/AUTHORS index 33ee644ea68..ca0f329466f 100644 --- a/AUTHORS +++ b/AUTHORS @@ -204,6 +204,7 @@ Hamza Mobeen Harald Armin Massa Harshna Henk-Jaap Wagenaar +Henry Schreiner Holger Kohr Hugo van Kemenade Hui Wang (coldnight) diff --git a/changelog/14687.improvement.rst b/changelog/14687.improvement.rst new file mode 100644 index 00000000000..04bef6173c9 --- /dev/null +++ b/changelog/14687.improvement.rst @@ -0,0 +1 @@ +The default fd-level output capturing (``--capture=fd``) now skips reading the capture buffer for tests which produce no output, reducing per-test overhead in large test suites.