Debian Codegraph @

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. :option:`--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-9.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 :option:`--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, using the :option:`--doctest-modules` option:
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-9.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 configuration file like this:
72
73 .. code-block:: toml
74
75 # content of pytest.toml
76 [pytest]
77 addopts = ["--doctest-modules"]
78
79 Encoding
80 --------
81
82 The default encoding is **UTF-8**, but you can specify the encoding
83 that will be used for those doctest files using the
84 :confval:`doctest_encoding` configuration option:
85
86 .. tab:: toml
87
88 .. code-block:: toml
89
90 [pytest]
91 doctest_encoding = "latin1"
92
93 .. tab:: ini
94
95 .. code-block:: ini
96
97 [pytest]
98 doctest_encoding = latin1
99
100 .. _using doctest options:
101
102 Using 'doctest' options
103 -----------------------
104
105 Python's standard :mod:`doctest` module provides some :ref:`options <python:option-flags-and-directives>`
106 to configure the strictness of doctest tests. In pytest, you can enable those flags using the
107 configuration file.
108
109 For example, to make pytest ignore trailing whitespaces and ignore
110 lengthy exception stack traces you can just write:
111
112 .. tab:: toml
113
114 .. code-block:: toml
115
116 [pytest]
117 doctest_optionflags = ["NORMALIZE_WHITESPACE", "IGNORE_EXCEPTION_DETAIL"]
118
119 .. tab:: ini
120
121 .. code-block:: ini
122
123 [pytest]
124 doctest_optionflags = NORMALIZE_WHITESPACE IGNORE_EXCEPTION_DETAIL
125
126 Alternatively, options can be enabled by an inline comment in the doc test
127 itself:
128
129 .. code-block:: rst
130
131 >>> something_that_raises() # doctest: +IGNORE_EXCEPTION_DETAIL
132 Traceback (most recent call last):
133 ValueError: ...
134
135 pytest also introduces new options:
136
137 * ``ALLOW_UNICODE``: when enabled, the ``u`` prefix is stripped from unicode
138 strings in expected doctest output. This allows doctests to run in Python 2
139 and Python 3 unchanged.
140
141 * ``ALLOW_BYTES``: similarly, the ``b`` prefix is stripped from byte strings
142 in expected doctest output.
143
144 * ``NUMBER``: when enabled, floating-point numbers only need to match as far as
145 the precision you have written in the expected doctest output. The numbers are
146 compared using :func:`pytest.approx` with relative tolerance equal to the
147 precision. For example, the following output would only need to match to 2
148 decimal places when comparing ``3.14`` to
149 ``pytest.approx(math.pi, rel=10**-2)``::
150
151 >>> math.pi
152 3.14
153
154 If you wrote ``3.1416`` then the actual output would need to match to
155 approximately 4 decimal places; and so on.
156
157 This avoids false positives caused by limited floating-point precision, like
158 this::
159
160 Expected:
161 0.233
162 Got:
163 0.23300000000000001
164
165 ``NUMBER`` also supports lists of floating-point numbers -- in fact, it
166 matches floating-point numbers appearing anywhere in the output, even inside
167 a string! This means that it may not be appropriate to enable globally in
168 ``doctest_optionflags`` in your configuration file.
169
170 .. versionadded:: 5.1
171
172
173 Continue on failure
174 -------------------
175
176 By default, pytest would report only the first failure for a given doctest. If
177 you want to continue the test even when you have failures, do:
178
179 .. code-block:: bash
180
181 pytest --doctest-modules --doctest-continue-on-failure
182
183
184 Output format
185 -------------
186
187 You can change the diff output format on failure for your doctests
188 by using one of the standard doctest module's format options
189 (see :data:`python:doctest.REPORT_UDIFF`, :data:`python:doctest.REPORT_CDIFF`,
190 :data:`python:doctest.REPORT_NDIFF`, :data:`python:doctest.REPORT_ONLY_FIRST_FAILURE`):
191
192 .. code-block:: bash
193
194 pytest --doctest-modules --doctest-report none
195 pytest --doctest-modules --doctest-report udiff
196 pytest --doctest-modules --doctest-report cdiff
197 pytest --doctest-modules --doctest-report ndiff
198 pytest --doctest-modules --doctest-report only_first_failure
199
200
201 pytest-specific features
202 ------------------------
203
204 Some features are provided to make writing doctests easier or with better integration with
205 your existing test suite. Keep in mind however that by using those features you will make
206 your doctests incompatible with the standard ``doctests`` module.
207
208 Using fixtures
209 ^^^^^^^^^^^^^^
210
211 It is possible to use fixtures using the ``getfixture`` helper:
212
213 .. code-block:: text
214
215 # content of example.rst
216 >>> tmp = getfixture('tmp_path')
217 >>> ...
218 >>>
219
220 Note that the fixture needs to be defined in a place visible by pytest, for example, a `conftest.py`
221 file or plugin; normal python files containing docstrings are not normally scanned for fixtures
222 unless explicitly configured by :confval:`python_files`.
223
224 Also, the :ref:`usefixtures <usefixtures>` mark and fixtures marked as :ref:`autouse <autouse>` are supported
225 when executing text doctest files.
226
227 Python doctest modules are collected independently from Python test files.
228 Fixture scope is not shared between the two.
229
230 Doctests do not support fixtures that depend on parametrization, because doctest
231 collection does not perform the same test generation as normal test functions.
232 This includes parametrized autouse fixtures. If you need to run doctests against
233 multiple backends or configurations, consider moving those checks into normal
234 test functions or a dedicated doctest plugin.
235
236
237 .. _`doctest_namespace`:
238
239 'doctest_namespace' fixture
240 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
241
242 The ``doctest_namespace`` fixture can be used to inject items into the
243 namespace in which your doctests run. It is intended to be used within
244 your own fixtures to provide the tests that use them with context.
245
246 ``doctest_namespace`` is a standard ``dict`` object into which you
247 place the objects you want to appear in the doctest namespace:
248
249 .. code-block:: python
250
251 # content of conftest.py
252 import pytest
253 import numpy
254
255
256 @pytest.fixture(autouse=True)
257 def add_np(doctest_namespace):
258 doctest_namespace["np"] = numpy
259
260 which can then be used in your doctests directly:
261
262 .. code-block:: python
263
264 # content of numpy.py
265 def arange():
266 """
267 >>> a = np.arange(10)
268 >>> len(a)
269 10
270 """
271
272 Note that like the normal ``conftest.py``, the fixtures are discovered in the directory tree conftest is in.
273 Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree.
274 Fixtures will not be discovered in a sibling directory tree!
275
276 Skipping tests
277 ^^^^^^^^^^^^^^
278
279 For the same reasons one might want to skip normal tests, it is also possible to skip
280 tests inside doctests.
281
282 To skip a single check inside a doctest you can use the standard
283 :data:`doctest.SKIP` directive:
284
285 .. code-block:: python
286
287 def test_random(y):
288 """
289 >>> random.random() # doctest: +SKIP
290 0.156231223
291
292 >>> 1 + 1
293 2
294 """
295
296 This will skip the first check, but not the second.
297
298 pytest also allows using the standard pytest functions :func:`pytest.skip` and
299 :func:`pytest.xfail` inside doctests, which might be useful because you can
300 then skip/xfail tests based on external conditions:
301
302
303 .. code-block:: text
304
305 >>> import sys, pytest
306 >>> if sys.platform.startswith('win'):
307 ... pytest.skip('this doctest does not work on Windows')
308 ...
309 >>> import fcntl
310 >>> ...
311
312 However using those functions is discouraged because it reduces the readability of the
313 docstring.
314
315 .. note::
316
317 :func:`pytest.skip` and :func:`pytest.xfail` behave differently depending
318 if the doctests are in a Python file (in docstrings) or a text file containing
319 doctests intermingled with text:
320
321 * Python modules (docstrings): the functions only act in that specific docstring,
322 letting the other docstrings in the same module execute as normal.
323
324 * Text files: the functions will skip/xfail the checks for the rest of the entire
325 file.
326
327
328 Alternatives
329 ------------
330
331 While the built-in pytest support provides a good set of functionalities for using
332 doctests, if you use them extensively you might be interested in those external packages
333 which add many more features, and include pytest integration:
334
335 * `pytest-doctestplus <https://github.com/scientific-python/pytest-doctestplus>`__: provides
336 advanced doctest support and enables the testing of reStructuredText (".rst") files.
337
338 * `Sybil <https://sybil.readthedocs.io>`__: provides a way to test examples in
339 your documentation by parsing them from the documentation source and evaluating
340 the parsed examples as part of your normal test run.