Debian Codegraph @

doc/en/how-to/capture-stdout-stderr.rst

raw
1
2 .. _`captures`:
3
4 How to capture stdout/stderr output
5 =========================================================
6
7 Pytest intercepts stdout and stderr as configured by the :option:`--capture=`
8 command-line argument or by using fixtures. The ``--capture=`` flag configures
9 reporting, whereas the fixtures offer more granular control and allow
10 inspection of output during testing. The reports can be customized with the
11 :option:`-r` flag.
12
13 Default stdout/stderr/stdin capturing behaviour
14 ---------------------------------------------------------
15
16 During test execution any output sent to ``stdout`` and ``stderr`` is
17 captured. If a test or a setup method fails its according captured
18 output will usually be shown along with the failure traceback. (This
19 behavior can be configured by the :option:`--show-capture` command-line option).
20
21 In addition, ``stdin`` is set to a "null" object which will
22 fail on attempts to read from it because it is rarely desired
23 to wait for interactive input when running automated tests.
24
25 By default capturing is done by intercepting writes to low level
26 file descriptors. This allows capturing output from simple
27 print statements as well as output from a subprocess started by
28 a test.
29
30 .. _capture-method:
31
32 Setting capturing methods or disabling capturing
33 -------------------------------------------------
34
35 There are three ways in which ``pytest`` can perform capturing:
36
37 * ``fd`` (file descriptor) level capturing (default): All writes going to the
38 operating system file descriptors 1 and 2 will be captured.
39
40 * ``sys`` level capturing: Only writes to Python files ``sys.stdout``
41 and ``sys.stderr`` will be captured. No capturing of writes to
42 filedescriptors is performed.
43
44 * ``tee-sys`` capturing: Python writes to ``sys.stdout`` and ``sys.stderr``
45 will be captured, however the writes will also be passed-through to
46 the actual ``sys.stdout`` and ``sys.stderr``. This allows output to be
47 'live printed' and captured for plugin use, such as junitxml (new in pytest 5.4).
48
49 .. _`disable capturing`:
50
51 You can influence output capturing mechanisms from the command line:
52
53 .. code-block:: bash
54
55 pytest -s # disable all capturing
56 pytest --capture=sys # replace sys.stdout/stderr with in-mem files
57 pytest --capture=fd # also point filedescriptors 1 and 2 to temp file
58 pytest --capture=tee-sys # combines 'sys' and '-s', capturing sys.stdout/stderr
59 # and passing it along to the actual sys.stdout/stderr
60
61 .. _printdebugging:
62
63 Using print statements for debugging
64 ---------------------------------------------------
65
66 One primary benefit of the default capturing of stdout/stderr output
67 is that you can use print statements for debugging:
68
69 .. code-block:: python
70
71 # content of test_module.py
72
73
74 def setup_function(function):
75 print("setting up", function)
76
77
78 def test_func1():
79 assert True
80
81
82 def test_func2():
83 assert False
84
85 and running this module will show you precisely the output
86 of the failing function and hide the other one:
87
88 .. code-block:: pytest
89
90 $ pytest
91 =========================== test session starts ============================
92 platform linux -- Python 3.x.y, pytest-9.x.y, pluggy-1.x.y
93 rootdir: /home/sweet/project
94 collected 2 items
95
96 test_module.py .F [100%]
97
98 ================================= FAILURES =================================
99 ________________________________ test_func2 ________________________________
100
101 def test_func2():
102 > assert False
103 E assert False
104
105 test_module.py:12: AssertionError
106 -------------------------- Captured stdout setup ---------------------------
107 setting up <function test_func2 at 0xdeadbeef0001>
108 ========================= short test summary info ==========================
109 FAILED test_module.py::test_func2 - assert False
110 ======================= 1 failed, 1 passed in 0.12s ========================
111
112 .. _accessing-captured-output:
113
114 Accessing captured output from a test function
115 ---------------------------------------------------
116
117 The :fixture:`capsys`, :fixture:`capteesys`, :fixture:`capsysbinary`, :fixture:`capfd`, and :fixture:`capfdbinary`
118 fixtures allow access to ``stdout``/``stderr`` output created during test execution.
119
120 Here is an example test function that performs some output related checks:
121
122 .. code-block:: python
123
124 def test_myoutput(capsys): # or use "capfd" for fd-level
125 print("hello")
126 sys.stderr.write("world\n")
127 captured = capsys.readouterr()
128 assert captured.out == "hello\n"
129 assert captured.err == "world\n"
130 print("next")
131 captured = capsys.readouterr()
132 assert captured.out == "next\n"
133
134 The ``readouterr()`` call snapshots the output so far -
135 and capturing will be continued. After the test
136 function finishes the original streams will
137 be restored. Using :fixture:`capsys` this way frees your
138 test from having to care about setting/resetting
139 output streams and also interacts well with pytest's
140 own per-test capturing.
141
142 The return value of ``readouterr()`` is a ``namedtuple`` with two attributes, ``out`` and ``err``.
143
144 If the code under test writes non-textual data (``bytes``), you can capture this using
145 the :fixture:`capsysbinary` fixture which instead returns ``bytes`` from
146 the ``readouterr`` method.
147
148 If you want to capture at the file descriptor level you can use
149 the :fixture:`capfd` fixture which offers the exact
150 same interface but allows to also capture output from
151 libraries or subprocesses that directly write to operating
152 system level output streams (FD1 and FD2). Similarly to :fixture:`capsysbinary`, :fixture:`capfdbinary` can be
153 used to capture ``bytes`` at the file descriptor level.
154
155
156 To temporarily disable capture within a test, the capture fixtures
157 have a ``disabled()`` method that can be used
158 as a context manager, disabling capture inside the ``with`` block:
159
160 .. code-block:: python
161
162 def test_disabling_capturing(capsys):
163 print("this output is captured")
164 with capsys.disabled():
165 print("output not captured, going directly to sys.stdout")
166 print("this output is also captured")
167
168 .. note::
169
170 When a capture fixture such as :fixture:`capsys` or :fixture:`capfd` is used,
171 it takes precedence over the global capturing configuration set via
172 command-line options such as ``-s`` or ``--capture=no``.
173
174 This means that output produced within a test using a capture fixture will
175 still be captured and available via ``readouterr()``, even if global capturing
176 is disabled.