capture.py 30 KB

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