| 1 |
# mypy: allow-untyped-defs |
| 2 |
"""Per-test stdout/stderr capturing mechanism.""" |
| 3 |
|
| 4 |
import abc |
| 5 |
import collections |
| 6 |
import contextlib |
| 7 |
import io |
| 8 |
from io import UnsupportedOperation |
| 9 |
import os |
| 10 |
import sys |
| 11 |
from tempfile import TemporaryFile |
| 12 |
from types import TracebackType |
| 13 |
from typing import Any |
| 14 |
from typing import AnyStr |
| 15 |
from typing import BinaryIO |
| 16 |
from typing import Final |
| 17 |
from typing import final |
| 18 |
from typing import Generator |
| 19 |
from typing import Generic |
| 20 |
from typing import Iterable |
| 21 |
from typing import Iterator |
| 22 |
from typing import List |
| 23 |
from typing import Literal |
| 24 |
from typing import NamedTuple |
| 25 |
from typing import Optional |
| 26 |
from typing import TextIO |
| 27 |
from typing import Tuple |
| 28 |
from typing import Type |
| 29 |
from typing import TYPE_CHECKING |
| 30 |
from typing import Union |
| 31 |
|
| 32 |
from _pytest.config import Config |
| 33 |
from _pytest.config import hookimpl |
| 34 |
from _pytest.config.argparsing import Parser |
| 35 |
from _pytest.deprecated import check_ispytest |
| 36 |
from _pytest.fixtures import fixture |
| 37 |
from _pytest.fixtures import SubRequest |
| 38 |
from _pytest.nodes import Collector |
| 39 |
from _pytest.nodes import File |
| 40 |
from _pytest.nodes import Item |
| 41 |
from _pytest.reports import CollectReport |
| 42 |
|
| 43 |
|
| 44 |
_CaptureMethod = Literal["fd", "sys", "no", "tee-sys"] |
| 45 |
|
| 46 |
|
| 47 |
def pytest_addoption(parser: Parser) -> None: |
| 48 |
group = parser.getgroup("general") |
| 49 |
group._addoption( |
| 50 |
"--capture", |
| 51 |
action="store", |
| 52 |
default="fd", |
| 53 |
metavar="method", |
| 54 |
choices=["fd", "sys", "no", "tee-sys"], |
| 55 |
help="Per-test capturing method: one of fd|sys|no|tee-sys", |
| 56 |
) |
| 57 |
group._addoption( |
| 58 |
"-s", |
| 59 |
action="store_const", |
| 60 |
const="no", |
| 61 |
dest="capture", |
| 62 |
help="Shortcut for --capture=no", |
| 63 |
) |
| 64 |
|
| 65 |
|
| 66 |
def _colorama_workaround() -> None: |
| 67 |
"""Ensure colorama is imported so that it attaches to the correct stdio |
| 68 |
handles on Windows. |
| 69 |
|
| 70 |
colorama uses the terminal on import time. So if something does the |
| 71 |
first import of colorama while I/O capture is active, colorama will |
| 72 |
fail in various ways. |
| 73 |
""" |
| 74 |
if sys.platform.startswith("win32"): |
| 75 |
try: |
| 76 |
import colorama # noqa: F401 |
| 77 |
except ImportError: |
| 78 |
pass |
| 79 |
|
| 80 |
|
| 81 |
def _windowsconsoleio_workaround(stream: TextIO) -> None: |
| 82 |
"""Workaround for Windows Unicode console handling. |
| 83 |
|
| 84 |
Python 3.6 implemented Unicode console handling for Windows. This works |
| 85 |
by reading/writing to the raw console handle using |
| 86 |
``{Read,Write}ConsoleW``. |
| 87 |
|
| 88 |
The problem is that we are going to ``dup2`` over the stdio file |
| 89 |
descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the |
| 90 |
handles used by Python to write to the console. Though there is still some |
| 91 |
weirdness and the console handle seems to only be closed randomly and not |
| 92 |
on the first call to ``CloseHandle``, or maybe it gets reopened with the |
| 93 |
same handle value when we suspend capturing. |
| 94 |
|
| 95 |
The workaround in this case will reopen stdio with a different fd which |
| 96 |
also means a different handle by replicating the logic in |
| 97 |
"Py_lifecycle.c:initstdio/create_stdio". |
| 98 |
|
| 99 |
:param stream: |
| 100 |
In practice ``sys.stdout`` or ``sys.stderr``, but given |
| 101 |
here as parameter for unittesting purposes. |
| 102 |
|
| 103 |
See https://github.com/pytest-dev/py/issues/103. |
| 104 |
""" |
| 105 |
if not sys.platform.startswith("win32") or hasattr(sys, "pypy_version_info"): |
| 106 |
return |
| 107 |
|
| 108 |
# Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666). |
| 109 |
if not hasattr(stream, "buffer"): # type: ignore[unreachable,unused-ignore] |
| 110 |
return |
| 111 |
|
| 112 |
raw_stdout = stream.buffer.raw if hasattr(stream.buffer, "raw") else stream.buffer |
| 113 |
|
| 114 |
if not isinstance(raw_stdout, io._WindowsConsoleIO): # type: ignore[attr-defined,unused-ignore] |
| 115 |
return |
| 116 |
|
| 117 |
def _reopen_stdio(f, mode): |
| 118 |
if not hasattr(stream.buffer, "raw") and mode[0] == "w": |
| 119 |
buffering = 0 |
| 120 |
else: |
| 121 |
buffering = -1 |
| 122 |
|
| 123 |
return io.TextIOWrapper( |
| 124 |
open(os.dup(f.fileno()), mode, buffering), |
| 125 |
f.encoding, |
| 126 |
f.errors, |
| 127 |
f.newlines, |
| 128 |
f.line_buffering, |
| 129 |
) |
| 130 |
|
| 131 |
sys.stdin = _reopen_stdio(sys.stdin, "rb") |
| 132 |
sys.stdout = _reopen_stdio(sys.stdout, "wb") |
| 133 |
sys.stderr = _reopen_stdio(sys.stderr, "wb") |
| 134 |
|
| 135 |
|
| 136 |
@hookimpl(wrapper=True) |
| 137 |
def pytest_load_initial_conftests(early_config: Config) -> Generator[None, None, None]: |
| 138 |
ns = early_config.known_args_namespace |
| 139 |
if ns.capture == "fd": |
| 140 |
_windowsconsoleio_workaround(sys.stdout) |
| 141 |
_colorama_workaround() |
| 142 |
pluginmanager = early_config.pluginmanager |
| 143 |
capman = CaptureManager(ns.capture) |
| 144 |
pluginmanager.register(capman, "capturemanager") |
| 145 |
|
| 146 |
# Make sure that capturemanager is properly reset at final shutdown. |
| 147 |
early_config.add_cleanup(capman.stop_global_capturing) |
| 148 |
|
| 149 |
# Finally trigger conftest loading but while capturing (issue #93). |
| 150 |
capman.start_global_capturing() |
| 151 |
try: |
| 152 |
try: |
| 153 |
yield |
| 154 |
finally: |
| 155 |
capman.suspend_global_capture() |
| 156 |
except BaseException: |
| 157 |
out, err = capman.read_global_capture() |
| 158 |
sys.stdout.write(out) |
| 159 |
sys.stderr.write(err) |
| 160 |
raise |
| 161 |
|
| 162 |
|
| 163 |
# IO Helpers. |
| 164 |
|
| 165 |
|
| 166 |
class EncodedFile(io.TextIOWrapper): |
| 167 |
__slots__ = () |
| 168 |
|
| 169 |
@property |
| 170 |
def name(self) -> str: |
| 171 |
# Ensure that file.name is a string. Workaround for a Python bug |
| 172 |
# fixed in >=3.7.4: https://bugs.python.org/issue36015 |
| 173 |
return repr(self.buffer) |
| 174 |
|
| 175 |
@property |
| 176 |
def mode(self) -> str: |
| 177 |
# TextIOWrapper doesn't expose a mode, but at least some of our |
| 178 |
# tests check it. |
| 179 |
return self.buffer.mode.replace("b", "") |
| 180 |
|
| 181 |
|
| 182 |
class CaptureIO(io.TextIOWrapper): |
| 183 |
def __init__(self) -> None: |
| 184 |
super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True) |
| 185 |
|
| 186 |
def getvalue(self) -> str: |
| 187 |
assert isinstance(self.buffer, io.BytesIO) |
| 188 |
return self.buffer.getvalue().decode("UTF-8") |
| 189 |
|
| 190 |
|
| 191 |
class TeeCaptureIO(CaptureIO): |
| 192 |
def __init__(self, other: TextIO) -> None: |
| 193 |
self._other = other |
| 194 |
super().__init__() |
| 195 |
|
| 196 |
def write(self, s: str) -> int: |
| 197 |
super().write(s) |
| 198 |
return self._other.write(s) |
| 199 |
|
| 200 |
|
| 201 |
class DontReadFromInput(TextIO): |
| 202 |
@property |
| 203 |
def encoding(self) -> str: |
| 204 |
return sys.__stdin__.encoding |
| 205 |
|
| 206 |
def read(self, size: int = -1) -> str: |
| 207 |
raise OSError( |
| 208 |
"pytest: reading from stdin while output is captured! Consider using `-s`." |
| 209 |
) |
| 210 |
|
| 211 |
readline = read |
| 212 |
|
| 213 |
def __next__(self) -> str: |
| 214 |
return self.readline() |
| 215 |
|
| 216 |
def readlines(self, hint: Optional[int] = -1) -> List[str]: |
| 217 |
raise OSError( |
| 218 |
"pytest: reading from stdin while output is captured! Consider using `-s`." |
| 219 |
) |
| 220 |
|
| 221 |
def __iter__(self) -> Iterator[str]: |
| 222 |
return self |
| 223 |
|
| 224 |
def fileno(self) -> int: |
| 225 |
raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()") |
| 226 |
|
| 227 |
def flush(self) -> None: |
| 228 |
raise UnsupportedOperation("redirected stdin is pseudofile, has no flush()") |
| 229 |
|
| 230 |
def isatty(self) -> bool: |
| 231 |
return False |
| 232 |
|
| 233 |
def close(self) -> None: |
| 234 |
pass |
| 235 |
|
| 236 |
def readable(self) -> bool: |
| 237 |
return False |
| 238 |
|
| 239 |
def seek(self, offset: int, whence: int = 0) -> int: |
| 240 |
raise UnsupportedOperation("redirected stdin is pseudofile, has no seek(int)") |
| 241 |
|
| 242 |
def seekable(self) -> bool: |
| 243 |
return False |
| 244 |
|
| 245 |
def tell(self) -> int: |
| 246 |
raise UnsupportedOperation("redirected stdin is pseudofile, has no tell()") |
| 247 |
|
| 248 |
def truncate(self, size: Optional[int] = None) -> int: |
| 249 |
raise UnsupportedOperation("cannot truncate stdin") |
| 250 |
|
| 251 |
def write(self, data: str) -> int: |
| 252 |
raise UnsupportedOperation("cannot write to stdin") |
| 253 |
|
| 254 |
def writelines(self, lines: Iterable[str]) -> None: |
| 255 |
raise UnsupportedOperation("Cannot write to stdin") |
| 256 |
|
| 257 |
def writable(self) -> bool: |
| 258 |
return False |
| 259 |
|
| 260 |
def __enter__(self) -> "DontReadFromInput": |
| 261 |
return self |
| 262 |
|
| 263 |
def __exit__( |
| 264 |
self, |
| 265 |
type: Optional[Type[BaseException]], |
| 266 |
value: Optional[BaseException], |
| 267 |
traceback: Optional[TracebackType], |
| 268 |
) -> None: |
| 269 |
pass |
| 270 |
|
| 271 |
@property |
| 272 |
def buffer(self) -> BinaryIO: |
| 273 |
# The str/bytes doesn't actually matter in this type, so OK to fake. |
| 274 |
return self # type: ignore[return-value] |
| 275 |
|
| 276 |
|
| 277 |
# Capture classes. |
| 278 |
|
| 279 |
|
| 280 |
class CaptureBase(abc.ABC, Generic[AnyStr]): |
| 281 |
EMPTY_BUFFER: AnyStr |
| 282 |
|
| 283 |
@abc.abstractmethod |
| 284 |
def __init__(self, fd: int) -> None: |
| 285 |
raise NotImplementedError() |
| 286 |
|
| 287 |
@abc.abstractmethod |
| 288 |
def start(self) -> None: |
| 289 |
raise NotImplementedError() |
| 290 |
|
| 291 |
@abc.abstractmethod |
| 292 |
def done(self) -> None: |
| 293 |
raise NotImplementedError() |
| 294 |
|
| 295 |
@abc.abstractmethod |
| 296 |
def suspend(self) -> None: |
| 297 |
raise NotImplementedError() |
| 298 |
|
| 299 |
@abc.abstractmethod |
| 300 |
def resume(self) -> None: |
| 301 |
raise NotImplementedError() |
| 302 |
|
| 303 |
@abc.abstractmethod |
| 304 |
def writeorg(self, data: AnyStr) -> None: |
| 305 |
raise NotImplementedError() |
| 306 |
|
| 307 |
@abc.abstractmethod |
| 308 |
def snap(self) -> AnyStr: |
| 309 |
raise NotImplementedError() |
| 310 |
|
| 311 |
|
| 312 |
patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"} |
| 313 |
|
| 314 |
|
| 315 |
class NoCapture(CaptureBase[str]): |
| 316 |
EMPTY_BUFFER = "" |
| 317 |
|
| 318 |
def __init__(self, fd: int) -> None: |
| 319 |
pass |
| 320 |
|
| 321 |
def start(self) -> None: |
| 322 |
pass |
| 323 |
|
| 324 |
def done(self) -> None: |
| 325 |
pass |
| 326 |
|
| 327 |
def suspend(self) -> None: |
| 328 |
pass |
| 329 |
|
| 330 |
def resume(self) -> None: |
| 331 |
pass |
| 332 |
|
| 333 |
def snap(self) -> str: |
| 334 |
return "" |
| 335 |
|
| 336 |
def writeorg(self, data: str) -> None: |
| 337 |
pass |
| 338 |
|
| 339 |
|
| 340 |
class SysCaptureBase(CaptureBase[AnyStr]): |
| 341 |
def __init__( |
| 342 |
self, fd: int, tmpfile: Optional[TextIO] = None, *, tee: bool = False |
| 343 |
) -> None: |
| 344 |
name = patchsysdict[fd] |
| 345 |
self._old: TextIO = getattr(sys, name) |
| 346 |
self.name = name |
| 347 |
if tmpfile is None: |
| 348 |
if name == "stdin": |
| 349 |
tmpfile = DontReadFromInput() |
| 350 |
else: |
| 351 |
tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old) |
| 352 |
self.tmpfile = tmpfile |
| 353 |
self._state = "initialized" |
| 354 |
|
| 355 |
def repr(self, class_name: str) -> str: |
| 356 |
return "<{} {} _old={} _state={!r} tmpfile={!r}>".format( |
| 357 |
class_name, |
| 358 |
self.name, |
| 359 |
hasattr(self, "_old") and repr(self._old) or "<UNSET>", |
| 360 |
self._state, |
| 361 |
self.tmpfile, |
| 362 |
) |
| 363 |
|
| 364 |
def __repr__(self) -> str: |
| 365 |
return "<{} {} _old={} _state={!r} tmpfile={!r}>".format( |
| 366 |
self.__class__.__name__, |
| 367 |
self.name, |
| 368 |
hasattr(self, "_old") and repr(self._old) or "<UNSET>", |
| 369 |
self._state, |
| 370 |
self.tmpfile, |
| 371 |
) |
| 372 |
|
| 373 |
def _assert_state(self, op: str, states: Tuple[str, ...]) -> None: |
| 374 |
assert ( |
| 375 |
self._state in states |
| 376 |
), "cannot {} in state {!r}: expected one of {}".format( |
| 377 |
op, self._state, ", ".join(states) |
| 378 |
) |
| 379 |
|
| 380 |
def start(self) -> None: |
| 381 |
self._assert_state("start", ("initialized",)) |
| 382 |
setattr(sys, self.name, self.tmpfile) |
| 383 |
self._state = "started" |
| 384 |
|
| 385 |
def done(self) -> None: |
| 386 |
self._assert_state("done", ("initialized", "started", "suspended", "done")) |
| 387 |
if self._state == "done": |
| 388 |
return |
| 389 |
setattr(sys, self.name, self._old) |
| 390 |
del self._old |
| 391 |
self.tmpfile.close() |
| 392 |
self._state = "done" |
| 393 |
|
| 394 |
def suspend(self) -> None: |
| 395 |
self._assert_state("suspend", ("started", "suspended")) |
| 396 |
setattr(sys, self.name, self._old) |
| 397 |
self._state = "suspended" |
| 398 |
|
| 399 |
def resume(self) -> None: |
| 400 |
self._assert_state("resume", ("started", "suspended")) |
| 401 |
if self._state == "started": |
| 402 |
return |
| 403 |
setattr(sys, self.name, self.tmpfile) |
| 404 |
self._state = "started" |
| 405 |
|
| 406 |
|
| 407 |
class SysCaptureBinary(SysCaptureBase[bytes]): |
| 408 |
EMPTY_BUFFER = b"" |
| 409 |
|
| 410 |
def snap(self) -> bytes: |
| 411 |
self._assert_state("snap", ("started", "suspended")) |
| 412 |
self.tmpfile.seek(0) |
| 413 |
res = self.tmpfile.buffer.read() |
| 414 |
self.tmpfile.seek(0) |
| 415 |
self.tmpfile.truncate() |
| 416 |
return res |
| 417 |
|
| 418 |
def writeorg(self, data: bytes) -> None: |
| 419 |
self._assert_state("writeorg", ("started", "suspended")) |
| 420 |
self._old.flush() |
| 421 |
self._old.buffer.write(data) |
| 422 |
self._old.buffer.flush() |
| 423 |
|
| 424 |
|
| 425 |
class SysCapture(SysCaptureBase[str]): |
| 426 |
EMPTY_BUFFER = "" |
| 427 |
|
| 428 |
def snap(self) -> str: |
| 429 |
self._assert_state("snap", ("started", "suspended")) |
| 430 |
assert isinstance(self.tmpfile, CaptureIO) |
| 431 |
res = self.tmpfile.getvalue() |
| 432 |
self.tmpfile.seek(0) |
| 433 |
self.tmpfile.truncate() |
| 434 |
return res |
| 435 |
|
| 436 |
def writeorg(self, data: str) -> None: |
| 437 |
self._assert_state("writeorg", ("started", "suspended")) |
| 438 |
self._old.write(data) |
| 439 |
self._old.flush() |
| 440 |
|
| 441 |
|
| 442 |
class FDCaptureBase(CaptureBase[AnyStr]): |
| 443 |
def __init__(self, targetfd: int) -> None: |
| 444 |
self.targetfd = targetfd |
| 445 |
|
| 446 |
try: |
| 447 |
os.fstat(targetfd) |
| 448 |
except OSError: |
| 449 |
# FD capturing is conceptually simple -- create a temporary file, |
| 450 |
# redirect the FD to it, redirect back when done. But when the |
| 451 |
# target FD is invalid it throws a wrench into this lovely scheme. |
| 452 |
# |
| 453 |
# Tests themselves shouldn't care if the FD is valid, FD capturing |
| 454 |
# should work regardless of external circumstances. So falling back |
| 455 |
# to just sys capturing is not a good option. |
| 456 |
# |
| 457 |
# Further complications are the need to support suspend() and the |
| 458 |
# possibility of FD reuse (e.g. the tmpfile getting the very same |
| 459 |
# target FD). The following approach is robust, I believe. |
| 460 |
self.targetfd_invalid: Optional[int] = os.open(os.devnull, os.O_RDWR) |
| 461 |
os.dup2(self.targetfd_invalid, targetfd) |
| 462 |
else: |
| 463 |
self.targetfd_invalid = None |
| 464 |
self.targetfd_save = os.dup(targetfd) |
| 465 |
|
| 466 |
if targetfd == 0: |
| 467 |
self.tmpfile = open(os.devnull, encoding="utf-8") |
| 468 |
self.syscapture: CaptureBase[str] = SysCapture(targetfd) |
| 469 |
else: |
| 470 |
self.tmpfile = EncodedFile( |
| 471 |
TemporaryFile(buffering=0), |
| 472 |
encoding="utf-8", |
| 473 |
errors="replace", |
| 474 |
newline="", |
| 475 |
write_through=True, |
| 476 |
) |
| 477 |
if targetfd in patchsysdict: |
| 478 |
self.syscapture = SysCapture(targetfd, self.tmpfile) |
| 479 |
else: |
| 480 |
self.syscapture = NoCapture(targetfd) |
| 481 |
|
| 482 |
self._state = "initialized" |
| 483 |
|
| 484 |
def __repr__(self) -> str: |
| 485 |
return ( |
| 486 |
f"<{self.__class__.__name__} {self.targetfd} oldfd={self.targetfd_save} " |
| 487 |
f"_state={self._state!r} tmpfile={self.tmpfile!r}>" |
| 488 |
) |
| 489 |
|
| 490 |
def _assert_state(self, op: str, states: Tuple[str, ...]) -> None: |
| 491 |
assert ( |
| 492 |
self._state in states |
| 493 |
), "cannot {} in state {!r}: expected one of {}".format( |
| 494 |
op, self._state, ", ".join(states) |
| 495 |
) |
| 496 |
|
| 497 |
def start(self) -> None: |
| 498 |
"""Start capturing on targetfd using memorized tmpfile.""" |
| 499 |
self._assert_state("start", ("initialized",)) |
| 500 |
os.dup2(self.tmpfile.fileno(), self.targetfd) |
| 501 |
self.syscapture.start() |
| 502 |
self._state = "started" |
| 503 |
|
| 504 |
def done(self) -> None: |
| 505 |
"""Stop capturing, restore streams, return original capture file, |
| 506 |
seeked to position zero.""" |
| 507 |
self._assert_state("done", ("initialized", "started", "suspended", "done")) |
| 508 |
if self._state == "done": |
| 509 |
return |
| 510 |
os.dup2(self.targetfd_save, self.targetfd) |
| 511 |
os.close(self.targetfd_save) |
| 512 |
if self.targetfd_invalid is not None: |
| 513 |
if self.targetfd_invalid != self.targetfd: |
| 514 |
os.close(self.targetfd) |
| 515 |
os.close(self.targetfd_invalid) |
| 516 |
self.syscapture.done() |
| 517 |
self.tmpfile.close() |
| 518 |
self._state = "done" |
| 519 |
|
| 520 |
def suspend(self) -> None: |
| 521 |
self._assert_state("suspend", ("started", "suspended")) |
| 522 |
if self._state == "suspended": |
| 523 |
return |
| 524 |
self.syscapture.suspend() |
| 525 |
os.dup2(self.targetfd_save, self.targetfd) |
| 526 |
self._state = "suspended" |
| 527 |
|
| 528 |
def resume(self) -> None: |
| 529 |
self._assert_state("resume", ("started", "suspended")) |
| 530 |
if self._state == "started": |
| 531 |
return |
| 532 |
self.syscapture.resume() |
| 533 |
os.dup2(self.tmpfile.fileno(), self.targetfd) |
| 534 |
self._state = "started" |
| 535 |
|
| 536 |
|
| 537 |
class FDCaptureBinary(FDCaptureBase[bytes]): |
| 538 |
"""Capture IO to/from a given OS-level file descriptor. |
| 539 |
|
| 540 |
snap() produces `bytes`. |
| 541 |
""" |
| 542 |
|
| 543 |
EMPTY_BUFFER = b"" |
| 544 |
|
| 545 |
def snap(self) -> bytes: |
| 546 |
self._assert_state("snap", ("started", "suspended")) |
| 547 |
self.tmpfile.seek(0) |
| 548 |
res = self.tmpfile.buffer.read() |
| 549 |
self.tmpfile.seek(0) |
| 550 |
self.tmpfile.truncate() |
| 551 |
return res |
| 552 |
|
| 553 |
def writeorg(self, data: bytes) -> None: |
| 554 |
"""Write to original file descriptor.""" |
| 555 |
self._assert_state("writeorg", ("started", "suspended")) |
| 556 |
os.write(self.targetfd_save, data) |
| 557 |
|
| 558 |
|
| 559 |
class FDCapture(FDCaptureBase[str]): |
| 560 |
"""Capture IO to/from a given OS-level file descriptor. |
| 561 |
|
| 562 |
snap() produces text. |
| 563 |
""" |
| 564 |
|
| 565 |
EMPTY_BUFFER = "" |
| 566 |
|
| 567 |
def snap(self) -> str: |
| 568 |
self._assert_state("snap", ("started", "suspended")) |
| 569 |
self.tmpfile.seek(0) |
| 570 |
res = self.tmpfile.read() |
| 571 |
self.tmpfile.seek(0) |
| 572 |
self.tmpfile.truncate() |
| 573 |
return res |
| 574 |
|
| 575 |
def writeorg(self, data: str) -> None: |
| 576 |
"""Write to original file descriptor.""" |
| 577 |
self._assert_state("writeorg", ("started", "suspended")) |
| 578 |
# XXX use encoding of original stream |
| 579 |
os.write(self.targetfd_save, data.encode("utf-8")) |
| 580 |
|
| 581 |
|
| 582 |
# MultiCapture |
| 583 |
|
| 584 |
|
| 585 |
# Generic NamedTuple only supported since Python 3.11. |
| 586 |
if sys.version_info >= (3, 11) or TYPE_CHECKING: |
| 587 |
|
| 588 |
@final |
| 589 |
class CaptureResult(NamedTuple, Generic[AnyStr]): |
| 590 |
"""The result of :method:`caplog.readouterr() <pytest.CaptureFixture.readouterr>`.""" |
| 591 |
|
| 592 |
out: AnyStr |
| 593 |
err: AnyStr |
| 594 |
|
| 595 |
else: |
| 596 |
|
| 597 |
class CaptureResult( |
| 598 |
collections.namedtuple("CaptureResult", ["out", "err"]), # noqa: PYI024 |
| 599 |
Generic[AnyStr], |
| 600 |
): |
| 601 |
"""The result of :method:`caplog.readouterr() <pytest.CaptureFixture.readouterr>`.""" |
| 602 |
|
| 603 |
__slots__ = () |
| 604 |
|
| 605 |
|
| 606 |
class MultiCapture(Generic[AnyStr]): |
| 607 |
_state = None |
| 608 |
_in_suspended = False |
| 609 |
|
| 610 |
def __init__( |
| 611 |
self, |
| 612 |
in_: Optional[CaptureBase[AnyStr]], |
| 613 |
out: Optional[CaptureBase[AnyStr]], |
| 614 |
err: Optional[CaptureBase[AnyStr]], |
| 615 |
) -> None: |
| 616 |
self.in_: Optional[CaptureBase[AnyStr]] = in_ |
| 617 |
self.out: Optional[CaptureBase[AnyStr]] = out |
| 618 |
self.err: Optional[CaptureBase[AnyStr]] = err |
| 619 |
|
| 620 |
def __repr__(self) -> str: |
| 621 |
return ( |
| 622 |
f"<MultiCapture out={self.out!r} err={self.err!r} in_={self.in_!r} " |
| 623 |
f"_state={self._state!r} _in_suspended={self._in_suspended!r}>" |
| 624 |
) |
| 625 |
|
| 626 |
def start_capturing(self) -> None: |
| 627 |
self._state = "started" |
| 628 |
if self.in_: |
| 629 |
self.in_.start() |
| 630 |
if self.out: |
| 631 |
self.out.start() |
| 632 |
if self.err: |
| 633 |
self.err.start() |
| 634 |
|
| 635 |
def pop_outerr_to_orig(self) -> Tuple[AnyStr, AnyStr]: |
| 636 |
"""Pop current snapshot out/err capture and flush to orig streams.""" |
| 637 |
out, err = self.readouterr() |
| 638 |
if out: |
| 639 |
assert self.out is not None |
| 640 |
self.out.writeorg(out) |
| 641 |
if err: |
| 642 |
assert self.err is not None |
| 643 |
self.err.writeorg(err) |
| 644 |
return out, err |
| 645 |
|
| 646 |
def suspend_capturing(self, in_: bool = False) -> None: |
| 647 |
self._state = "suspended" |
| 648 |
if self.out: |
| 649 |
self.out.suspend() |
| 650 |
if self.err: |
| 651 |
self.err.suspend() |
| 652 |
if in_ and self.in_: |
| 653 |
self.in_.suspend() |
| 654 |
self._in_suspended = True |
| 655 |
|
| 656 |
def resume_capturing(self) -> None: |
| 657 |
self._state = "started" |
| 658 |
if self.out: |
| 659 |
self.out.resume() |
| 660 |
if self.err: |
| 661 |
self.err.resume() |
| 662 |
if self._in_suspended: |
| 663 |
assert self.in_ is not None |
| 664 |
self.in_.resume() |
| 665 |
self._in_suspended = False |
| 666 |
|
| 667 |
def stop_capturing(self) -> None: |
| 668 |
"""Stop capturing and reset capturing streams.""" |
| 669 |
if self._state == "stopped": |
| 670 |
raise ValueError("was already stopped") |
| 671 |
self._state = "stopped" |
| 672 |
if self.out: |
| 673 |
self.out.done() |
| 674 |
if self.err: |
| 675 |
self.err.done() |
| 676 |
if self.in_: |
| 677 |
self.in_.done() |
| 678 |
|
| 679 |
def is_started(self) -> bool: |
| 680 |
"""Whether actively capturing -- not suspended or stopped.""" |
| 681 |
return self._state == "started" |
| 682 |
|
| 683 |
def readouterr(self) -> CaptureResult[AnyStr]: |
| 684 |
out = self.out.snap() if self.out else "" |
| 685 |
err = self.err.snap() if self.err else "" |
| 686 |
# TODO: This type error is real, need to fix. |
| 687 |
return CaptureResult(out, err) # type: ignore[arg-type] |
| 688 |
|
| 689 |
|
| 690 |
def _get_multicapture(method: _CaptureMethod) -> MultiCapture[str]: |
| 691 |
if method == "fd": |
| 692 |
return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2)) |
| 693 |
elif method == "sys": |
| 694 |
return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2)) |
| 695 |
elif method == "no": |
| 696 |
return MultiCapture(in_=None, out=None, err=None) |
| 697 |
elif method == "tee-sys": |
| 698 |
return MultiCapture( |
| 699 |
in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True) |
| 700 |
) |
| 701 |
raise ValueError(f"unknown capturing method: {method!r}") |
| 702 |
|
| 703 |
|
| 704 |
# CaptureManager and CaptureFixture |
| 705 |
|
| 706 |
|
| 707 |
class CaptureManager: |
| 708 |
"""The capture plugin. |
| 709 |
|
| 710 |
Manages that the appropriate capture method is enabled/disabled during |
| 711 |
collection and each test phase (setup, call, teardown). After each of |
| 712 |
those points, the captured output is obtained and attached to the |
| 713 |
collection/runtest report. |
| 714 |
|
| 715 |
There are two levels of capture: |
| 716 |
|
| 717 |
* global: enabled by default and can be suppressed by the ``-s`` |
| 718 |
option. This is always enabled/disabled during collection and each test |
| 719 |
phase. |
| 720 |
|
| 721 |
* fixture: when a test function or one of its fixture depend on the |
| 722 |
``capsys`` or ``capfd`` fixtures. In this case special handling is |
| 723 |
needed to ensure the fixtures take precedence over the global capture. |
| 724 |
""" |
| 725 |
|
| 726 |
def __init__(self, method: _CaptureMethod) -> None: |
| 727 |
self._method: Final = method |
| 728 |
self._global_capturing: Optional[MultiCapture[str]] = None |
| 729 |
self._capture_fixture: Optional[CaptureFixture[Any]] = None |
| 730 |
|
| 731 |
def __repr__(self) -> str: |
| 732 |
return ( |
| 733 |
f"<CaptureManager _method={self._method!r} _global_capturing={self._global_capturing!r} " |
| 734 |
f"_capture_fixture={self._capture_fixture!r}>" |
| 735 |
) |
| 736 |
|
| 737 |
def is_capturing(self) -> Union[str, bool]: |
| 738 |
if self.is_globally_capturing(): |
| 739 |
return "global" |
| 740 |
if self._capture_fixture: |
| 741 |
return "fixture %s" % self._capture_fixture.request.fixturename |
| 742 |
return False |
| 743 |
|
| 744 |
# Global capturing control |
| 745 |
|
| 746 |
def is_globally_capturing(self) -> bool: |
| 747 |
return self._method != "no" |
| 748 |
|
| 749 |
def start_global_capturing(self) -> None: |
| 750 |
assert self._global_capturing is None |
| 751 |
self._global_capturing = _get_multicapture(self._method) |
| 752 |
self._global_capturing.start_capturing() |
| 753 |
|
| 754 |
def stop_global_capturing(self) -> None: |
| 755 |
if self._global_capturing is not None: |
| 756 |
self._global_capturing.pop_outerr_to_orig() |
| 757 |
self._global_capturing.stop_capturing() |
| 758 |
self._global_capturing = None |
| 759 |
|
| 760 |
def resume_global_capture(self) -> None: |
| 761 |
# During teardown of the python process, and on rare occasions, capture |
| 762 |
# attributes can be `None` while trying to resume global capture. |
| 763 |
if self._global_capturing is not None: |
| 764 |
self._global_capturing.resume_capturing() |
| 765 |
|
| 766 |
def suspend_global_capture(self, in_: bool = False) -> None: |
| 767 |
if self._global_capturing is not None: |
| 768 |
self._global_capturing.suspend_capturing(in_=in_) |
| 769 |
|
| 770 |
def suspend(self, in_: bool = False) -> None: |
| 771 |
# Need to undo local capsys-et-al if it exists before disabling global capture. |
| 772 |
self.suspend_fixture() |
| 773 |
self.suspend_global_capture(in_) |
| 774 |
|
| 775 |
def resume(self) -> None: |
| 776 |
self.resume_global_capture() |
| 777 |
self.resume_fixture() |
| 778 |
|
| 779 |
def read_global_capture(self) -> CaptureResult[str]: |
| 780 |
assert self._global_capturing is not None |
| 781 |
return self._global_capturing.readouterr() |
| 782 |
|
| 783 |
# Fixture Control |
| 784 |
|
| 785 |
def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None: |
| 786 |
if self._capture_fixture: |
| 787 |
current_fixture = self._capture_fixture.request.fixturename |
| 788 |
requested_fixture = capture_fixture.request.fixturename |
| 789 |
capture_fixture.request.raiseerror( |
| 790 |
f"cannot use {requested_fixture} and {current_fixture} at the same time" |
| 791 |
) |
| 792 |
self._capture_fixture = capture_fixture |
| 793 |
|
| 794 |
def unset_fixture(self) -> None: |
| 795 |
self._capture_fixture = None |
| 796 |
|
| 797 |
def activate_fixture(self) -> None: |
| 798 |
"""If the current item is using ``capsys`` or ``capfd``, activate |
| 799 |
them so they take precedence over the global capture.""" |
| 800 |
if self._capture_fixture: |
| 801 |
self._capture_fixture._start() |
| 802 |
|
| 803 |
def deactivate_fixture(self) -> None: |
| 804 |
"""Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any.""" |
| 805 |
if self._capture_fixture: |
| 806 |
self._capture_fixture.close() |
| 807 |
|
| 808 |
def suspend_fixture(self) -> None: |
| 809 |
if self._capture_fixture: |
| 810 |
self._capture_fixture._suspend() |
| 811 |
|
| 812 |
def resume_fixture(self) -> None: |
| 813 |
if self._capture_fixture: |
| 814 |
self._capture_fixture._resume() |
| 815 |
|
| 816 |
# Helper context managers |
| 817 |
|
| 818 |
@contextlib.contextmanager |
| 819 |
def global_and_fixture_disabled(self) -> Generator[None, None, None]: |
| 820 |
"""Context manager to temporarily disable global and current fixture capturing.""" |
| 821 |
do_fixture = self._capture_fixture and self._capture_fixture._is_started() |
| 822 |
if do_fixture: |
| 823 |
self.suspend_fixture() |
| 824 |
do_global = self._global_capturing and self._global_capturing.is_started() |
| 825 |
if do_global: |
| 826 |
self.suspend_global_capture() |
| 827 |
try: |
| 828 |
yield |
| 829 |
finally: |
| 830 |
if do_global: |
| 831 |
self.resume_global_capture() |
| 832 |
if do_fixture: |
| 833 |
self.resume_fixture() |
| 834 |
|
| 835 |
@contextlib.contextmanager |
| 836 |
def item_capture(self, when: str, item: Item) -> Generator[None, None, None]: |
| 837 |
self.resume_global_capture() |
| 838 |
self.activate_fixture() |
| 839 |
try: |
| 840 |
yield |
| 841 |
finally: |
| 842 |
self.deactivate_fixture() |
| 843 |
self.suspend_global_capture(in_=False) |
| 844 |
|
| 845 |
out, err = self.read_global_capture() |
| 846 |
item.add_report_section(when, "stdout", out) |
| 847 |
item.add_report_section(when, "stderr", err) |
| 848 |
|
| 849 |
# Hooks |
| 850 |
|
| 851 |
@hookimpl(wrapper=True) |
| 852 |
def pytest_make_collect_report( |
| 853 |
self, collector: Collector |
| 854 |
) -> Generator[None, CollectReport, CollectReport]: |
| 855 |
if isinstance(collector, File): |
| 856 |
self.resume_global_capture() |
| 857 |
try: |
| 858 |
rep = yield |
| 859 |
finally: |
| 860 |
self.suspend_global_capture() |
| 861 |
out, err = self.read_global_capture() |
| 862 |
if out: |
| 863 |
rep.sections.append(("Captured stdout", out)) |
| 864 |
if err: |
| 865 |
rep.sections.append(("Captured stderr", err)) |
| 866 |
else: |
| 867 |
rep = yield |
| 868 |
return rep |
| 869 |
|
| 870 |
@hookimpl(wrapper=True) |
| 871 |
def pytest_runtest_setup(self, item: Item) -> Generator[None, None, None]: |
| 872 |
with self.item_capture("setup", item): |
| 873 |
return (yield) |
| 874 |
|
| 875 |
@hookimpl(wrapper=True) |
| 876 |
def pytest_runtest_call(self, item: Item) -> Generator[None, None, None]: |
| 877 |
with self.item_capture("call", item): |
| 878 |
return (yield) |
| 879 |
|
| 880 |
@hookimpl(wrapper=True) |
| 881 |
def pytest_runtest_teardown(self, item: Item) -> Generator[None, None, None]: |
| 882 |
with self.item_capture("teardown", item): |
| 883 |
return (yield) |
| 884 |
|
| 885 |
@hookimpl(tryfirst=True) |
| 886 |
def pytest_keyboard_interrupt(self) -> None: |
| 887 |
self.stop_global_capturing() |
| 888 |
|
| 889 |
@hookimpl(tryfirst=True) |
| 890 |
def pytest_internalerror(self) -> None: |
| 891 |
self.stop_global_capturing() |
| 892 |
|
| 893 |
|
| 894 |
class CaptureFixture(Generic[AnyStr]): |
| 895 |
"""Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`, |
| 896 |
:fixture:`capfd` and :fixture:`capfdbinary` fixtures.""" |
| 897 |
|
| 898 |
def __init__( |
| 899 |
self, |
| 900 |
captureclass: Type[CaptureBase[AnyStr]], |
| 901 |
request: SubRequest, |
| 902 |
*, |
| 903 |
_ispytest: bool = False, |
| 904 |
) -> None: |
| 905 |
check_ispytest(_ispytest) |
| 906 |
self.captureclass: Type[CaptureBase[AnyStr]] = captureclass |
| 907 |
self.request = request |
| 908 |
self._capture: Optional[MultiCapture[AnyStr]] = None |
| 909 |
self._captured_out: AnyStr = self.captureclass.EMPTY_BUFFER |
| 910 |
self._captured_err: AnyStr = self.captureclass.EMPTY_BUFFER |
| 911 |
|
| 912 |
def _start(self) -> None: |
| 913 |
if self._capture is None: |
| 914 |
self._capture = MultiCapture( |
| 915 |
in_=None, |
| 916 |
out=self.captureclass(1), |
| 917 |
err=self.captureclass(2), |
| 918 |
) |
| 919 |
self._capture.start_capturing() |
| 920 |
|
| 921 |
def close(self) -> None: |
| 922 |
if self._capture is not None: |
| 923 |
out, err = self._capture.pop_outerr_to_orig() |
| 924 |
self._captured_out += out |
| 925 |
self._captured_err += err |
| 926 |
self._capture.stop_capturing() |
| 927 |
self._capture = None |
| 928 |
|
| 929 |
def readouterr(self) -> CaptureResult[AnyStr]: |
| 930 |
"""Read and return the captured output so far, resetting the internal |
| 931 |
buffer. |
| 932 |
|
| 933 |
:returns: |
| 934 |
The captured content as a namedtuple with ``out`` and ``err`` |
| 935 |
string attributes. |
| 936 |
""" |
| 937 |
captured_out, captured_err = self._captured_out, self._captured_err |
| 938 |
if self._capture is not None: |
| 939 |
out, err = self._capture.readouterr() |
| 940 |
captured_out += out |
| 941 |
captured_err += err |
| 942 |
self._captured_out = self.captureclass.EMPTY_BUFFER |
| 943 |
self._captured_err = self.captureclass.EMPTY_BUFFER |
| 944 |
return CaptureResult(captured_out, captured_err) |
| 945 |
|
| 946 |
def _suspend(self) -> None: |
| 947 |
"""Suspend this fixture's own capturing temporarily.""" |
| 948 |
if self._capture is not None: |
| 949 |
self._capture.suspend_capturing() |
| 950 |
|
| 951 |
def _resume(self) -> None: |
| 952 |
"""Resume this fixture's own capturing temporarily.""" |
| 953 |
if self._capture is not None: |
| 954 |
self._capture.resume_capturing() |
| 955 |
|
| 956 |
def _is_started(self) -> bool: |
| 957 |
"""Whether actively capturing -- not disabled or closed.""" |
| 958 |
if self._capture is not None: |
| 959 |
return self._capture.is_started() |
| 960 |
return False |
| 961 |
|
| 962 |
@contextlib.contextmanager |
| 963 |
def disabled(self) -> Generator[None, None, None]: |
| 964 |
"""Temporarily disable capturing while inside the ``with`` block.""" |
| 965 |
capmanager: CaptureManager = self.request.config.pluginmanager.getplugin( |
| 966 |
"capturemanager" |
| 967 |
) |
| 968 |
with capmanager.global_and_fixture_disabled(): |
| 969 |
yield |
| 970 |
|
| 971 |
|
| 972 |
# The fixtures. |
| 973 |
|
| 974 |
|
| 975 |
@fixture |
| 976 |
def capsys(request: SubRequest) -> Generator[CaptureFixture[str], None, None]: |
| 977 |
r"""Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``. |
| 978 |
|
| 979 |
The captured output is made available via ``capsys.readouterr()`` method |
| 980 |
calls, which return a ``(out, err)`` namedtuple. |
| 981 |
``out`` and ``err`` will be ``text`` objects. |
| 982 |
|
| 983 |
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`. |
| 984 |
|
| 985 |
Example: |
| 986 |
.. code-block:: python |
| 987 |
|
| 988 |
def test_output(capsys): |
| 989 |
print("hello") |
| 990 |
captured = capsys.readouterr() |
| 991 |
assert captured.out == "hello\n" |
| 992 |
""" |
| 993 |
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") |
| 994 |
capture_fixture = CaptureFixture(SysCapture, request, _ispytest=True) |
| 995 |
capman.set_fixture(capture_fixture) |
| 996 |
capture_fixture._start() |
| 997 |
yield capture_fixture |
| 998 |
capture_fixture.close() |
| 999 |
capman.unset_fixture() |
| 1000 |
|
| 1001 |
|
| 1002 |
@fixture |
| 1003 |
def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]: |
| 1004 |
r"""Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``. |
| 1005 |
|
| 1006 |
The captured output is made available via ``capsysbinary.readouterr()`` |
| 1007 |
method calls, which return a ``(out, err)`` namedtuple. |
| 1008 |
``out`` and ``err`` will be ``bytes`` objects. |
| 1009 |
|
| 1010 |
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`. |
| 1011 |
|
| 1012 |
Example: |
| 1013 |
.. code-block:: python |
| 1014 |
|
| 1015 |
def test_output(capsysbinary): |
| 1016 |
print("hello") |
| 1017 |
captured = capsysbinary.readouterr() |
| 1018 |
assert captured.out == b"hello\n" |
| 1019 |
""" |
| 1020 |
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") |
| 1021 |
capture_fixture = CaptureFixture(SysCaptureBinary, request, _ispytest=True) |
| 1022 |
capman.set_fixture(capture_fixture) |
| 1023 |
capture_fixture._start() |
| 1024 |
yield capture_fixture |
| 1025 |
capture_fixture.close() |
| 1026 |
capman.unset_fixture() |
| 1027 |
|
| 1028 |
|
| 1029 |
@fixture |
| 1030 |
def capfd(request: SubRequest) -> Generator[CaptureFixture[str], None, None]: |
| 1031 |
r"""Enable text capturing of writes to file descriptors ``1`` and ``2``. |
| 1032 |
|
| 1033 |
The captured output is made available via ``capfd.readouterr()`` method |
| 1034 |
calls, which return a ``(out, err)`` namedtuple. |
| 1035 |
``out`` and ``err`` will be ``text`` objects. |
| 1036 |
|
| 1037 |
Returns an instance of :class:`CaptureFixture[str] <pytest.CaptureFixture>`. |
| 1038 |
|
| 1039 |
Example: |
| 1040 |
.. code-block:: python |
| 1041 |
|
| 1042 |
def test_system_echo(capfd): |
| 1043 |
os.system('echo "hello"') |
| 1044 |
captured = capfd.readouterr() |
| 1045 |
assert captured.out == "hello\n" |
| 1046 |
""" |
| 1047 |
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") |
| 1048 |
capture_fixture = CaptureFixture(FDCapture, request, _ispytest=True) |
| 1049 |
capman.set_fixture(capture_fixture) |
| 1050 |
capture_fixture._start() |
| 1051 |
yield capture_fixture |
| 1052 |
capture_fixture.close() |
| 1053 |
capman.unset_fixture() |
| 1054 |
|
| 1055 |
|
| 1056 |
@fixture |
| 1057 |
def capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]: |
| 1058 |
r"""Enable bytes capturing of writes to file descriptors ``1`` and ``2``. |
| 1059 |
|
| 1060 |
The captured output is made available via ``capfd.readouterr()`` method |
| 1061 |
calls, which return a ``(out, err)`` namedtuple. |
| 1062 |
``out`` and ``err`` will be ``byte`` objects. |
| 1063 |
|
| 1064 |
Returns an instance of :class:`CaptureFixture[bytes] <pytest.CaptureFixture>`. |
| 1065 |
|
| 1066 |
Example: |
| 1067 |
.. code-block:: python |
| 1068 |
|
| 1069 |
def test_system_echo(capfdbinary): |
| 1070 |
os.system('echo "hello"') |
| 1071 |
captured = capfdbinary.readouterr() |
| 1072 |
assert captured.out == b"hello\n" |
| 1073 |
|
| 1074 |
""" |
| 1075 |
capman: CaptureManager = request.config.pluginmanager.getplugin("capturemanager") |
| 1076 |
capture_fixture = CaptureFixture(FDCaptureBinary, request, _ispytest=True) |
| 1077 |
capman.set_fixture(capture_fixture) |
| 1078 |
capture_fixture._start() |
| 1079 |
yield capture_fixture |
| 1080 |
capture_fixture.close() |
| 1081 |
capman.unset_fixture() |