Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/doc/en/how-to/doctest.rst

raw
1 .. _doctest:
2
3 How to run doctests
4 =========================================================
5
6 By default, all files matching the ``test*.txt`` pattern will
7 be run through the python standard :mod:`doctest` module. You
8 can change the pattern by issuing:
9
10 .. code-block:: bash
11
12 pytest --doctest-glob="*.rst"
13
14 on the command line. ``--doctest-glob`` can be given multiple times in the command-line.
15
16 If you then have a text file like this:
17
18 .. code-block:: text
19
20 # content of test_example.txt
21
22 hello this is a doctest
23 >>> x = 3
24 >>> x
25 3
26
27 then you can just invoke ``pytest`` directly:
28
29 .. code-block:: pytest
30
31 $ pytest
32 =========================== test session starts ============================
33 platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
34 rootdir: /home/sweet/project
35 collected 1 item
36
37 test_example.txt . [100%]
38
39 ============================ 1 passed in 0.12s =============================
40
41 By default, pytest will collect ``test*.txt`` files looking for doctest directives, but you
42 can pass additional globs using the ``--doctest-glob`` option (multi-allowed).
43
44 In addition to text files, you can also execute doctests directly from docstrings of your classes
45 and functions, including from test modules:
46
47 .. code-block:: python
48
49 # content of mymodule.py
50 def something():
51 """a doctest in a docstring
52 >>> something()
53 42
54 """
55 return 42
56
57 .. code-block:: bash
58
59 $ pytest --doctest-modules
60 =========================== test session starts ============================
61 platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
62 rootdir: /home/sweet/project
63 collected 2 items
64
65 mymodule.py . [ 50%]
66 test_example.txt . [100%]
67
68 ============================ 2 passed in 0.12s =============================
69
70 You can make these changes permanent in your project by
71 putting them into a pytest.ini file like this:
72
73 .. code-block:: ini
74
75 # content of pytest.ini
76 [pytest]
77 addopts = --doctest-modules
78
79
80 Encoding
81 --------
82
83 The default encoding is **UTF-8**, but you can specify the encoding
84 that will be used for those doctest files using the
85 ``doctest_encoding`` ini option:
86
87 .. code-block:: ini
88
89 # content of pytest.ini
90 [pytest]
91 doctest_encoding = latin1
92
93 .. _using doctest options:
94
95 Using 'doctest' options
96 -----------------------
97
98 Python's standard :mod:`doctest` module provides some :ref:`options <python:option-flags-and-directives>`
99 to configure the strictness of doctest tests. In pytest, you can enable those flags using the
100 configuration file.
101
102 For example, to make pytest ignore trailing whitespaces and ignore
103 lengthy exception stack traces you can just write:
104
105 .. code-block:: ini
106
107 [pytest]
108 doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
109
110 Alternatively, options can be enabled by an inline comment in the doc test
111 itself:
112
113 .. code-block:: rst
114
115 >>> something_that_raises() # doctest: +IGNORE_EXCEPTION_DETAIL
116 Traceback (most recent call last):
117 ValueError: ...
118
119 pytest also introduces new options:
120
121 * ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode
122 strings in expected doctest output. This allows doctests to run in Python 2
123 and Python 3 unchanged.
124
125 * ``ALLOW_BYTES``: similarly, the ``b`` prefix is stripped from byte strings
126 in expected doctest output.
127
128 * ``NUMBER``: when enabled, floating-point numbers only need to match as far as
129 the precision you have written in the expected doctest output. The numbers are
130 compared using :func:`pytest.approx` with relative tolerance equal to the
131 precision. For example, the following output would only need to match to 2
132 decimal places when comparing ``3.14`` to
133 ``pytest.approx(math.pi, rel=10**-2)``::
134
135 >>> math.pi
136 3.14
137
138 If you wrote ``3.1416`` then the actual output would need to match to
139 approximately 4 decimal places; and so on.
140
141 This avoids false positives caused by limited floating-point precision, like
142 this::
143
144 Expected:
145 0.233
146 Got:
147 0.23300000000000001
148
149 ``NUMBER`` also supports lists of floating-point numbers -- in fact, it
150 matches floating-point numbers appearing anywhere in the output, even inside
151 a string! This means that it may not be appropriate to enable globally in
152 ``doctest_optionflags`` in your configuration file.
153
154 .. versionadded:: 5.1
155
156
157 Continue on failure
158 -------------------
159
160 By default, pytest would report only the first failure for a given doctest. If
161 you want to continue the test even when you have failures, do:
162
163 .. code-block:: bash
164
165 pytest --doctest-modules --doctest-continue-on-failure
166
167
168 Output format
169 -------------
170
171 You can change the diff output format on failure for your doctests
172 by using one of standard doctest modules format in options
173 (see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,
174 :data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):
175
176 .. code-block:: bash
177
178 pytest --doctest-modules --doctest-report none
179 pytest --doctest-modules --doctest-report udiff
180 pytest --doctest-modules --doctest-report cdiff
181 pytest --doctest-modules --doctest-report ndiff
182 pytest --doctest-modules --doctest-report only_first_failure
183
184
185 pytest-specific features
186 ------------------------
187
188 Some features are provided to make writing doctests easier or with better integration with
189 your existing test suite. Keep in mind however that by using those features you will make
190 your doctests incompatible with the standard ``doctests`` module.
191
192 Using fixtures
193 ^^^^^^^^^^^^^^
194
195 It is possible to use fixtures using the ``getfixture`` helper:
196
197 .. code-block:: text
198
199 # content of example.rst
200 >>> tmp = getfixture('tmp_path')
201 >>> ...
202 >>>
203
204 Note that the fixture needs to be defined in a place visible by pytest, for example, a `conftest.py`
205 file or plugin; normal python files containing docstrings are not normally scanned for fixtures
206 unless explicitly configured by :confval:`python_files`.
207
208 Also, the :ref:`usefixtures <usefixtures>` mark and fixtures marked as :ref:`autouse <autouse>` are supported
209 when executing text doctest files.
210
211
212 .. _`doctest_namespace`:
213
214 'doctest_namespace' fixture
215 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
216
217 The ``doctest_namespace`` fixture can be used to inject items into the
218 namespace in which your doctests run. It is intended to be used within
219 your own fixtures to provide the tests that use them with context.
220
221 ``doctest_namespace`` is a standard ``dict`` object into which you
222 place the objects you want to appear in the doctest namespace:
223
224 .. code-block:: python
225
226 # content of conftest.py
227 import pytest
228 import numpy
229
230
231 @pytest.fixture(autouse=True)
232 def add_np(doctest_namespace):
233 doctest_namespace["np"] = numpy
234
235 which can then be used in your doctests directly:
236
237 .. code-block:: python
238
239 # content of numpy.py
240 def arange():
241 """
242 >>> a = np.arange(10)
243 >>> len(a)
244 10
245 """
246
247 Note that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.
248 Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.
249 Fixtures will not be discovered in a sibling directory tree!
250
251 Skipping tests
252 ^^^^^^^^^^^^^^
253
254 For the same reasons one might want to skip normal tests, it is also possible to skip
255 tests inside doctests.
256
257 To skip a single check inside a doctest you can use the standard
258 :data:`doctest.SKIP` directive:
259
260 .. code-block:: python
261
262 def test_random(y):
263 """
264 >>> random.random() # doctest: +SKIP
265 0.156231223
266
267 >>> 1 + 1
268 2
269 """
270
271 This will skip the first check, but not the second.
272
273 pytest also allows using the standard pytest functions :func:`pytest.skip` and
274 :func:`pytest.xfail` inside doctests, which might be useful because you can
275 then skip/xfail tests based on external conditions:
276
277
278 .. code-block:: text
279
280 >>> import sys, pytest
281 >>> if sys.platform.startswith('win'):
282 ... pytest.skip('this doctest does not work on Windows')
283 ...
284 >>> import fcntl
285 >>> ...
286
287 However using those functions is discouraged because it reduces the readability of the
288 docstring.
289
290 .. note::
291
292 :func:`pytest.skip` and :func:`pytest.xfail` behave differently depending
293 if the doctests are in a Python file (in docstrings) or a text file containing
294 doctests intermingled with text:
295
296 * Python modules (docstrings): the functions only act in that specific docstring,
297 letting the other docstrings in the same module execute as normal.
298
299 * Text files: the functions will skip/xfail the checks for the rest of the entire
300 file.
301
302
303 Alternatives
304 ------------
305
306 While the built-in pytest support provides a good set of functionalities for using
307 doctests, if you use them extensively you might be interested in those external packages
308 which add many more features, and include pytest integration:
309
310 * `pytest-doctestplus <https://github.com/astropy/pytest-doctestplus>`__: provides
311 advanced doctest support and enables the testing of reStructuredText (".rst") files.
312
313 * `Sybil <https://sybil.readthedocs.io>`__: provides a way to test examples in
314 your documentation by parsing them from the documentation source and evaluating
315 the parsed examples as part of your normal test run.