Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -449,6 +449,8 @@ class SysCapture(SysCaptureBase[str]):

def snap(self) -> str:
self._assert_state("snap", ("started", "suspended"))
if getattr(self.tmpfile, "closed", False):
return self.EMPTY_BUFFER
assert isinstance(self.tmpfile, CaptureIO)
res = self.tmpfile.getvalue()
self.tmpfile.seek(0)
Expand Down Expand Up @@ -566,6 +568,8 @@ class FDCaptureBinary(FDCaptureBase[bytes]):

def snap(self) -> bytes:
self._assert_state("snap", ("started", "suspended"))
if getattr(self.tmpfile, "closed", False):
return self.EMPTY_BUFFER
self.tmpfile.seek(0)
res = self.tmpfile.buffer.read()
self.tmpfile.seek(0)
Expand All @@ -588,6 +592,8 @@ class FDCapture(FDCaptureBase[str]):

def snap(self) -> str:
self._assert_state("snap", ("started", "suspended"))
if getattr(self.tmpfile, "closed", False):
return self.EMPTY_BUFFER
self.tmpfile.seek(0)
res = self.tmpfile.read()
self.tmpfile.seek(0)
Expand Down
27 changes: 27 additions & 0 deletions testing/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -1750,3 +1750,30 @@ def pytest_terminal_summary(config):
match = re.search(r"^value: '(.*)'\r?$", rest, re.MULTILINE)
assert match is not None
assert match.group(1) == "hi"


def test_snap_on_closed_tmpfile() -> None:
"""Regression test for #14528: snap() should not crash when tmpfile is closed."""
# FDCapture
cap = capture.FDCapture(1)
cap.start()
cap.done()
assert cap.snap() == ""

# FDCaptureBinary
capb = capture.FDCaptureBinary(1)
capb.start()
capb.done()
assert capb.snap() == b""

# SysCapture
caps = capture.SysCapture(1)
caps.start()
caps.done()
assert caps.snap() == ""

# SysCaptureBinary
capsb = capture.SysCaptureBinary(1)
capsb.start()
capsb.done()
assert capsb.snap() == b""
Loading