You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

968 line
31KB

  1. """Per-test stdout/stderr capturing mechanism."""
  2. import contextlib
  3. import functools
  4. import io
  5. import os
  6. import sys
  7. from io import UnsupportedOperation
  8. from tempfile import TemporaryFile
  9. from typing import Any
  10. from typing import AnyStr
  11. from typing import Generator
  12. from typing import Generic
  13. from typing import Iterator
  14. from typing import Optional
  15. from typing import TextIO
  16. from typing import Tuple
  17. from typing import TYPE_CHECKING
  18. from typing import Union
  19. from _pytest.compat import final
  20. from _pytest.config import Config
  21. from _pytest.config import hookimpl
  22. from _pytest.config.argparsing import Parser
  23. from _pytest.deprecated import check_ispytest
  24. from _pytest.fixtures import fixture
  25. from _pytest.fixtures import SubRequest
  26. from _pytest.nodes import Collector
  27. from _pytest.nodes import File
  28. from _pytest.nodes import Item
  29. if TYPE_CHECKING:
  30. from typing_extensions import Literal
  31. _CaptureMethod = Literal["fd", "sys", "no", "tee-sys"]
  32. def pytest_addoption(parser: Parser) -> None:
  33. group = parser.getgroup("general")
  34. group._addoption(
  35. "--capture",
  36. action="store",
  37. default="fd",
  38. metavar="method",
  39. choices=["fd", "sys", "no", "tee-sys"],
  40. help="per-test capturing method: one of fd|sys|no|tee-sys.",
  41. )
  42. group._addoption(
  43. "-s",
  44. action="store_const",
  45. const="no",
  46. dest="capture",
  47. help="shortcut for --capture=no.",
  48. )
  49. def _colorama_workaround() -> None:
  50. """Ensure colorama is imported so that it attaches to the correct stdio
  51. handles on Windows.
  52. colorama uses the terminal on import time. So if something does the
  53. first import of colorama while I/O capture is active, colorama will
  54. fail in various ways.
  55. """
  56. if sys.platform.startswith("win32"):
  57. try:
  58. import colorama # noqa: F401
  59. except ImportError:
  60. pass
  61. def _readline_workaround() -> None:
  62. """Ensure readline is imported so that it attaches to the correct stdio
  63. handles on Windows.
  64. Pdb uses readline support where available--when not running from the Python
  65. prompt, the readline module is not imported until running the pdb REPL. If
  66. running pytest with the --pdb option this means the readline module is not
  67. imported until after I/O capture has been started.
  68. This is a problem for pyreadline, which is often used to implement readline
  69. support on Windows, as it does not attach to the correct handles for stdout
  70. and/or stdin if they have been redirected by the FDCapture mechanism. This
  71. workaround ensures that readline is imported before I/O capture is setup so
  72. that it can attach to the actual stdin/out for the console.
  73. See https://github.com/pytest-dev/pytest/pull/1281.
  74. """
  75. if sys.platform.startswith("win32"):
  76. try:
  77. import readline # noqa: F401
  78. except ImportError:
  79. pass
  80. def _py36_windowsconsoleio_workaround(stream: TextIO) -> None:
  81. """Workaround for Windows Unicode console handling on Python>=3.6.
  82. Python 3.6 implemented Unicode console handling for Windows. This works
  83. by reading/writing to the raw console handle using
  84. ``{Read,Write}ConsoleW``.
  85. The problem is that we are going to ``dup2`` over the stdio file
  86. descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the
  87. handles used by Python to write to the console. Though there is still some
  88. weirdness and the console handle seems to only be closed randomly and not
  89. on the first call to ``CloseHandle``, or maybe it gets reopened with the
  90. same handle value when we suspend capturing.
  91. The workaround in this case will reopen stdio with a different fd which
  92. also means a different handle by replicating the logic in
  93. "Py_lifecycle.c:initstdio/create_stdio".
  94. :param stream:
  95. In practice ``sys.stdout`` or ``sys.stderr``, but given
  96. here as parameter for unittesting purposes.
  97. See https://github.com/pytest-dev/py/issues/103.
  98. """
  99. if not sys.platform.startswith("win32") or hasattr(sys, "pypy_version_info"):
  100. return
  101. # Bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666).
  102. if not hasattr(stream, "buffer"): # type: ignore[unreachable]
  103. return
  104. buffered = hasattr(stream.buffer, "raw")
  105. raw_stdout = stream.buffer.raw if buffered else stream.buffer # type: ignore[attr-defined]
  106. if not isinstance(raw_stdout, io._WindowsConsoleIO): # type: ignore[attr-defined]
  107. return
  108. def _reopen_stdio(f, mode):
  109. if not buffered and mode[0] == "w":
  110. buffering = 0
  111. else:
  112. buffering = -1
  113. return io.TextIOWrapper(
  114. open(os.dup(f.fileno()), mode, buffering), # type: ignore[arg-type]
  115. f.encoding,
  116. f.errors,
  117. f.newlines,
  118. f.line_buffering,
  119. )
  120. sys.stdin = _reopen_stdio(sys.stdin, "rb")
  121. sys.stdout = _reopen_stdio(sys.stdout, "wb")
  122. sys.stderr = _reopen_stdio(sys.stderr, "wb")
  123. @hookimpl(hookwrapper=True)
  124. def pytest_load_initial_conftests(early_config: Config):
  125. ns = early_config.known_args_namespace
  126. if ns.capture == "fd":
  127. _py36_windowsconsoleio_workaround(sys.stdout)
  128. _colorama_workaround()
  129. _readline_workaround()
  130. pluginmanager = early_config.pluginmanager
  131. capman = CaptureManager(ns.capture)
  132. pluginmanager.register(capman, "capturemanager")
  133. # Make sure that capturemanager is properly reset at final shutdown.
  134. early_config.add_cleanup(capman.stop_global_capturing)
  135. # Finally trigger conftest loading but while capturing (issue #93).
  136. capman.start_global_capturing()
  137. outcome = yield
  138. capman.suspend_global_capture()
  139. if outcome.excinfo is not None:
  140. out, err = capman.read_global_capture()
  141. sys.stdout.write(out)
  142. sys.stderr.write(err)
  143. # IO Helpers.
  144. class EncodedFile(io.TextIOWrapper):
  145. __slots__ = ()
  146. @property
  147. def name(self) -> str:
  148. # Ensure that file.name is a string. Workaround for a Python bug
  149. # fixed in >=3.7.4: https://bugs.python.org/issue36015
  150. return repr(self.buffer)
  151. @property
  152. def mode(self) -> str:
  153. # TextIOWrapper doesn't expose a mode, but at least some of our
  154. # tests check it.
  155. return self.buffer.mode.replace("b", "")
  156. class CaptureIO(io.TextIOWrapper):
  157. def __init__(self) -> None:
  158. super().__init__(io.BytesIO(), encoding="UTF-8", newline="", write_through=True)
  159. def getvalue(self) -> str:
  160. assert isinstance(self.buffer, io.BytesIO)
  161. return self.buffer.getvalue().decode("UTF-8")
  162. class TeeCaptureIO(CaptureIO):
  163. def __init__(self, other: TextIO) -> None:
  164. self._other = other
  165. super().__init__()
  166. def write(self, s: str) -> int:
  167. super().write(s)
  168. return self._other.write(s)
  169. class DontReadFromInput:
  170. encoding = None
  171. def read(self, *args):
  172. raise OSError(
  173. "pytest: reading from stdin while output is captured! Consider using `-s`."
  174. )
  175. readline = read
  176. readlines = read
  177. __next__ = read
  178. def __iter__(self):
  179. return self
  180. def fileno(self) -> int:
  181. raise UnsupportedOperation("redirected stdin is pseudofile, has no fileno()")
  182. def isatty(self) -> bool:
  183. return False
  184. def close(self) -> None:
  185. pass
  186. @property
  187. def buffer(self):
  188. return self
  189. # Capture classes.
  190. patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"}
  191. class NoCapture:
  192. EMPTY_BUFFER = None
  193. __init__ = start = done = suspend = resume = lambda *args: None
  194. class SysCaptureBinary:
  195. EMPTY_BUFFER = b""
  196. def __init__(self, fd: int, tmpfile=None, *, tee: bool = False) -> None:
  197. name = patchsysdict[fd]
  198. self._old = getattr(sys, name)
  199. self.name = name
  200. if tmpfile is None:
  201. if name == "stdin":
  202. tmpfile = DontReadFromInput()
  203. else:
  204. tmpfile = CaptureIO() if not tee else TeeCaptureIO(self._old)
  205. self.tmpfile = tmpfile
  206. self._state = "initialized"
  207. def repr(self, class_name: str) -> str:
  208. return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
  209. class_name,
  210. self.name,
  211. hasattr(self, "_old") and repr(self._old) or "<UNSET>",
  212. self._state,
  213. self.tmpfile,
  214. )
  215. def __repr__(self) -> str:
  216. return "<{} {} _old={} _state={!r} tmpfile={!r}>".format(
  217. self.__class__.__name__,
  218. self.name,
  219. hasattr(self, "_old") and repr(self._old) or "<UNSET>",
  220. self._state,
  221. self.tmpfile,
  222. )
  223. def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
  224. assert (
  225. self._state in states
  226. ), "cannot {} in state {!r}: expected one of {}".format(
  227. op, self._state, ", ".join(states)
  228. )
  229. def start(self) -> None:
  230. self._assert_state("start", ("initialized",))
  231. setattr(sys, self.name, self.tmpfile)
  232. self._state = "started"
  233. def snap(self):
  234. self._assert_state("snap", ("started", "suspended"))
  235. self.tmpfile.seek(0)
  236. res = self.tmpfile.buffer.read()
  237. self.tmpfile.seek(0)
  238. self.tmpfile.truncate()
  239. return res
  240. def done(self) -> None:
  241. self._assert_state("done", ("initialized", "started", "suspended", "done"))
  242. if self._state == "done":
  243. return
  244. setattr(sys, self.name, self._old)
  245. del self._old
  246. self.tmpfile.close()
  247. self._state = "done"
  248. def suspend(self) -> None:
  249. self._assert_state("suspend", ("started", "suspended"))
  250. setattr(sys, self.name, self._old)
  251. self._state = "suspended"
  252. def resume(self) -> None:
  253. self._assert_state("resume", ("started", "suspended"))
  254. if self._state == "started":
  255. return
  256. setattr(sys, self.name, self.tmpfile)
  257. self._state = "started"
  258. def writeorg(self, data) -> None:
  259. self._assert_state("writeorg", ("started", "suspended"))
  260. self._old.flush()
  261. self._old.buffer.write(data)
  262. self._old.buffer.flush()
  263. class SysCapture(SysCaptureBinary):
  264. EMPTY_BUFFER = "" # type: ignore[assignment]
  265. def snap(self):
  266. res = self.tmpfile.getvalue()
  267. self.tmpfile.seek(0)
  268. self.tmpfile.truncate()
  269. return res
  270. def writeorg(self, data):
  271. self._assert_state("writeorg", ("started", "suspended"))
  272. self._old.write(data)
  273. self._old.flush()
  274. class FDCaptureBinary:
  275. """Capture IO to/from a given OS-level file descriptor.
  276. snap() produces `bytes`.
  277. """
  278. EMPTY_BUFFER = b""
  279. def __init__(self, targetfd: int) -> None:
  280. self.targetfd = targetfd
  281. try:
  282. os.fstat(targetfd)
  283. except OSError:
  284. # FD capturing is conceptually simple -- create a temporary file,
  285. # redirect the FD to it, redirect back when done. But when the
  286. # target FD is invalid it throws a wrench into this loveley scheme.
  287. #
  288. # Tests themselves shouldn't care if the FD is valid, FD capturing
  289. # should work regardless of external circumstances. So falling back
  290. # to just sys capturing is not a good option.
  291. #
  292. # Further complications are the need to support suspend() and the
  293. # possibility of FD reuse (e.g. the tmpfile getting the very same
  294. # target FD). The following approach is robust, I believe.
  295. self.targetfd_invalid: Optional[int] = os.open(os.devnull, os.O_RDWR)
  296. os.dup2(self.targetfd_invalid, targetfd)
  297. else:
  298. self.targetfd_invalid = None
  299. self.targetfd_save = os.dup(targetfd)
  300. if targetfd == 0:
  301. self.tmpfile = open(os.devnull)
  302. self.syscapture = SysCapture(targetfd)
  303. else:
  304. self.tmpfile = EncodedFile(
  305. TemporaryFile(buffering=0),
  306. encoding="utf-8",
  307. errors="replace",
  308. newline="",
  309. write_through=True,
  310. )
  311. if targetfd in patchsysdict:
  312. self.syscapture = SysCapture(targetfd, self.tmpfile)
  313. else:
  314. self.syscapture = NoCapture()
  315. self._state = "initialized"
  316. def __repr__(self) -> str:
  317. return "<{} {} oldfd={} _state={!r} tmpfile={!r}>".format(
  318. self.__class__.__name__,
  319. self.targetfd,
  320. self.targetfd_save,
  321. self._state,
  322. self.tmpfile,
  323. )
  324. def _assert_state(self, op: str, states: Tuple[str, ...]) -> None:
  325. assert (
  326. self._state in states
  327. ), "cannot {} in state {!r}: expected one of {}".format(
  328. op, self._state, ", ".join(states)
  329. )
  330. def start(self) -> None:
  331. """Start capturing on targetfd using memorized tmpfile."""
  332. self._assert_state("start", ("initialized",))
  333. os.dup2(self.tmpfile.fileno(), self.targetfd)
  334. self.syscapture.start()
  335. self._state = "started"
  336. def snap(self):
  337. self._assert_state("snap", ("started", "suspended"))
  338. self.tmpfile.seek(0)
  339. res = self.tmpfile.buffer.read()
  340. self.tmpfile.seek(0)
  341. self.tmpfile.truncate()
  342. return res
  343. def done(self) -> None:
  344. """Stop capturing, restore streams, return original capture file,
  345. seeked to position zero."""
  346. self._assert_state("done", ("initialized", "started", "suspended", "done"))
  347. if self._state == "done":
  348. return
  349. os.dup2(self.targetfd_save, self.targetfd)
  350. os.close(self.targetfd_save)
  351. if self.targetfd_invalid is not None:
  352. if self.targetfd_invalid != self.targetfd:
  353. os.close(self.targetfd)
  354. os.close(self.targetfd_invalid)
  355. self.syscapture.done()
  356. self.tmpfile.close()
  357. self._state = "done"
  358. def suspend(self) -> None:
  359. self._assert_state("suspend", ("started", "suspended"))
  360. if self._state == "suspended":
  361. return
  362. self.syscapture.suspend()
  363. os.dup2(self.targetfd_save, self.targetfd)
  364. self._state = "suspended"
  365. def resume(self) -> None:
  366. self._assert_state("resume", ("started", "suspended"))
  367. if self._state == "started":
  368. return
  369. self.syscapture.resume()
  370. os.dup2(self.tmpfile.fileno(), self.targetfd)
  371. self._state = "started"
  372. def writeorg(self, data):
  373. """Write to original file descriptor."""
  374. self._assert_state("writeorg", ("started", "suspended"))
  375. os.write(self.targetfd_save, data)
  376. class FDCapture(FDCaptureBinary):
  377. """Capture IO to/from a given OS-level file descriptor.
  378. snap() produces text.
  379. """
  380. # Ignore type because it doesn't match the type in the superclass (bytes).
  381. EMPTY_BUFFER = "" # type: ignore
  382. def snap(self):
  383. self._assert_state("snap", ("started", "suspended"))
  384. self.tmpfile.seek(0)
  385. res = self.tmpfile.read()
  386. self.tmpfile.seek(0)
  387. self.tmpfile.truncate()
  388. return res
  389. def writeorg(self, data):
  390. """Write to original file descriptor."""
  391. super().writeorg(data.encode("utf-8")) # XXX use encoding of original stream
  392. # MultiCapture
  393. # This class was a namedtuple, but due to mypy limitation[0] it could not be
  394. # made generic, so was replaced by a regular class which tries to emulate the
  395. # pertinent parts of a namedtuple. If the mypy limitation is ever lifted, can
  396. # make it a namedtuple again.
  397. # [0]: https://github.com/python/mypy/issues/685
  398. @final
  399. @functools.total_ordering
  400. class CaptureResult(Generic[AnyStr]):
  401. """The result of :method:`CaptureFixture.readouterr`."""
  402. __slots__ = ("out", "err")
  403. def __init__(self, out: AnyStr, err: AnyStr) -> None:
  404. self.out: AnyStr = out
  405. self.err: AnyStr = err
  406. def __len__(self) -> int:
  407. return 2
  408. def __iter__(self) -> Iterator[AnyStr]:
  409. return iter((self.out, self.err))
  410. def __getitem__(self, item: int) -> AnyStr:
  411. return tuple(self)[item]
  412. def _replace(
  413. self, *, out: Optional[AnyStr] = None, err: Optional[AnyStr] = None
  414. ) -> "CaptureResult[AnyStr]":
  415. return CaptureResult(
  416. out=self.out if out is None else out, err=self.err if err is None else err
  417. )
  418. def count(self, value: AnyStr) -> int:
  419. return tuple(self).count(value)
  420. def index(self, value) -> int:
  421. return tuple(self).index(value)
  422. def __eq__(self, other: object) -> bool:
  423. if not isinstance(other, (CaptureResult, tuple)):
  424. return NotImplemented
  425. return tuple(self) == tuple(other)
  426. def __hash__(self) -> int:
  427. return hash(tuple(self))
  428. def __lt__(self, other: object) -> bool:
  429. if not isinstance(other, (CaptureResult, tuple)):
  430. return NotImplemented
  431. return tuple(self) < tuple(other)
  432. def __repr__(self) -> str:
  433. return f"CaptureResult(out={self.out!r}, err={self.err!r})"
  434. class MultiCapture(Generic[AnyStr]):
  435. _state = None
  436. _in_suspended = False
  437. def __init__(self, in_, out, err) -> None:
  438. self.in_ = in_
  439. self.out = out
  440. self.err = err
  441. def __repr__(self) -> str:
  442. return "<MultiCapture out={!r} err={!r} in_={!r} _state={!r} _in_suspended={!r}>".format(
  443. self.out, self.err, self.in_, self._state, self._in_suspended,
  444. )
  445. def start_capturing(self) -> None:
  446. self._state = "started"
  447. if self.in_:
  448. self.in_.start()
  449. if self.out:
  450. self.out.start()
  451. if self.err:
  452. self.err.start()
  453. def pop_outerr_to_orig(self) -> Tuple[AnyStr, AnyStr]:
  454. """Pop current snapshot out/err capture and flush to orig streams."""
  455. out, err = self.readouterr()
  456. if out:
  457. self.out.writeorg(out)
  458. if err:
  459. self.err.writeorg(err)
  460. return out, err
  461. def suspend_capturing(self, in_: bool = False) -> None:
  462. self._state = "suspended"
  463. if self.out:
  464. self.out.suspend()
  465. if self.err:
  466. self.err.suspend()
  467. if in_ and self.in_:
  468. self.in_.suspend()
  469. self._in_suspended = True
  470. def resume_capturing(self) -> None:
  471. self._state = "started"
  472. if self.out:
  473. self.out.resume()
  474. if self.err:
  475. self.err.resume()
  476. if self._in_suspended:
  477. self.in_.resume()
  478. self._in_suspended = False
  479. def stop_capturing(self) -> None:
  480. """Stop capturing and reset capturing streams."""
  481. if self._state == "stopped":
  482. raise ValueError("was already stopped")
  483. self._state = "stopped"
  484. if self.out:
  485. self.out.done()
  486. if self.err:
  487. self.err.done()
  488. if self.in_:
  489. self.in_.done()
  490. def is_started(self) -> bool:
  491. """Whether actively capturing -- not suspended or stopped."""
  492. return self._state == "started"
  493. def readouterr(self) -> CaptureResult[AnyStr]:
  494. if self.out:
  495. out = self.out.snap()
  496. else:
  497. out = ""
  498. if self.err:
  499. err = self.err.snap()
  500. else:
  501. err = ""
  502. return CaptureResult(out, err)
  503. def _get_multicapture(method: "_CaptureMethod") -> MultiCapture[str]:
  504. if method == "fd":
  505. return MultiCapture(in_=FDCapture(0), out=FDCapture(1), err=FDCapture(2))
  506. elif method == "sys":
  507. return MultiCapture(in_=SysCapture(0), out=SysCapture(1), err=SysCapture(2))
  508. elif method == "no":
  509. return MultiCapture(in_=None, out=None, err=None)
  510. elif method == "tee-sys":
  511. return MultiCapture(
  512. in_=None, out=SysCapture(1, tee=True), err=SysCapture(2, tee=True)
  513. )
  514. raise ValueError(f"unknown capturing method: {method!r}")
  515. # CaptureManager and CaptureFixture
  516. class CaptureManager:
  517. """The capture plugin.
  518. Manages that the appropriate capture method is enabled/disabled during
  519. collection and each test phase (setup, call, teardown). After each of
  520. those points, the captured output is obtained and attached to the
  521. collection/runtest report.
  522. There are two levels of capture:
  523. * global: enabled by default and can be suppressed by the ``-s``
  524. option. This is always enabled/disabled during collection and each test
  525. phase.
  526. * fixture: when a test function or one of its fixture depend on the
  527. ``capsys`` or ``capfd`` fixtures. In this case special handling is
  528. needed to ensure the fixtures take precedence over the global capture.
  529. """
  530. def __init__(self, method: "_CaptureMethod") -> None:
  531. self._method = method
  532. self._global_capturing: Optional[MultiCapture[str]] = None
  533. self._capture_fixture: Optional[CaptureFixture[Any]] = None
  534. def __repr__(self) -> str:
  535. return "<CaptureManager _method={!r} _global_capturing={!r} _capture_fixture={!r}>".format(
  536. self._method, self._global_capturing, self._capture_fixture
  537. )
  538. def is_capturing(self) -> Union[str, bool]:
  539. if self.is_globally_capturing():
  540. return "global"
  541. if self._capture_fixture:
  542. return "fixture %s" % self._capture_fixture.request.fixturename
  543. return False
  544. # Global capturing control
  545. def is_globally_capturing(self) -> bool:
  546. return self._method != "no"
  547. def start_global_capturing(self) -> None:
  548. assert self._global_capturing is None
  549. self._global_capturing = _get_multicapture(self._method)
  550. self._global_capturing.start_capturing()
  551. def stop_global_capturing(self) -> None:
  552. if self._global_capturing is not None:
  553. self._global_capturing.pop_outerr_to_orig()
  554. self._global_capturing.stop_capturing()
  555. self._global_capturing = None
  556. def resume_global_capture(self) -> None:
  557. # During teardown of the python process, and on rare occasions, capture
  558. # attributes can be `None` while trying to resume global capture.
  559. if self._global_capturing is not None:
  560. self._global_capturing.resume_capturing()
  561. def suspend_global_capture(self, in_: bool = False) -> None:
  562. if self._global_capturing is not None:
  563. self._global_capturing.suspend_capturing(in_=in_)
  564. def suspend(self, in_: bool = False) -> None:
  565. # Need to undo local capsys-et-al if it exists before disabling global capture.
  566. self.suspend_fixture()
  567. self.suspend_global_capture(in_)
  568. def resume(self) -> None:
  569. self.resume_global_capture()
  570. self.resume_fixture()
  571. def read_global_capture(self) -> CaptureResult[str]:
  572. assert self._global_capturing is not None
  573. return self._global_capturing.readouterr()
  574. # Fixture Control
  575. def set_fixture(self, capture_fixture: "CaptureFixture[Any]") -> None:
  576. if self._capture_fixture:
  577. current_fixture = self._capture_fixture.request.fixturename
  578. requested_fixture = capture_fixture.request.fixturename
  579. capture_fixture.request.raiseerror(
  580. "cannot use {} and {} at the same time".format(
  581. requested_fixture, current_fixture
  582. )
  583. )
  584. self._capture_fixture = capture_fixture
  585. def unset_fixture(self) -> None:
  586. self._capture_fixture = None
  587. def activate_fixture(self) -> None:
  588. """If the current item is using ``capsys`` or ``capfd``, activate
  589. them so they take precedence over the global capture."""
  590. if self._capture_fixture:
  591. self._capture_fixture._start()
  592. def deactivate_fixture(self) -> None:
  593. """Deactivate the ``capsys`` or ``capfd`` fixture of this item, if any."""
  594. if self._capture_fixture:
  595. self._capture_fixture.close()
  596. def suspend_fixture(self) -> None:
  597. if self._capture_fixture:
  598. self._capture_fixture._suspend()
  599. def resume_fixture(self) -> None:
  600. if self._capture_fixture:
  601. self._capture_fixture._resume()
  602. # Helper context managers
  603. @contextlib.contextmanager
  604. def global_and_fixture_disabled(self) -> Generator[None, None, None]:
  605. """Context manager to temporarily disable global and current fixture capturing."""
  606. do_fixture = self._capture_fixture and self._capture_fixture._is_started()
  607. if do_fixture:
  608. self.suspend_fixture()
  609. do_global = self._global_capturing and self._global_capturing.is_started()
  610. if do_global:
  611. self.suspend_global_capture()
  612. try:
  613. yield
  614. finally:
  615. if do_global:
  616. self.resume_global_capture()
  617. if do_fixture:
  618. self.resume_fixture()
  619. @contextlib.contextmanager
  620. def item_capture(self, when: str, item: Item) -> Generator[None, None, None]:
  621. self.resume_global_capture()
  622. self.activate_fixture()
  623. try:
  624. yield
  625. finally:
  626. self.deactivate_fixture()
  627. self.suspend_global_capture(in_=False)
  628. out, err = self.read_global_capture()
  629. item.add_report_section(when, "stdout", out)
  630. item.add_report_section(when, "stderr", err)
  631. # Hooks
  632. @hookimpl(hookwrapper=True)
  633. def pytest_make_collect_report(self, collector: Collector):
  634. if isinstance(collector, File):
  635. self.resume_global_capture()
  636. outcome = yield
  637. self.suspend_global_capture()
  638. out, err = self.read_global_capture()
  639. rep = outcome.get_result()
  640. if out:
  641. rep.sections.append(("Captured stdout", out))
  642. if err:
  643. rep.sections.append(("Captured stderr", err))
  644. else:
  645. yield
  646. @hookimpl(hookwrapper=True)
  647. def pytest_runtest_setup(self, item: Item) -> Generator[None, None, None]:
  648. with self.item_capture("setup", item):
  649. yield
  650. @hookimpl(hookwrapper=True)
  651. def pytest_runtest_call(self, item: Item) -> Generator[None, None, None]:
  652. with self.item_capture("call", item):
  653. yield
  654. @hookimpl(hookwrapper=True)
  655. def pytest_runtest_teardown(self, item: Item) -> Generator[None, None, None]:
  656. with self.item_capture("teardown", item):
  657. yield
  658. @hookimpl(tryfirst=True)
  659. def pytest_keyboard_interrupt(self) -> None:
  660. self.stop_global_capturing()
  661. @hookimpl(tryfirst=True)
  662. def pytest_internalerror(self) -> None:
  663. self.stop_global_capturing()
  664. class CaptureFixture(Generic[AnyStr]):
  665. """Object returned by the :fixture:`capsys`, :fixture:`capsysbinary`,
  666. :fixture:`capfd` and :fixture:`capfdbinary` fixtures."""
  667. def __init__(
  668. self, captureclass, request: SubRequest, *, _ispytest: bool = False
  669. ) -> None:
  670. check_ispytest(_ispytest)
  671. self.captureclass = captureclass
  672. self.request = request
  673. self._capture: Optional[MultiCapture[AnyStr]] = None
  674. self._captured_out = self.captureclass.EMPTY_BUFFER
  675. self._captured_err = self.captureclass.EMPTY_BUFFER
  676. def _start(self) -> None:
  677. if self._capture is None:
  678. self._capture = MultiCapture(
  679. in_=None, out=self.captureclass(1), err=self.captureclass(2),
  680. )
  681. self._capture.start_capturing()
  682. def close(self) -> None:
  683. if self._capture is not None:
  684. out, err = self._capture.pop_outerr_to_orig()
  685. self._captured_out += out
  686. self._captured_err += err
  687. self._capture.stop_capturing()
  688. self._capture = None
  689. def readouterr(self) -> CaptureResult[AnyStr]:
  690. """Read and return the captured output so far, resetting the internal
  691. buffer.
  692. :returns:
  693. The captured content as a namedtuple with ``out`` and ``err``
  694. string attributes.
  695. """
  696. captured_out, captured_err = self._captured_out, self._captured_err
  697. if self._capture is not None:
  698. out, err = self._capture.readouterr()
  699. captured_out += out
  700. captured_err += err
  701. self._captured_out = self.captureclass.EMPTY_BUFFER
  702. self._captured_err = self.captureclass.EMPTY_BUFFER
  703. return CaptureResult(captured_out, captured_err)
  704. def _suspend(self) -> None:
  705. """Suspend this fixture's own capturing temporarily."""
  706. if self._capture is not None:
  707. self._capture.suspend_capturing()
  708. def _resume(self) -> None:
  709. """Resume this fixture's own capturing temporarily."""
  710. if self._capture is not None:
  711. self._capture.resume_capturing()
  712. def _is_started(self) -> bool:
  713. """Whether actively capturing -- not disabled or closed."""
  714. if self._capture is not None:
  715. return self._capture.is_started()
  716. return False
  717. @contextlib.contextmanager
  718. def disabled(self) -> Generator[None, None, None]:
  719. """Temporarily disable capturing while inside the ``with`` block."""
  720. capmanager = self.request.config.pluginmanager.getplugin("capturemanager")
  721. with capmanager.global_and_fixture_disabled():
  722. yield
  723. # The fixtures.
  724. @fixture
  725. def capsys(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
  726. """Enable text capturing of writes to ``sys.stdout`` and ``sys.stderr``.
  727. The captured output is made available via ``capsys.readouterr()`` method
  728. calls, which return a ``(out, err)`` namedtuple.
  729. ``out`` and ``err`` will be ``text`` objects.
  730. """
  731. capman = request.config.pluginmanager.getplugin("capturemanager")
  732. capture_fixture = CaptureFixture[str](SysCapture, request, _ispytest=True)
  733. capman.set_fixture(capture_fixture)
  734. capture_fixture._start()
  735. yield capture_fixture
  736. capture_fixture.close()
  737. capman.unset_fixture()
  738. @fixture
  739. def capsysbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
  740. """Enable bytes capturing of writes to ``sys.stdout`` and ``sys.stderr``.
  741. The captured output is made available via ``capsysbinary.readouterr()``
  742. method calls, which return a ``(out, err)`` namedtuple.
  743. ``out`` and ``err`` will be ``bytes`` objects.
  744. """
  745. capman = request.config.pluginmanager.getplugin("capturemanager")
  746. capture_fixture = CaptureFixture[bytes](SysCaptureBinary, request, _ispytest=True)
  747. capman.set_fixture(capture_fixture)
  748. capture_fixture._start()
  749. yield capture_fixture
  750. capture_fixture.close()
  751. capman.unset_fixture()
  752. @fixture
  753. def capfd(request: SubRequest) -> Generator[CaptureFixture[str], None, None]:
  754. """Enable text capturing of writes to file descriptors ``1`` and ``2``.
  755. The captured output is made available via ``capfd.readouterr()`` method
  756. calls, which return a ``(out, err)`` namedtuple.
  757. ``out`` and ``err`` will be ``text`` objects.
  758. """
  759. capman = request.config.pluginmanager.getplugin("capturemanager")
  760. capture_fixture = CaptureFixture[str](FDCapture, request, _ispytest=True)
  761. capman.set_fixture(capture_fixture)
  762. capture_fixture._start()
  763. yield capture_fixture
  764. capture_fixture.close()
  765. capman.unset_fixture()
  766. @fixture
  767. def capfdbinary(request: SubRequest) -> Generator[CaptureFixture[bytes], None, None]:
  768. """Enable bytes capturing of writes to file descriptors ``1`` and ``2``.
  769. The captured output is made available via ``capfd.readouterr()`` method
  770. calls, which return a ``(out, err)`` namedtuple.
  771. ``out`` and ``err`` will be ``byte`` objects.
  772. """
  773. capman = request.config.pluginmanager.getplugin("capturemanager")
  774. capture_fixture = CaptureFixture[bytes](FDCaptureBinary, request, _ispytest=True)
  775. capman.set_fixture(capture_fixture)
  776. capture_fixture._start()
  777. yield capture_fixture
  778. capture_fixture.close()
  779. capman.unset_fixture()