Debian Codegraph @

doc/usage/extensions/doctest.rst

raw
1 .. highlight:: rst
2
3 :mod:`sphinx.ext.doctest` -- Test snippets in the documentation
4 ===============================================================
5
6 .. module:: sphinx.ext.doctest
7 :synopsis: Test snippets in the documentation.
8
9 .. index:: pair: automatic; testing
10 single: doctest
11 pair: testing; snippets
12
13 .. role:: code-py(code)
14 :language: Python
15
16
17 It is often helpful to include snippets of code in your documentation and
18 demonstrate the results of executing them. But it is important to ensure that
19 the documentation stays up-to-date with the code.
20
21 This extension allows you to test such code snippets in the documentation in
22 a natural way. If you mark the code blocks as shown here, the ``doctest``
23 builder will collect them and run them as doctest tests.
24
25 Within each document, you can assign each snippet to a *group*. Each group
26 consists of:
27
28 * zero or more *setup code* blocks (e.g. importing the module to test)
29 * one or more *test* blocks
30
31 When building the docs with the ``doctest`` builder, groups are collected for
32 each document and run one after the other, first executing setup code blocks,
33 then the test blocks in the order they appear in the file.
34
35 There are two kinds of test blocks:
36
37 * *doctest-style* blocks mimic interactive sessions by interleaving Python code
38 (including the interpreter prompt) and output.
39
40 * *code-output-style* blocks consist of an ordinary piece of Python code, and
41 optionally, a piece of output for that code.
42
43
44 Directives
45 ----------
46
47 The *group* argument below is interpreted as follows: if it is empty, the block
48 is assigned to the group named ``default``. If it is ``*``, the block is
49 assigned to all groups (including the ``default`` group). Otherwise, it must be
50 a comma-separated list of group names.
51
52 .. rst:directive:: .. testsetup:: [group]
53
54 A setup code block. This code is not shown in the output for other builders,
55 but executed before the doctests of the group(s) it belongs to.
56
57 .. rubric:: Options
58
59 .. rst:directive:option:: skipif: condition
60 :type: text
61
62 Skip the directive if the python expression *condition* is True.
63 See :ref:`skipping tests conditionally <doctest-skipif>`.
64
65
66 .. rst:directive:: .. testcleanup:: [group]
67
68 A cleanup code block. This code is not shown in the output for other
69 builders, but executed after the doctests of the group(s) it belongs to.
70
71 .. versionadded:: 1.1
72
73 .. rubric:: Options
74
75 .. rst:directive:option:: skipif: condition
76 :type: text
77
78 Skip the directive if the python expression *condition* is True.
79 See :ref:`skipping tests conditionally <doctest-skipif>`.
80
81
82 .. rst:directive:: .. doctest:: [group]
83
84 A doctest-style code block. You can use standard :mod:`doctest` flags for
85 controlling how actual output is compared with what you give as output. The
86 default set of flags is specified by the :confval:`doctest_default_flags`
87 configuration variable.
88
89 .. rubric:: Options
90
91 .. rst:directive:option:: hide
92
93 Hide the doctest block in other builders.
94 By default it is shown as a highlighted doctest block.
95
96 .. rst:directive:option:: options: doctest flags
97 :type: comma separated list
98
99 A comma-separated list of doctest flags that apply to each example in the
100 tests. (You still can give explicit flags per example, with doctest comments,
101 but they will show up in other builders too.)
102
103 Alternatively, you can give inline doctest options, like in doctest:
104
105 .. code-block:: pycon
106
107 >>> datetime.date.now() # doctest: +SKIP
108 datetime.date(2008, 1, 1)
109
110 They will be respected when the test is run, but by default will be stripped from
111 presentation output. You can prevent stripping using the option
112 :rst:dir:`doctest:no-trim-doctest-flags`.
113
114 .. rst:directive:option:: pyversion
115 :type: text
116
117 Specify the required Python version for the example to be tested. For instance,
118 in the following case the example will be tested only for Python versions greater
119 than 3.14::
120
121 .. doctest::
122 :pyversion: > 3.14
123
124 The following operands are supported:
125
126 * ``~=``: Compatible release clause
127 * ``==``: Version matching clause
128 * ``!=``: Version exclusion clause
129 * ``<=``, ``>=``: Inclusive ordered comparison clause
130 * ``<``, ``>``: Exclusive ordered comparison clause
131 * ``===``: Arbitrary equality clause.
132
133 ``pyversion`` option is followed :pep:`PEP-440: Version Specifiers
134 <440#version-specifiers>`.
135
136 .. versionadded:: 1.6
137
138 .. versionchanged:: 1.7
139
140 Supported PEP-440 operands and notations
141
142 .. rst:directive:option:: trim-doctest-flags
143 no-trim-doctest-flags
144
145 Whether to trim remove doctest flags (comments looking like
146 ``# doctest: FLAG, ...``) at the ends of lines and ``<BLANKLINE>`` markers
147 individually. Default is ``trim-doctest-flags``.
148
149 Note that like with standard doctests, you have to use ``<BLANKLINE>`` to
150 signal a blank line in the expected output. The ``<BLANKLINE>`` is removed
151 when building presentation output (HTML, LaTeX etc.).
152
153 .. rst:directive:option:: skipif: condition
154 :type: text
155
156 Skip the directive if the python expression *condition* is True.
157 See :ref:`skipping tests conditionally <doctest-skipif>`.
158
159 .. rst:directive:: .. testcode:: [group]
160
161 A code block for a code-output-style test.
162
163 .. rubric:: Options
164
165 .. rst:directive:option:: hide
166
167 Hide the code block in other builders.
168 By default it is shown as a highlighted code block.
169
170 .. rst:directive:option:: trim-doctest-flags
171 no-trim-doctest-flags
172
173 Whether to trim remove doctest flags (comments looking like
174 ``# doctest: FLAG, ...``) at the ends of lines and ``<BLANKLINE>`` markers
175 individually. Default is ``trim-doctest-flags``.
176
177 .. rst:directive:option:: skipif: condition
178 :type: text
179
180 Skip the directive if the python expression *condition* is True.
181 See :ref:`skipping tests conditionally <doctest-skipif>`.
182
183 .. note::
184
185 Code in a ``testcode`` block is always executed all at once, no matter how
186 many statements it contains. Therefore, output will *not* be generated
187 for bare expressions -- use ``print``. Example::
188
189 .. testcode::
190
191 1+1 # this will give no output!
192 print(2+2) # this will give output
193
194 .. testoutput::
195
196 4
197
198 Also, please be aware that since the doctest module does not support
199 mixing regular output and an exception message in the same snippet, this
200 applies to testcode/testoutput as well.
201
202
203 .. rst:directive:: .. testoutput:: [group]
204
205 The corresponding output, or the exception message, for the last
206 :rst:dir:`testcode` block.
207
208 .. rst:directive:option:: hide
209
210 Hide the doctest block in other builders.
211 By default it is shown as a highlighted doctest block.
212
213 .. rst:directive:option:: options: doctest flags
214 :type: comma separated list
215
216 A comma-separated list of doctest flags.
217
218 .. rst:directive:option:: trim-doctest-flags
219 no-trim-doctest-flags
220
221 Whether to trim remove doctest flags (comments looking like
222 ``# doctest: FLAG, ...``) at the ends of lines and ``<BLANKLINE>`` markers
223 individually. Default is ``trim-doctest-flags``.
224
225 .. rst:directive:option:: skipif: condition
226 :type: text
227
228 Skip the directive if the python expression *condition* is True.
229 See :ref:`skipping tests conditionally <doctest-skipif>`.
230
231 Example::
232
233 .. testcode::
234
235 print('Output text.')
236
237 .. testoutput::
238 :hide:
239 :options: -ELLIPSIS, +NORMALIZE_WHITESPACE
240
241 Output text.
242
243 The following is an example for the usage of the directives. The test via
244 :rst:dir:`doctest` and the test via :rst:dir:`testcode` and
245 :rst:dir:`testoutput` are equivalent. ::
246
247 The parrot module
248 =================
249
250 .. testsetup:: *
251
252 import parrot
253
254 The parrot module is a module about parrots.
255
256 Doctest example:
257
258 .. doctest::
259
260 >>> parrot.voom(3000)
261 This parrot wouldn't voom if you put 3000 volts through it!
262
263 Test-Output example:
264
265 .. testcode::
266
267 parrot.voom(3000)
268
269 This would output:
270
271 .. testoutput::
272
273 This parrot wouldn't voom if you put 3000 volts through it!
274
275
276 .. _doctest-skipif:
277
278 Skipping tests conditionally
279 ----------------------------
280
281 ``skipif``, a string option, can be used to skip directives conditionally. This
282 may be useful e.g. when a different set of tests should be run depending on the
283 environment (hardware, network/VPN, optional dependencies or different versions
284 of dependencies). The ``skipif`` option is supported by all of the doctest
285 directives. Below are typical use cases for ``skipif`` when used for different
286 directives:
287
288 - :rst:dir:`testsetup` and :rst:dir:`testcleanup`
289
290 - conditionally skip test setup and/or cleanup
291 - customize setup/cleanup code per environment
292
293 - :rst:dir:`doctest`
294
295 - conditionally skip both a test and its output verification
296
297 - :rst:dir:`testcode`
298
299 - conditionally skip a test
300 - customize test code per environment
301
302 - :rst:dir:`testoutput`
303
304 - conditionally skip output assertion for a skipped test
305 - expect different output depending on the environment
306
307 The value of the ``skipif`` option is evaluated as a Python expression. If the
308 result is a true value, the directive is omitted from the test run just as if
309 it wasn't present in the file at all.
310
311 Instead of repeating an expression, the :confval:`doctest_global_setup`
312 configuration option can be used to assign it to a variable which can then be
313 used instead.
314
315 Here's an example which skips some tests if Pandas is not installed:
316
317 .. code-block:: py
318 :caption: conf.py
319
320 extensions = ['sphinx.ext.doctest']
321 doctest_global_setup = '''
322 try:
323 import pandas as pd
324 except ImportError:
325 pd = None
326 '''
327
328 .. code-block:: rst
329 :caption: contents.rst
330
331 .. testsetup::
332 :skipif: pd is None
333
334 data = pd.Series([42])
335
336 .. doctest::
337 :skipif: pd is None
338
339 >>> data.iloc[0]
340 42
341
342 .. testcode::
343 :skipif: pd is None
344
345 print(data.iloc[-1])
346
347 .. testoutput::
348 :skipif: pd is None
349
350 42
351
352
353 Configuration
354 -------------
355
356 The doctest extension uses the following configuration values:
357
358 .. confval:: doctest_default_flags
359 :type: :code-py:`int`
360 :default: :code-py:`ELLIPSIS | IGNORE_EXCEPTION_DETAIL | DONT_ACCEPT_TRUE_FOR_1`
361
362 By default, these options are enabled:
363
364 - ``ELLIPSIS``, allowing you to put ellipses in the expected output that
365 match anything in the actual output;
366 - ``IGNORE_EXCEPTION_DETAIL``, causing everything following the leftmost
367 colon and any module information in the exception name to be ignored;
368 - ``DONT_ACCEPT_TRUE_FOR_1``, rejecting "True" in the output where "1" is
369 given -- the default behavior of accepting this substitution is a relic of
370 pre-Python 2.2 times.
371
372 .. versionadded:: 1.5
373
374 .. confval:: doctest_show_successes
375 :type: :code-py:`bool`
376 :default: :code-py:`True`
377
378 Controls whether successes are reported.
379
380 For a project with many doctests,
381 it may be useful to set this to ``False`` to only highlight failures.
382
383 .. versionadded:: 7.2
384
385 .. confval:: doctest_path
386 :type: :code-py:`Sequence[str]`
387 :default: :code-py:`()`
388
389 A list of directories that will be added to :data:`sys.path` when the doctest
390 builder is used. (Make sure it contains absolute paths.)
391
392 .. confval:: doctest_global_setup
393 :type: :code-py:`str`
394 :default: :code-py:`''`
395
396 Python code that is treated like it were put in a ``testsetup`` directive for
397 *every* file that is tested, and for every group. You can use this to
398 e.g. import modules you will always need in your doctests.
399
400 .. versionadded:: 0.6
401
402 .. confval:: doctest_global_cleanup
403 :type: :code-py:`str`
404 :default: :code-py:`''`
405
406 Python code that is treated like it were put in a ``testcleanup`` directive
407 for *every* file that is tested, and for every group. You can use this to
408 e.g. remove any temporary files that the tests leave behind.
409
410 .. versionadded:: 1.1
411
412 .. confval:: doctest_test_doctest_blocks
413 :type: :code-py:`str`
414 :default: :code-py:`'default'`
415
416 If this is a nonempty string,
417 standard reStructuredText doctest blocks will be tested too.
418 They will be assigned to the group name given.
419
420 reStructuredText doctest blocks are simply doctests
421 put into a paragraph of their own, like so::
422
423 Some documentation text.
424
425 >>> print(1)
426 1
427
428 Some more documentation text.
429
430 (Note that no special ``::`` is used to introduce a doctest block; docutils
431 recognizes them from the leading ``>>>``. Also, no additional indentation is
432 used, though it doesn't hurt.)
433
434 If this value is left at its default value, the above snippet is interpreted
435 by the doctest builder exactly like the following::
436
437 Some documentation text.
438
439 .. doctest::
440
441 >>> print(1)
442 1
443
444 Some more documentation text.
445
446 This feature makes it easy for you to test doctests in docstrings included
447 with the :mod:`~sphinx.ext.autodoc` extension without marking them up with a
448 special directive.
449
450 Note though that you can't have blank lines in reStructuredText doctest blocks.
451 They will be interpreted as one block ending and another one starting.
452 Also, removal of ``<BLANKLINE>`` and ``# doctest:`` options only works in
453 :rst:dir:`doctest` blocks, though you may set :confval:`trim_doctest_flags`
454 to achieve that in all code blocks with Python console content.
455
456 .. confval:: doctest_fail_fast
457 :type: :code-py:`bool`
458 :default: :code-py:`False`
459
460 Exit when the first failure is encountered.
461
462 .. versionadded:: 9.0