Skip to content
Open
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
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,7 @@ Xuan Luong
Xuecong Liao
Yannick Péroux
Yao Xiao
Ybucaille
Yoav Caspi
Yuliang Shao
Yury V. Zaytsev
Expand Down
1 change: 1 addition & 0 deletions changelog/10553.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed ``sys.stdout`` and ``sys.stderr`` replaced by a test being reset to the capture stream whenever capture was suspended and resumed, for example by live logging with :option:`--log-cli-level`.
9 changes: 8 additions & 1 deletion src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,7 @@ def __init__(
else:
tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old)
self.tmpfile = tmpfile
self._replaced: TextIO | None = None
self._state = "initialized"

def repr(self, class_name: str) -> str:
Expand Down Expand Up @@ -415,14 +416,20 @@ def done(self) -> None:

def suspend(self) -> None:
self._assert_state("suspend", ("started", "suspended"))
if self._state == "started":
# Remember a stream that the code under test installed in place of
# ours, so that resume() does not discard it.
current = getattr(sys, self.name)
self._replaced = None if current is self.tmpfile else current
setattr(sys, self.name, self._old)
self._state = "suspended"

def resume(self) -> None:
self._assert_state("resume", ("started", "suspended"))
if self._state == "started":
return
setattr(sys, self.name, self.tmpfile)
replaced, self._replaced = self._replaced, None
setattr(sys, self.name, self.tmpfile if replaced is None else replaced)
self._state = "started"


Expand Down
26 changes: 26 additions & 0 deletions testing/logging/test_reporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,32 @@ def test_foo():
result.stdout.no_re_match_line("DEBUG")


def test_log_cli_keeps_stdout_replaced_by_test(pytester: Pytester) -> None:
"""Live logging suspends and resumes capture; it must not undo a test's own
replacement of sys.stdout (#10553)."""
pytester.makepyfile(
"""
import io
import logging
import sys
def test_foo():
saved = sys.stdout
out = io.StringIO()
sys.stdout = out
try:
logging.warning("some log")
print("A")
assert sys.stdout is out
assert out.getvalue() == "A\\n"
finally:
sys.stdout = saved
"""
)
result = pytester.runpytest("--log-cli-level=INFO")
result.assert_outcomes(passed=1)


@pytest.mark.parametrize("level", ["20", '"20"', '"INFO"'])
def test_log_cli_level_toml(pytester: Pytester, level: str) -> None:
"""log_cli_level accepts a native TOML int as well as strings."""
Expand Down
Loading