Debian Codegraph @

src/_pytest/capture.py

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