blob: 42ad0c9f06e237184da838b7d560be1680384780 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`doctest` --- Test interactive Python examples
2===================================================
3
4.. module:: doctest
5 :synopsis: Test pieces of code within docstrings.
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Tim Peters <tim@python.org>
8.. sectionauthor:: Tim Peters <tim@python.org>
9.. sectionauthor:: Moshe Zadka <moshez@debian.org>
10.. sectionauthor:: Edward Loper <edloper@users.sourceforge.net>
11
Terry Jan Reedyfa089b92016-06-11 15:02:54 -040012**Source code:** :source:`Lib/doctest.py`
13
14--------------
Georg Brandl116aa622007-08-15 14:28:22 +000015
16The :mod:`doctest` module searches for pieces of text that look like interactive
17Python sessions, and then executes those sessions to verify that they work
18exactly as shown. There are several common ways to use doctest:
19
20* To check that a module's docstrings are up-to-date by verifying that all
21 interactive examples still work as documented.
22
23* To perform regression testing by verifying that interactive examples from a
24 test file or a test object work as expected.
25
26* To write tutorial documentation for a package, liberally illustrated with
27 input-output examples. Depending on whether the examples or the expository text
28 are emphasized, this has the flavor of "literate testing" or "executable
29 documentation".
30
31Here's a complete but small example module::
32
33 """
34 This is the "example" module.
35
36 The example module supplies one function, factorial(). For example,
37
38 >>> factorial(5)
39 120
40 """
41
42 def factorial(n):
43 """Return the factorial of n, an exact integer >= 0.
44
Georg Brandl116aa622007-08-15 14:28:22 +000045 >>> [factorial(n) for n in range(6)]
46 [1, 1, 2, 6, 24, 120]
Georg Brandl116aa622007-08-15 14:28:22 +000047 >>> factorial(30)
Georg Brandl5c106642007-11-29 17:41:05 +000048 265252859812191058636308480000000
Georg Brandl116aa622007-08-15 14:28:22 +000049 >>> factorial(-1)
50 Traceback (most recent call last):
51 ...
52 ValueError: n must be >= 0
53
54 Factorials of floats are OK, but the float must be an exact integer:
55 >>> factorial(30.1)
56 Traceback (most recent call last):
57 ...
58 ValueError: n must be exact integer
59 >>> factorial(30.0)
Georg Brandl5c106642007-11-29 17:41:05 +000060 265252859812191058636308480000000
Georg Brandl116aa622007-08-15 14:28:22 +000061
62 It must also not be ridiculously large:
63 >>> factorial(1e100)
64 Traceback (most recent call last):
65 ...
66 OverflowError: n too large
67 """
68
Georg Brandl116aa622007-08-15 14:28:22 +000069 import math
70 if not n >= 0:
71 raise ValueError("n must be >= 0")
72 if math.floor(n) != n:
73 raise ValueError("n must be exact integer")
74 if n+1 == n: # catch a value like 1e300
75 raise OverflowError("n too large")
76 result = 1
77 factor = 2
78 while factor <= n:
79 result *= factor
80 factor += 1
81 return result
82
Georg Brandl116aa622007-08-15 14:28:22 +000083
84 if __name__ == "__main__":
Guido van Rossum04110fb2007-08-24 16:32:05 +000085 import doctest
86 doctest.testmod()
Georg Brandl116aa622007-08-15 14:28:22 +000087
88If you run :file:`example.py` directly from the command line, :mod:`doctest`
Martin Panter1050d2d2016-07-26 11:18:21 +020089works its magic:
90
91.. code-block:: shell-session
Georg Brandl116aa622007-08-15 14:28:22 +000092
93 $ python example.py
94 $
95
96There's no output! That's normal, and it means all the examples worked. Pass
Éric Araujo713d3032010-11-18 16:38:46 +000097``-v`` to the script, and :mod:`doctest` prints a detailed log of what
Martin Panter1050d2d2016-07-26 11:18:21 +020098it's trying, and prints a summary at the end:
99
100.. code-block:: shell-session
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 $ python example.py -v
103 Trying:
104 factorial(5)
105 Expecting:
106 120
107 ok
108 Trying:
109 [factorial(n) for n in range(6)]
110 Expecting:
111 [1, 1, 2, 6, 24, 120]
112 ok
Georg Brandl116aa622007-08-15 14:28:22 +0000113
Martin Panter1050d2d2016-07-26 11:18:21 +0200114And so on, eventually ending with:
115
116.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 Trying:
119 factorial(1e100)
120 Expecting:
121 Traceback (most recent call last):
122 ...
123 OverflowError: n too large
124 ok
Georg Brandl116aa622007-08-15 14:28:22 +0000125 2 items passed all tests:
126 1 tests in __main__
127 8 tests in __main__.factorial
Guido van Rossum04110fb2007-08-24 16:32:05 +0000128 9 tests in 2 items.
Georg Brandl116aa622007-08-15 14:28:22 +0000129 9 passed and 0 failed.
130 Test passed.
131 $
132
133That's all you need to know to start making productive use of :mod:`doctest`!
134Jump in. The following sections provide full details. Note that there are many
135examples of doctests in the standard Python test suite and libraries.
136Especially useful examples can be found in the standard test file
137:file:`Lib/test/test_doctest.py`.
138
139
140.. _doctest-simple-testmod:
141
142Simple Usage: Checking Examples in Docstrings
143---------------------------------------------
144
145The simplest way to start using doctest (but not necessarily the way you'll
146continue to do it) is to end each module :mod:`M` with::
147
Guido van Rossum04110fb2007-08-24 16:32:05 +0000148 if __name__ == "__main__":
Georg Brandl116aa622007-08-15 14:28:22 +0000149 import doctest
150 doctest.testmod()
151
Georg Brandl116aa622007-08-15 14:28:22 +0000152:mod:`doctest` then examines docstrings in module :mod:`M`.
153
154Running the module as a script causes the examples in the docstrings to get
155executed and verified::
156
157 python M.py
158
159This won't display anything unless an example fails, in which case the failing
160example(s) and the cause(s) of the failure(s) are printed to stdout, and the
161final line of output is ``***Test Failed*** N failures.``, where *N* is the
162number of examples that failed.
163
Éric Araujo713d3032010-11-18 16:38:46 +0000164Run it with the ``-v`` switch instead::
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166 python M.py -v
167
168and a detailed report of all examples tried is printed to standard output, along
169with assorted summaries at the end.
170
171You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or
172prohibit it by passing ``verbose=False``. In either of those cases,
Éric Araujo713d3032010-11-18 16:38:46 +0000173``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not
Georg Brandl116aa622007-08-15 14:28:22 +0000174has no effect).
175
Georg Brandl31835852008-05-12 17:38:56 +0000176There is also a command line shortcut for running :func:`testmod`. You can
177instruct the Python interpreter to run the doctest module directly from the
178standard library and pass the module name(s) on the command line::
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 python -m doctest -v example.py
181
182This will import :file:`example.py` as a standalone module and run
183:func:`testmod` on it. Note that this may not work correctly if the file is
184part of a package and imports other submodules from that package.
185
186For more information on :func:`testmod`, see section :ref:`doctest-basic-api`.
187
188
189.. _doctest-simple-testfile:
190
191Simple Usage: Checking Examples in a Text File
192----------------------------------------------
193
194Another simple application of doctest is testing interactive examples in a text
195file. This can be done with the :func:`testfile` function::
196
197 import doctest
198 doctest.testfile("example.txt")
199
200That short script executes and verifies any interactive Python examples
201contained in the file :file:`example.txt`. The file content is treated as if it
202were a single giant docstring; the file doesn't need to contain a Python
Martin Panter1050d2d2016-07-26 11:18:21 +0200203program! For example, perhaps :file:`example.txt` contains this:
204
205.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 The ``example`` module
208 ======================
209
210 Using ``factorial``
211 -------------------
212
213 This is an example text file in reStructuredText format. First import
214 ``factorial`` from the ``example`` module:
215
216 >>> from example import factorial
217
218 Now use it:
219
220 >>> factorial(6)
221 120
222
223Running ``doctest.testfile("example.txt")`` then finds the error in this
224documentation::
225
226 File "./example.txt", line 14, in example.txt
227 Failed example:
228 factorial(6)
229 Expected:
230 120
231 Got:
232 720
233
234As with :func:`testmod`, :func:`testfile` won't display anything unless an
235example fails. If an example does fail, then the failing example(s) and the
236cause(s) of the failure(s) are printed to stdout, using the same format as
237:func:`testmod`.
238
239By default, :func:`testfile` looks for files in the calling module's directory.
240See section :ref:`doctest-basic-api` for a description of the optional arguments
241that can be used to tell it to look for files in other locations.
242
243Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the
Éric Araujo713d3032010-11-18 16:38:46 +0000244``-v`` command-line switch or with the optional keyword argument
Georg Brandl116aa622007-08-15 14:28:22 +0000245*verbose*.
246
Georg Brandl31835852008-05-12 17:38:56 +0000247There is also a command line shortcut for running :func:`testfile`. You can
248instruct the Python interpreter to run the doctest module directly from the
249standard library and pass the file name(s) on the command line::
Georg Brandl116aa622007-08-15 14:28:22 +0000250
251 python -m doctest -v example.txt
252
253Because the file name does not end with :file:`.py`, :mod:`doctest` infers that
254it must be run with :func:`testfile`, not :func:`testmod`.
255
256For more information on :func:`testfile`, see section :ref:`doctest-basic-api`.
257
258
259.. _doctest-how-it-works:
260
261How It Works
262------------
263
264This section examines in detail how doctest works: which docstrings it looks at,
265how it finds interactive examples, what execution context it uses, how it
266handles exceptions, and how option flags can be used to control its behavior.
267This is the information that you need to know to write doctest examples; for
268information about actually running doctest on these examples, see the following
269sections.
270
271
272.. _doctest-which-docstrings:
273
274Which Docstrings Are Examined?
275^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
276
277The module docstring, and all function, class and method docstrings are
278searched. Objects imported into the module are not searched.
279
280In addition, if ``M.__test__`` exists and "is true", it must be a dict, and each
281entry maps a (string) name to a function object, class object, or string.
282Function and class object docstrings found from ``M.__test__`` are searched, and
283strings are treated as if they were docstrings. In output, a key ``K`` in
284``M.__test__`` appears with name ::
285
286 <name of M>.__test__.K
287
288Any classes found are recursively searched similarly, to test docstrings in
289their contained methods and nested classes.
290
Zachary Warea4b7a752013-11-24 01:19:09 -0600291.. impl-detail::
292 Prior to version 3.4, extension modules written in C were not fully
293 searched by doctest.
294
Georg Brandl116aa622007-08-15 14:28:22 +0000295
296.. _doctest-finding-examples:
297
298How are Docstring Examples Recognized?
299^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
300
R. David Murray9691e592010-06-15 23:46:40 +0000301In most cases a copy-and-paste of an interactive console session works fine,
302but doctest isn't trying to do an exact emulation of any specific Python shell.
Georg Brandl116aa622007-08-15 14:28:22 +0000303
Georg Brandl116aa622007-08-15 14:28:22 +0000304::
305
306 >>> # comments are ignored
307 >>> x = 12
308 >>> x
309 12
310 >>> if x == 13:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000311 ... print("yes")
Georg Brandl116aa622007-08-15 14:28:22 +0000312 ... else:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000313 ... print("no")
314 ... print("NO")
315 ... print("NO!!!")
Georg Brandl116aa622007-08-15 14:28:22 +0000316 ...
317 no
318 NO
319 NO!!!
320 >>>
321
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300322.. index::
323 single: >>>; interpreter prompt
324 single: ...; interpreter prompt
325
Georg Brandl116aa622007-08-15 14:28:22 +0000326Any expected output must immediately follow the final ``'>>> '`` or ``'... '``
327line containing the code, and the expected output (if any) extends to the next
328``'>>> '`` or all-whitespace line.
329
330The fine print:
331
332* Expected output cannot contain an all-whitespace line, since such a line is
333 taken to signal the end of expected output. If expected output does contain a
334 blank line, put ``<BLANKLINE>`` in your doctest example each place a blank line
335 is expected.
336
R. David Murray9691e592010-06-15 23:46:40 +0000337* All hard tab characters are expanded to spaces, using 8-column tab stops.
338 Tabs in output generated by the tested code are not modified. Because any
339 hard tabs in the sample output *are* expanded, this means that if the code
340 output includes hard tabs, the only way the doctest can pass is if the
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700341 :const:`NORMALIZE_WHITESPACE` option or :ref:`directive <doctest-directives>`
342 is in effect.
R. David Murray9691e592010-06-15 23:46:40 +0000343 Alternatively, the test can be rewritten to capture the output and compare it
344 to an expected value as part of the test. This handling of tabs in the
345 source was arrived at through trial and error, and has proven to be the least
346 error prone way of handling them. It is possible to use a different
347 algorithm for handling tabs by writing a custom :class:`DocTestParser` class.
348
Georg Brandl116aa622007-08-15 14:28:22 +0000349* Output to stdout is captured, but not output to stderr (exception tracebacks
350 are captured via a different means).
351
352* If you continue a line via backslashing in an interactive session, or for any
353 other reason use a backslash, you should use a raw docstring, which will
354 preserve your backslashes exactly as you type them::
355
356 >>> def f(x):
357 ... r'''Backslashes in a raw docstring: m\n'''
Georg Brandl6911e3c2007-09-04 07:15:32 +0000358 >>> print(f.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000359 Backslashes in a raw docstring: m\n
360
361 Otherwise, the backslash will be interpreted as part of the string. For example,
Ezio Melotti694f2332012-09-20 09:47:03 +0300362 the ``\n`` above would be interpreted as a newline character. Alternatively, you
Georg Brandl116aa622007-08-15 14:28:22 +0000363 can double each backslash in the doctest version (and not use a raw string)::
364
365 >>> def f(x):
366 ... '''Backslashes in a raw docstring: m\\n'''
Georg Brandl6911e3c2007-09-04 07:15:32 +0000367 >>> print(f.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000368 Backslashes in a raw docstring: m\n
369
370* The starting column doesn't matter::
371
372 >>> assert "Easy!"
373 >>> import math
374 >>> math.floor(1.9)
R. David Murray7c5714f2009-11-23 03:13:23 +0000375 1
Georg Brandl116aa622007-08-15 14:28:22 +0000376
377 and as many leading whitespace characters are stripped from the expected output
378 as appeared in the initial ``'>>> '`` line that started the example.
379
380
381.. _doctest-execution-context:
382
383What's the Execution Context?
384^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
385
386By default, each time :mod:`doctest` finds a docstring to test, it uses a
387*shallow copy* of :mod:`M`'s globals, so that running tests doesn't change the
388module's real globals, and so that one test in :mod:`M` can't leave behind
389crumbs that accidentally allow another test to work. This means examples can
390freely use any names defined at top-level in :mod:`M`, and names defined earlier
391in the docstring being run. Examples cannot see names defined in other
392docstrings.
393
394You can force use of your own dict as the execution context by passing
395``globs=your_dict`` to :func:`testmod` or :func:`testfile` instead.
396
397
398.. _doctest-exceptions:
399
400What About Exceptions?
401^^^^^^^^^^^^^^^^^^^^^^
402
403No problem, provided that the traceback is the only output produced by the
404example: just paste in the traceback. [#]_ Since tracebacks contain details
405that are likely to change rapidly (for example, exact file paths and line
406numbers), this is one case where doctest works hard to be flexible in what it
407accepts.
408
409Simple example::
410
411 >>> [1, 2, 3].remove(42)
412 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530413 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000414 ValueError: list.remove(x): x not in list
415
416That doctest succeeds if :exc:`ValueError` is raised, with the ``list.remove(x):
417x not in list`` detail as shown.
418
419The expected output for an exception must start with a traceback header, which
420may be either of the following two lines, indented the same as the first line of
421the example::
422
423 Traceback (most recent call last):
424 Traceback (innermost last):
425
426The traceback header is followed by an optional traceback stack, whose contents
427are ignored by doctest. The traceback stack is typically omitted, or copied
428verbatim from an interactive session.
429
430The traceback stack is followed by the most interesting part: the line(s)
431containing the exception type and detail. This is usually the last line of a
432traceback, but can extend across multiple lines if the exception has a
433multi-line detail::
434
435 >>> raise ValueError('multi\n line\ndetail')
436 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530437 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000438 ValueError: multi
439 line
440 detail
441
442The last three lines (starting with :exc:`ValueError`) are compared against the
443exception's type and detail, and the rest are ignored.
444
445Best practice is to omit the traceback stack, unless it adds significant
446documentation value to the example. So the last example is probably better as::
447
448 >>> raise ValueError('multi\n line\ndetail')
449 Traceback (most recent call last):
450 ...
451 ValueError: multi
452 line
453 detail
454
455Note that tracebacks are treated very specially. In particular, in the
456rewritten example, the use of ``...`` is independent of doctest's
457:const:`ELLIPSIS` option. The ellipsis in that example could be left out, or
458could just as well be three (or three hundred) commas or digits, or an indented
459transcript of a Monty Python skit.
460
461Some details you should read once, but won't need to remember:
462
463* Doctest can't guess whether your expected output came from an exception
464 traceback or from ordinary printing. So, e.g., an example that expects
465 ``ValueError: 42 is prime`` will pass whether :exc:`ValueError` is actually
466 raised or if the example merely prints that traceback text. In practice,
467 ordinary output rarely begins with a traceback header line, so this doesn't
468 create real problems.
469
470* Each line of the traceback stack (if present) must be indented further than
471 the first line of the example, *or* start with a non-alphanumeric character.
472 The first line following the traceback header indented the same and starting
473 with an alphanumeric is taken to be the start of the exception detail. Of
474 course this does the right thing for genuine tracebacks.
475
Nick Coghlan5e76e942010-06-12 13:42:46 +0000476* When the :const:`IGNORE_EXCEPTION_DETAIL` doctest option is specified,
477 everything following the leftmost colon and any module information in the
478 exception name is ignored.
Georg Brandl116aa622007-08-15 14:28:22 +0000479
480* The interactive shell omits the traceback header line for some
481 :exc:`SyntaxError`\ s. But doctest uses the traceback header line to
482 distinguish exceptions from non-exceptions. So in the rare case where you need
483 to test a :exc:`SyntaxError` that omits the traceback header, you will need to
484 manually add the traceback header line to your test example.
485
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200486.. index:: single: ^ (caret); marker
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300487
Georg Brandl116aa622007-08-15 14:28:22 +0000488* For some :exc:`SyntaxError`\ s, Python displays the character position of the
489 syntax error, using a ``^`` marker::
490
491 >>> 1 1
492 File "<stdin>", line 1
493 1 1
494 ^
495 SyntaxError: invalid syntax
496
497 Since the lines showing the position of the error come before the exception type
498 and detail, they are not checked by doctest. For example, the following test
499 would pass, even though it puts the ``^`` marker in the wrong location::
500
501 >>> 1 1
502 Traceback (most recent call last):
503 File "<stdin>", line 1
504 1 1
505 ^
506 SyntaxError: invalid syntax
507
Georg Brandl116aa622007-08-15 14:28:22 +0000508
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700509.. _option-flags-and-directives:
Georg Brandl116aa622007-08-15 14:28:22 +0000510.. _doctest-options:
511
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700512Option Flags
513^^^^^^^^^^^^
Georg Brandl116aa622007-08-15 14:28:22 +0000514
515A number of option flags control various aspects of doctest's behavior.
516Symbolic names for the flags are supplied as module constants, which can be
Mariatta Wijaya81b89772017-02-06 20:15:01 -0800517:ref:`bitwise ORed <bitwise>` together and passed to various functions.
518The names can also be used in :ref:`doctest directives <doctest-directives>`,
519and may be passed to the doctest command line interface via the ``-o`` option.
R David Murray5707d502013-06-23 14:24:13 -0400520
Georg Brandldf48b972014-03-24 09:06:18 +0100521.. versionadded:: 3.4
522 The ``-o`` command line option.
Georg Brandl116aa622007-08-15 14:28:22 +0000523
524The first group of options define test semantics, controlling aspects of how
525doctest decides whether actual output matches an example's expected output:
526
527
528.. data:: DONT_ACCEPT_TRUE_FOR_1
529
530 By default, if an expected output block contains just ``1``, an actual output
531 block containing just ``1`` or just ``True`` is considered to be a match, and
532 similarly for ``0`` versus ``False``. When :const:`DONT_ACCEPT_TRUE_FOR_1` is
533 specified, neither substitution is allowed. The default behavior caters to that
534 Python changed the return type of many functions from integer to boolean;
535 doctests expecting "little integer" output still work in these cases. This
536 option will probably go away, but not for several years.
537
538
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300539.. index:: single: <BLANKLINE>
Georg Brandl116aa622007-08-15 14:28:22 +0000540.. data:: DONT_ACCEPT_BLANKLINE
541
542 By default, if an expected output block contains a line containing only the
543 string ``<BLANKLINE>``, then that line will match a blank line in the actual
544 output. Because a genuinely blank line delimits the expected output, this is
545 the only way to communicate that a blank line is expected. When
546 :const:`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed.
547
548
549.. data:: NORMALIZE_WHITESPACE
550
551 When specified, all sequences of whitespace (blanks and newlines) are treated as
552 equal. Any sequence of whitespace within the expected output will match any
553 sequence of whitespace within the actual output. By default, whitespace must
554 match exactly. :const:`NORMALIZE_WHITESPACE` is especially useful when a line of
555 expected output is very long, and you want to wrap it across multiple lines in
556 your source.
557
558
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300559.. index:: single: ...; in doctests
Georg Brandl116aa622007-08-15 14:28:22 +0000560.. data:: ELLIPSIS
561
562 When specified, an ellipsis marker (``...``) in the expected output can match
563 any substring in the actual output. This includes substrings that span line
564 boundaries, and empty substrings, so it's best to keep usage of this simple.
565 Complicated uses can lead to the same kinds of "oops, it matched too much!"
566 surprises that ``.*`` is prone to in regular expressions.
567
568
569.. data:: IGNORE_EXCEPTION_DETAIL
570
571 When specified, an example that expects an exception passes if an exception of
572 the expected type is raised, even if the exception detail does not match. For
573 example, an example expecting ``ValueError: 42`` will pass if the actual
574 exception raised is ``ValueError: 3*14``, but will fail, e.g., if
575 :exc:`TypeError` is raised.
576
Nick Coghlan5e76e942010-06-12 13:42:46 +0000577 It will also ignore the module name used in Python 3 doctest reports. Hence
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700578 both of these variations will work with the flag specified, regardless of
579 whether the test is run under Python 2.7 or Python 3.2 (or later versions)::
Nick Coghlan5e76e942010-06-12 13:42:46 +0000580
Chris Jerdonek3fa8c592012-10-10 08:34:38 -0700581 >>> raise CustomError('message')
Nick Coghlan5e76e942010-06-12 13:42:46 +0000582 Traceback (most recent call last):
583 CustomError: message
584
Chris Jerdonek3fa8c592012-10-10 08:34:38 -0700585 >>> raise CustomError('message')
Nick Coghlan5e76e942010-06-12 13:42:46 +0000586 Traceback (most recent call last):
587 my_module.CustomError: message
588
589 Note that :const:`ELLIPSIS` can also be used to ignore the
590 details of the exception message, but such a test may still fail based
591 on whether or not the module details are printed as part of the
592 exception name. Using :const:`IGNORE_EXCEPTION_DETAIL` and the details
593 from Python 2.3 is also the only clear way to write a doctest that doesn't
594 care about the exception detail yet continues to pass under Python 2.3 or
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700595 earlier (those releases do not support :ref:`doctest directives
596 <doctest-directives>` and ignore them as irrelevant comments). For example::
Georg Brandl116aa622007-08-15 14:28:22 +0000597
Chris Jerdonek3fa8c592012-10-10 08:34:38 -0700598 >>> (1, 2)[3] = 'moo'
Georg Brandl116aa622007-08-15 14:28:22 +0000599 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530600 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000601 TypeError: object doesn't support item assignment
602
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700603 passes under Python 2.3 and later Python versions with the flag specified,
604 even though the detail
Nick Coghlan5e76e942010-06-12 13:42:46 +0000605 changed in Python 2.4 to say "does not" instead of "doesn't".
606
607 .. versionchanged:: 3.2
Georg Brandl67b21b72010-08-17 15:07:14 +0000608 :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information relating
609 to the module containing the exception under test.
Georg Brandl116aa622007-08-15 14:28:22 +0000610
611
612.. data:: SKIP
613
614 When specified, do not run the example at all. This can be useful in contexts
615 where doctest examples serve as both documentation and test cases, and an
616 example should be included for documentation purposes, but should not be
617 checked. E.g., the example's output might be random; or the example might
618 depend on resources which would be unavailable to the test driver.
619
620 The SKIP flag can also be used for temporarily "commenting out" examples.
621
622
623.. data:: COMPARISON_FLAGS
624
625 A bitmask or'ing together all the comparison flags above.
626
627The second group of options controls how test failures are reported:
628
629
630.. data:: REPORT_UDIFF
631
632 When specified, failures that involve multi-line expected and actual outputs are
633 displayed using a unified diff.
634
635
636.. data:: REPORT_CDIFF
637
638 When specified, failures that involve multi-line expected and actual outputs
639 will be displayed using a context diff.
640
641
642.. data:: REPORT_NDIFF
643
644 When specified, differences are computed by ``difflib.Differ``, using the same
645 algorithm as the popular :file:`ndiff.py` utility. This is the only method that
646 marks differences within lines as well as across lines. For example, if a line
647 of expected output contains digit ``1`` where actual output contains letter
648 ``l``, a line is inserted with a caret marking the mismatching column positions.
649
650
651.. data:: REPORT_ONLY_FIRST_FAILURE
652
653 When specified, display the first failing example in each doctest, but suppress
654 output for all remaining examples. This will prevent doctest from reporting
655 correct examples that break because of earlier failures; but it might also hide
656 incorrect examples that fail independently of the first failure. When
657 :const:`REPORT_ONLY_FIRST_FAILURE` is specified, the remaining examples are
658 still run, and still count towards the total number of failures reported; only
659 the output is suppressed.
660
661
R David Murray5a9d7062012-11-21 15:09:21 -0500662.. data:: FAIL_FAST
663
664 When specified, exit after the first failing example and don't attempt to run
R David Murray60dd6e52012-11-22 06:22:41 -0500665 the remaining examples. Thus, the number of failures reported will be at most
666 1. This flag may be useful during debugging, since examples after the first
R David Murray5a9d7062012-11-21 15:09:21 -0500667 failure won't even produce debugging output.
668
R David Murray5707d502013-06-23 14:24:13 -0400669 The doctest command line accepts the option ``-f`` as a shorthand for ``-o
670 FAIL_FAST``.
671
R David Murray5a9d7062012-11-21 15:09:21 -0500672 .. versionadded:: 3.4
673
674
Georg Brandl116aa622007-08-15 14:28:22 +0000675.. data:: REPORTING_FLAGS
676
677 A bitmask or'ing together all the reporting flags above.
678
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700679
680There is also a way to register new option flag names, though this isn't
681useful unless you intend to extend :mod:`doctest` internals via subclassing:
682
683
684.. function:: register_optionflag(name)
685
686 Create a new option flag with a given name, and return the new flag's integer
687 value. :func:`register_optionflag` can be used when subclassing
688 :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are
689 supported by your subclasses. :func:`register_optionflag` should always be
690 called using the following idiom::
691
692 MY_FLAG = register_optionflag('MY_FLAG')
693
694
Serhiy Storchakaddb961d2018-10-26 09:00:49 +0300695.. index::
Serhiy Storchaka913876d2018-10-28 13:41:26 +0200696 single: # (hash); in doctests
697 single: + (plus); in doctests
698 single: - (minus); in doctests
Chris Jerdonek3650ea22012-10-10 06:52:08 -0700699.. _doctest-directives:
700
701Directives
702^^^^^^^^^^
703
704Doctest directives may be used to modify the :ref:`option flags
705<doctest-options>` for an individual example. Doctest directives are
706special Python comments following an example's source code:
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708.. productionlist:: doctest
709 directive: "#" "doctest:" `directive_options`
710 directive_options: `directive_option` ("," `directive_option`)\*
711 directive_option: `on_or_off` `directive_option_name`
712 on_or_off: "+" \| "-"
713 directive_option_name: "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...
714
715Whitespace is not allowed between the ``+`` or ``-`` and the directive option
716name. The directive option name can be any of the option flag names explained
717above.
718
719An example's doctest directives modify doctest's behavior for that single
720example. Use ``+`` to enable the named behavior, or ``-`` to disable it.
721
Julien Palardc8a10d22020-12-15 17:23:03 +0100722For example, this test passes:
Nick Coghlan8f80e0a2012-10-03 12:21:44 +0530723
Julien Palardc8a10d22020-12-15 17:23:03 +0100724.. doctest::
725 :no-trim-doctest-flags:
726
727 >>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000728 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
729 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
730
731Without the directive it would fail, both because the actual output doesn't have
732two blanks before the single-digit list elements, and because the actual output
733is on a single line. This test also passes, and also requires a directive to do
Julien Palardc8a10d22020-12-15 17:23:03 +0100734so:
Georg Brandl116aa622007-08-15 14:28:22 +0000735
Julien Palardc8a10d22020-12-15 17:23:03 +0100736.. doctest::
737 :no-trim-doctest-flags:
738
739 >>> print(list(range(20))) # doctest: +ELLIPSIS
Georg Brandl116aa622007-08-15 14:28:22 +0000740 [0, 1, ..., 18, 19]
741
Nick Coghlan0b26ccf2012-10-03 13:52:48 +0530742Multiple directives can be used on a single physical line, separated by
Julien Palardc8a10d22020-12-15 17:23:03 +0100743commas:
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Julien Palardc8a10d22020-12-15 17:23:03 +0100745.. doctest::
746 :no-trim-doctest-flags:
747
748 >>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000749 [0, 1, ..., 18, 19]
750
751If multiple directive comments are used for a single example, then they are
Julien Palardc8a10d22020-12-15 17:23:03 +0100752combined:
Georg Brandl116aa622007-08-15 14:28:22 +0000753
Julien Palardc8a10d22020-12-15 17:23:03 +0100754.. doctest::
755 :no-trim-doctest-flags:
756
757 >>> print(list(range(20))) # doctest: +ELLIPSIS
758 ... # doctest: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000759 [0, 1, ..., 18, 19]
760
761As the previous example shows, you can add ``...`` lines to your example
762containing only directives. This can be useful when an example is too long for
Julien Palardc8a10d22020-12-15 17:23:03 +0100763a directive to comfortably fit on the same line:
764
765.. doctest::
766 :no-trim-doctest-flags:
Georg Brandl116aa622007-08-15 14:28:22 +0000767
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000768 >>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
Georg Brandl116aa622007-08-15 14:28:22 +0000769 ... # doctest: +ELLIPSIS
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000770 [0, ..., 4, 10, ..., 19, 30, ..., 39]
Georg Brandl116aa622007-08-15 14:28:22 +0000771
772Note that since all options are disabled by default, and directives apply only
773to the example they appear in, enabling options (via ``+`` in a directive) is
774usually the only meaningful choice. However, option flags can also be passed to
775functions that run doctests, establishing different defaults. In such cases,
776disabling an option via ``-`` in a directive can be useful.
777
Georg Brandl116aa622007-08-15 14:28:22 +0000778
779.. _doctest-warnings:
780
781Warnings
782^^^^^^^^
783
784:mod:`doctest` is serious about requiring exact matches in expected output. If
785even a single character doesn't match, the test fails. This will probably
786surprise you a few times, as you learn exactly what Python does and doesn't
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200787guarantee about output. For example, when printing a set, Python doesn't
788guarantee that the element is printed in any particular order, so a test like ::
Georg Brandl116aa622007-08-15 14:28:22 +0000789
790 >>> foo()
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200791 {"Hermione", "Harry"}
Georg Brandl116aa622007-08-15 14:28:22 +0000792
793is vulnerable! One workaround is to do ::
794
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200795 >>> foo() == {"Hermione", "Harry"}
Georg Brandl116aa622007-08-15 14:28:22 +0000796 True
797
798instead. Another is to do ::
799
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200800 >>> d = sorted(foo())
Georg Brandl116aa622007-08-15 14:28:22 +0000801 >>> d
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200802 ['Harry', 'Hermione']
803
804.. note::
805
806 Before Python 3.6, when printing a dict, Python did not guarantee that
807 the key-value pairs was printed in any particular order.
Georg Brandl116aa622007-08-15 14:28:22 +0000808
809There are others, but you get the idea.
810
Julien Palardc8a10d22020-12-15 17:23:03 +0100811Another bad idea is to print things that embed an object address, like
Georg Brandl116aa622007-08-15 14:28:22 +0000812
Julien Palardc8a10d22020-12-15 17:23:03 +0100813.. doctest::
814
815 >>> id(1.0) # certain to fail some of the time # doctest: +SKIP
Georg Brandl116aa622007-08-15 14:28:22 +0000816 7948648
817 >>> class C: pass
Julien Palardc8a10d22020-12-15 17:23:03 +0100818 >>> C() # the default repr() for instances embeds an address # doctest: +SKIP
819 <C object at 0x00AC18F0>
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Julien Palardc8a10d22020-12-15 17:23:03 +0100821The :const:`ELLIPSIS` directive gives a nice approach for the last example:
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Julien Palardc8a10d22020-12-15 17:23:03 +0100823.. doctest::
824 :no-trim-doctest-flags:
825
826 >>> C() # doctest: +ELLIPSIS
827 <C object at 0x...>
Georg Brandl116aa622007-08-15 14:28:22 +0000828
829Floating-point numbers are also subject to small output variations across
830platforms, because Python defers to the platform C library for float formatting,
831and C libraries vary widely in quality here. ::
832
833 >>> 1./7 # risky
834 0.14285714285714285
Georg Brandl6911e3c2007-09-04 07:15:32 +0000835 >>> print(1./7) # safer
Georg Brandl116aa622007-08-15 14:28:22 +0000836 0.142857142857
Georg Brandl6911e3c2007-09-04 07:15:32 +0000837 >>> print(round(1./7, 6)) # much safer
Georg Brandl116aa622007-08-15 14:28:22 +0000838 0.142857
839
840Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
841contrive doctest examples to produce numbers of that form::
842
843 >>> 3./4 # utterly safe
844 0.75
845
846Simple fractions are also easier for people to understand, and that makes for
847better documentation.
848
849
850.. _doctest-basic-api:
851
852Basic API
853---------
854
855The functions :func:`testmod` and :func:`testfile` provide a simple interface to
856doctest that should be sufficient for most basic uses. For a less formal
857introduction to these two functions, see sections :ref:`doctest-simple-testmod`
858and :ref:`doctest-simple-testfile`.
859
860
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000861.. function:: testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=DocTestParser(), encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863 All arguments except *filename* are optional, and should be specified in keyword
864 form.
865
866 Test examples in the file named *filename*. Return ``(failure_count,
867 test_count)``.
868
869 Optional argument *module_relative* specifies how the filename should be
870 interpreted:
871
872 * If *module_relative* is ``True`` (the default), then *filename* specifies an
873 OS-independent module-relative path. By default, this path is relative to the
874 calling module's directory; but if the *package* argument is specified, then it
875 is relative to that package. To ensure OS-independence, *filename* should use
876 ``/`` characters to separate path segments, and may not be an absolute path
877 (i.e., it may not begin with ``/``).
878
879 * If *module_relative* is ``False``, then *filename* specifies an OS-specific
880 path. The path may be absolute or relative; relative paths are resolved with
881 respect to the current working directory.
882
883 Optional argument *name* gives the name of the test; by default, or if ``None``,
884 ``os.path.basename(filename)`` is used.
885
886 Optional argument *package* is a Python package or the name of a Python package
887 whose directory should be used as the base directory for a module-relative
888 filename. If no package is specified, then the calling module's directory is
889 used as the base directory for module-relative filenames. It is an error to
890 specify *package* if *module_relative* is ``False``.
891
892 Optional argument *globs* gives a dict to be used as the globals when executing
893 examples. A new shallow copy of this dict is created for the doctest, so its
894 examples start with a clean slate. By default, or if ``None``, a new empty dict
895 is used.
896
897 Optional argument *extraglobs* gives a dict merged into the globals used to
898 execute examples. This works like :meth:`dict.update`: if *globs* and
899 *extraglobs* have a common key, the associated value in *extraglobs* appears in
900 the combined dict. By default, or if ``None``, no extra globals are used. This
901 is an advanced feature that allows parameterization of doctests. For example, a
902 doctest can be written for a base class, using a generic name for the class,
903 then reused to test any number of subclasses by passing an *extraglobs* dict
904 mapping the generic name to the subclass to be tested.
905
906 Optional argument *verbose* prints lots of stuff if true, and prints only
907 failures if false; by default, or if ``None``, it's true if and only if ``'-v'``
908 is in ``sys.argv``.
909
910 Optional argument *report* prints a summary at the end when true, else prints
911 nothing at the end. In verbose mode, the summary is detailed, else the summary
912 is very brief (in fact, empty if all tests passed).
913
Mariatta Wijaya81b89772017-02-06 20:15:01 -0800914 Optional argument *optionflags* (default value 0) takes the
915 :ref:`bitwise OR <bitwise>` of option flags.
916 See section :ref:`doctest-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000917
918 Optional argument *raise_on_error* defaults to false. If true, an exception is
919 raised upon the first failure or unexpected exception in an example. This
920 allows failures to be post-mortem debugged. Default behavior is to continue
921 running examples.
922
923 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) that
924 should be used to extract tests from the files. It defaults to a normal parser
925 (i.e., ``DocTestParser()``).
926
927 Optional argument *encoding* specifies an encoding that should be used to
928 convert the file to unicode.
929
Georg Brandl116aa622007-08-15 14:28:22 +0000930
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000931.. function:: testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)
Georg Brandl116aa622007-08-15 14:28:22 +0000932
933 All arguments are optional, and all except for *m* should be specified in
934 keyword form.
935
936 Test examples in docstrings in functions and classes reachable from module *m*
937 (or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with
938 ``m.__doc__``.
939
940 Also test examples reachable from dict ``m.__test__``, if it exists and is not
941 ``None``. ``m.__test__`` maps names (strings) to functions, classes and
942 strings; function and class docstrings are searched for examples; strings are
943 searched directly, as if they were docstrings.
944
945 Only docstrings attached to objects belonging to module *m* are searched.
946
947 Return ``(failure_count, test_count)``.
948
949 Optional argument *name* gives the name of the module; by default, or if
950 ``None``, ``m.__name__`` is used.
951
952 Optional argument *exclude_empty* defaults to false. If true, objects for which
953 no doctests are found are excluded from consideration. The default is a backward
954 compatibility hack, so that code still using :meth:`doctest.master.summarize` in
955 conjunction with :func:`testmod` continues to get output for objects with no
956 tests. The *exclude_empty* argument to the newer :class:`DocTestFinder`
957 constructor defaults to true.
958
959 Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*,
960 *raise_on_error*, and *globs* are the same as for function :func:`testfile`
961 above, except that *globs* defaults to ``m.__dict__``.
962
Georg Brandl116aa622007-08-15 14:28:22 +0000963
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000964.. function:: run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000965
Ethan Furman2a5f9da2015-09-17 22:20:41 -0700966 Test examples associated with object *f*; for example, *f* may be a string,
967 a module, a function, or a class object.
Georg Brandl116aa622007-08-15 14:28:22 +0000968
969 A shallow copy of dictionary argument *globs* is used for the execution context.
970
971 Optional argument *name* is used in failure messages, and defaults to
972 ``"NoName"``.
973
974 If optional argument *verbose* is true, output is generated even if there are no
975 failures. By default, output is generated only in case of an example failure.
976
977 Optional argument *compileflags* gives the set of flags that should be used by
978 the Python compiler when running the examples. By default, or if ``None``,
979 flags are deduced corresponding to the set of future features found in *globs*.
980
981 Optional argument *optionflags* works as for function :func:`testfile` above.
982
983
984.. _doctest-unittest-api:
985
986Unittest API
987------------
988
989As your collection of doctest'ed modules grows, you'll want a way to run all
Georg Brandl31835852008-05-12 17:38:56 +0000990their doctests systematically. :mod:`doctest` provides two functions that can
991be used to create :mod:`unittest` test suites from modules and text files
Georg Brandla8514832010-07-10 12:20:38 +0000992containing doctests. To integrate with :mod:`unittest` test discovery, include
993a :func:`load_tests` function in your test module::
Georg Brandl116aa622007-08-15 14:28:22 +0000994
995 import unittest
996 import doctest
Georg Brandla8514832010-07-10 12:20:38 +0000997 import my_module_with_doctests
Georg Brandl116aa622007-08-15 14:28:22 +0000998
Georg Brandla8514832010-07-10 12:20:38 +0000999 def load_tests(loader, tests, ignore):
1000 tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
R. David Murray796343b2010-12-13 22:50:30 +00001001 return tests
Georg Brandl116aa622007-08-15 14:28:22 +00001002
1003There are two main functions for creating :class:`unittest.TestSuite` instances
1004from text files and modules with doctests:
1005
1006
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001007.. function:: DocFileSuite(*paths, module_relative=True, package=None, setUp=None, tearDown=None, globs=None, optionflags=0, parser=DocTestParser(), encoding=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001008
1009 Convert doctest tests from one or more text files to a
1010 :class:`unittest.TestSuite`.
1011
1012 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
1013 and runs the interactive examples in each file. If an example in any file
1014 fails, then the synthesized unit test fails, and a :exc:`failureException`
1015 exception is raised showing the name of the file containing the test and a
1016 (sometimes approximate) line number.
1017
1018 Pass one or more paths (as strings) to text files to be examined.
1019
1020 Options may be provided as keyword arguments:
1021
1022 Optional argument *module_relative* specifies how the filenames in *paths*
1023 should be interpreted:
1024
Benjamin Petersond23f8222009-04-05 19:13:16 +00001025 * If *module_relative* is ``True`` (the default), then each filename in
1026 *paths* specifies an OS-independent module-relative path. By default, this
1027 path is relative to the calling module's directory; but if the *package*
1028 argument is specified, then it is relative to that package. To ensure
1029 OS-independence, each filename should use ``/`` characters to separate path
1030 segments, and may not be an absolute path (i.e., it may not begin with
1031 ``/``).
Georg Brandl116aa622007-08-15 14:28:22 +00001032
Benjamin Petersond23f8222009-04-05 19:13:16 +00001033 * If *module_relative* is ``False``, then each filename in *paths* specifies
1034 an OS-specific path. The path may be absolute or relative; relative paths
1035 are resolved with respect to the current working directory.
Georg Brandl116aa622007-08-15 14:28:22 +00001036
Benjamin Petersond23f8222009-04-05 19:13:16 +00001037 Optional argument *package* is a Python package or the name of a Python
1038 package whose directory should be used as the base directory for
1039 module-relative filenames in *paths*. If no package is specified, then the
1040 calling module's directory is used as the base directory for module-relative
1041 filenames. It is an error to specify *package* if *module_relative* is
1042 ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00001043
Benjamin Petersond23f8222009-04-05 19:13:16 +00001044 Optional argument *setUp* specifies a set-up function for the test suite.
1045 This is called before running the tests in each file. The *setUp* function
Georg Brandl116aa622007-08-15 14:28:22 +00001046 will be passed a :class:`DocTest` object. The setUp function can access the
1047 test globals as the *globs* attribute of the test passed.
1048
Benjamin Petersond23f8222009-04-05 19:13:16 +00001049 Optional argument *tearDown* specifies a tear-down function for the test
1050 suite. This is called after running the tests in each file. The *tearDown*
1051 function will be passed a :class:`DocTest` object. The setUp function can
1052 access the test globals as the *globs* attribute of the test passed.
1053
Georg Brandl116aa622007-08-15 14:28:22 +00001054 Optional argument *globs* is a dictionary containing the initial global
1055 variables for the tests. A new copy of this dictionary is created for each
1056 test. By default, *globs* is a new empty dictionary.
1057
1058 Optional argument *optionflags* specifies the default doctest options for the
1059 tests, created by or-ing together individual option flags. See section
Benjamin Petersond23f8222009-04-05 19:13:16 +00001060 :ref:`doctest-options`. See function :func:`set_unittest_reportflags` below
1061 for a better way to set reporting options.
Georg Brandl116aa622007-08-15 14:28:22 +00001062
Benjamin Petersond23f8222009-04-05 19:13:16 +00001063 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass)
1064 that should be used to extract tests from the files. It defaults to a normal
1065 parser (i.e., ``DocTestParser()``).
Georg Brandl116aa622007-08-15 14:28:22 +00001066
1067 Optional argument *encoding* specifies an encoding that should be used to
1068 convert the file to unicode.
1069
Georg Brandl55ac8f02007-09-01 13:51:09 +00001070 The global ``__file__`` is added to the globals provided to doctests loaded
1071 from a text file using :func:`DocFileSuite`.
Georg Brandl116aa622007-08-15 14:28:22 +00001072
1073
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001074.. function:: DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, checker=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076 Convert doctest tests for a module to a :class:`unittest.TestSuite`.
1077
1078 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
1079 and runs each doctest in the module. If any of the doctests fail, then the
1080 synthesized unit test fails, and a :exc:`failureException` exception is raised
1081 showing the name of the file containing the test and a (sometimes approximate)
1082 line number.
1083
1084 Optional argument *module* provides the module to be tested. It can be a module
1085 object or a (possibly dotted) module name. If not specified, the module calling
1086 this function is used.
1087
1088 Optional argument *globs* is a dictionary containing the initial global
1089 variables for the tests. A new copy of this dictionary is created for each
1090 test. By default, *globs* is a new empty dictionary.
1091
1092 Optional argument *extraglobs* specifies an extra set of global variables, which
1093 is merged into *globs*. By default, no extra globals are used.
1094
1095 Optional argument *test_finder* is the :class:`DocTestFinder` object (or a
1096 drop-in replacement) that is used to extract doctests from the module.
1097
1098 Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for
1099 function :func:`DocFileSuite` above.
1100
Georg Brandl55ac8f02007-09-01 13:51:09 +00001101 This function uses the same search technique as :func:`testmod`.
Georg Brandl116aa622007-08-15 14:28:22 +00001102
R David Murray1976d9b2014-04-14 20:28:36 -04001103 .. versionchanged:: 3.5
1104 :func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if *module*
1105 contains no docstrings instead of raising :exc:`ValueError`.
R David Murray5abd76a2012-09-10 10:15:58 -04001106
Georg Brandl116aa622007-08-15 14:28:22 +00001107
1108Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
1109of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
1110subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented
1111here (it's an internal detail), but studying its code can answer questions about
1112the exact details of :mod:`unittest` integration.
1113
1114Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of
1115:class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass
1116of :class:`DocTestCase`.
1117
1118So both ways of creating a :class:`unittest.TestSuite` run instances of
1119:class:`DocTestCase`. This is important for a subtle reason: when you run
1120:mod:`doctest` functions yourself, you can control the :mod:`doctest` options in
1121use directly, by passing option flags to :mod:`doctest` functions. However, if
1122you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls
1123when and how tests get run. The framework author typically wants to control
1124:mod:`doctest` reporting options (perhaps, e.g., specified by command line
1125options), but there's no way to pass options through :mod:`unittest` to
1126:mod:`doctest` test runners.
1127
1128For this reason, :mod:`doctest` also supports a notion of :mod:`doctest`
1129reporting flags specific to :mod:`unittest` support, via this function:
1130
1131
1132.. function:: set_unittest_reportflags(flags)
1133
1134 Set the :mod:`doctest` reporting flags to use.
1135
Mariatta Wijaya81b89772017-02-06 20:15:01 -08001136 Argument *flags* takes the :ref:`bitwise OR <bitwise>` of option flags. See
1137 section :ref:`doctest-options`. Only "reporting flags" can be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001138
1139 This is a module-global setting, and affects all future doctests run by module
1140 :mod:`unittest`: the :meth:`runTest` method of :class:`DocTestCase` looks at
1141 the option flags specified for the test case when the :class:`DocTestCase`
1142 instance was constructed. If no reporting flags were specified (which is the
1143 typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are
Mariatta Wijaya81b89772017-02-06 20:15:01 -08001144 :ref:`bitwise ORed <bitwise>` into the option flags, and the option flags
1145 so augmented are passed to the :class:`DocTestRunner` instance created to
1146 run the doctest. If any reporting flags were specified when the
1147 :class:`DocTestCase` instance was constructed, :mod:`doctest`'s
1148 :mod:`unittest` reporting flags are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150 The value of the :mod:`unittest` reporting flags in effect before the function
1151 was called is returned by the function.
1152
Georg Brandl116aa622007-08-15 14:28:22 +00001153
1154.. _doctest-advanced-api:
1155
1156Advanced API
1157------------
1158
1159The basic API is a simple wrapper that's intended to make doctest easy to use.
1160It is fairly flexible, and should meet most users' needs; however, if you
1161require more fine-grained control over testing, or wish to extend doctest's
1162capabilities, then you should use the advanced API.
1163
1164The advanced API revolves around two container classes, which are used to store
1165the interactive examples extracted from doctest cases:
1166
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001167* :class:`Example`: A single Python :term:`statement`, paired with its expected
Christian Heimesd8654cf2007-12-02 15:22:16 +00001168 output.
Georg Brandl116aa622007-08-15 14:28:22 +00001169
1170* :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted
1171 from a single docstring or text file.
1172
1173Additional processing classes are defined to find, parse, and run, and check
1174doctest examples:
1175
1176* :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a
1177 :class:`DocTestParser` to create a :class:`DocTest` from every docstring that
1178 contains interactive examples.
1179
1180* :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such
1181 as an object's docstring).
1182
1183* :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses
1184 an :class:`OutputChecker` to verify their output.
1185
1186* :class:`OutputChecker`: Compares the actual output from a doctest example with
1187 the expected output, and decides whether they match.
1188
1189The relationships among these processing classes are summarized in the following
1190diagram::
1191
1192 list of:
1193 +------+ +---------+
1194 |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1195 +------+ | ^ +---------+ | ^ (printed)
1196 | | | Example | | |
1197 v | | ... | v |
1198 DocTestParser | Example | OutputChecker
1199 +---------+
1200
1201
1202.. _doctest-doctest:
1203
1204DocTest Objects
1205^^^^^^^^^^^^^^^
1206
1207
1208.. class:: DocTest(examples, globs, name, filename, lineno, docstring)
1209
1210 A collection of doctest examples that should be run in a single namespace. The
Senthil Kumarana6bac952011-07-04 11:28:30 -07001211 constructor arguments are used to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001212
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Senthil Kumarana6bac952011-07-04 11:28:30 -07001214 :class:`DocTest` defines the following attributes. They are initialized by
Benjamin Petersone41251e2008-04-25 01:59:09 +00001215 the constructor, and should not be modified directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217
Benjamin Petersone41251e2008-04-25 01:59:09 +00001218 .. attribute:: examples
Georg Brandl116aa622007-08-15 14:28:22 +00001219
Benjamin Petersone41251e2008-04-25 01:59:09 +00001220 A list of :class:`Example` objects encoding the individual interactive Python
1221 examples that should be run by this test.
Georg Brandl116aa622007-08-15 14:28:22 +00001222
1223
Benjamin Petersone41251e2008-04-25 01:59:09 +00001224 .. attribute:: globs
Georg Brandl116aa622007-08-15 14:28:22 +00001225
Benjamin Petersone41251e2008-04-25 01:59:09 +00001226 The namespace (aka globals) that the examples should be run in. This is a
1227 dictionary mapping names to values. Any changes to the namespace made by the
1228 examples (such as binding new variables) will be reflected in :attr:`globs`
1229 after the test is run.
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231
Benjamin Petersone41251e2008-04-25 01:59:09 +00001232 .. attribute:: name
Georg Brandl116aa622007-08-15 14:28:22 +00001233
Benjamin Petersone41251e2008-04-25 01:59:09 +00001234 A string name identifying the :class:`DocTest`. Typically, this is the name
1235 of the object or file that the test was extracted from.
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237
Benjamin Petersone41251e2008-04-25 01:59:09 +00001238 .. attribute:: filename
Georg Brandl116aa622007-08-15 14:28:22 +00001239
Benjamin Petersone41251e2008-04-25 01:59:09 +00001240 The name of the file that this :class:`DocTest` was extracted from; or
1241 ``None`` if the filename is unknown, or if the :class:`DocTest` was not
1242 extracted from a file.
Georg Brandl116aa622007-08-15 14:28:22 +00001243
1244
Benjamin Petersone41251e2008-04-25 01:59:09 +00001245 .. attribute:: lineno
Georg Brandl116aa622007-08-15 14:28:22 +00001246
Benjamin Petersone41251e2008-04-25 01:59:09 +00001247 The line number within :attr:`filename` where this :class:`DocTest` begins, or
1248 ``None`` if the line number is unavailable. This line number is zero-based
1249 with respect to the beginning of the file.
Georg Brandl116aa622007-08-15 14:28:22 +00001250
1251
Benjamin Petersone41251e2008-04-25 01:59:09 +00001252 .. attribute:: docstring
Georg Brandl116aa622007-08-15 14:28:22 +00001253
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001254 The string that the test was extracted from, or ``None`` if the string is
Benjamin Petersone41251e2008-04-25 01:59:09 +00001255 unavailable, or if the test was not extracted from a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001256
1257
1258.. _doctest-example:
1259
1260Example Objects
1261^^^^^^^^^^^^^^^
1262
1263
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001264.. class:: Example(source, want, exc_msg=None, lineno=0, indent=0, options=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001265
1266 A single interactive example, consisting of a Python statement and its expected
Senthil Kumarana6bac952011-07-04 11:28:30 -07001267 output. The constructor arguments are used to initialize the attributes of
1268 the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001269
Georg Brandl116aa622007-08-15 14:28:22 +00001270
Senthil Kumarana6bac952011-07-04 11:28:30 -07001271 :class:`Example` defines the following attributes. They are initialized by
Benjamin Petersone41251e2008-04-25 01:59:09 +00001272 the constructor, and should not be modified directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001273
1274
Benjamin Petersone41251e2008-04-25 01:59:09 +00001275 .. attribute:: source
Georg Brandl116aa622007-08-15 14:28:22 +00001276
Benjamin Petersone41251e2008-04-25 01:59:09 +00001277 A string containing the example's source code. This source code consists of a
1278 single Python statement, and always ends with a newline; the constructor adds
1279 a newline when necessary.
Georg Brandl116aa622007-08-15 14:28:22 +00001280
1281
Benjamin Petersone41251e2008-04-25 01:59:09 +00001282 .. attribute:: want
Georg Brandl116aa622007-08-15 14:28:22 +00001283
Benjamin Petersone41251e2008-04-25 01:59:09 +00001284 The expected output from running the example's source code (either from
1285 stdout, or a traceback in case of exception). :attr:`want` ends with a
1286 newline unless no output is expected, in which case it's an empty string. The
1287 constructor adds a newline when necessary.
Georg Brandl116aa622007-08-15 14:28:22 +00001288
1289
Benjamin Petersone41251e2008-04-25 01:59:09 +00001290 .. attribute:: exc_msg
Georg Brandl116aa622007-08-15 14:28:22 +00001291
Benjamin Petersone41251e2008-04-25 01:59:09 +00001292 The exception message generated by the example, if the example is expected to
1293 generate an exception; or ``None`` if it is not expected to generate an
1294 exception. This exception message is compared against the return value of
1295 :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline
1296 unless it's ``None``. The constructor adds a newline if needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001297
1298
Benjamin Petersone41251e2008-04-25 01:59:09 +00001299 .. attribute:: lineno
Georg Brandl116aa622007-08-15 14:28:22 +00001300
Benjamin Petersone41251e2008-04-25 01:59:09 +00001301 The line number within the string containing this example where the example
1302 begins. This line number is zero-based with respect to the beginning of the
1303 containing string.
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305
Benjamin Petersone41251e2008-04-25 01:59:09 +00001306 .. attribute:: indent
Georg Brandl116aa622007-08-15 14:28:22 +00001307
Benjamin Petersone41251e2008-04-25 01:59:09 +00001308 The example's indentation in the containing string, i.e., the number of space
1309 characters that precede the example's first prompt.
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311
Benjamin Petersone41251e2008-04-25 01:59:09 +00001312 .. attribute:: options
Georg Brandl116aa622007-08-15 14:28:22 +00001313
Benjamin Petersone41251e2008-04-25 01:59:09 +00001314 A dictionary mapping from option flags to ``True`` or ``False``, which is used
1315 to override default options for this example. Any option flags not contained
1316 in this dictionary are left at their default value (as specified by the
1317 :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
Georg Brandl116aa622007-08-15 14:28:22 +00001318
1319
1320.. _doctest-doctestfinder:
1321
1322DocTestFinder objects
1323^^^^^^^^^^^^^^^^^^^^^
1324
1325
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001326.. class:: DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328 A processing class used to extract the :class:`DocTest`\ s that are relevant to
1329 a given object, from its docstring and the docstrings of its contained objects.
Zachary Warea4b7a752013-11-24 01:19:09 -06001330 :class:`DocTest`\ s can be extracted from modules, classes, functions,
1331 methods, staticmethods, classmethods, and properties.
Georg Brandl116aa622007-08-15 14:28:22 +00001332
1333 The optional argument *verbose* can be used to display the objects searched by
1334 the finder. It defaults to ``False`` (no output).
1335
1336 The optional argument *parser* specifies the :class:`DocTestParser` object (or a
1337 drop-in replacement) that is used to extract doctests from docstrings.
1338
1339 If the optional argument *recurse* is false, then :meth:`DocTestFinder.find`
1340 will only examine the given object, and not any contained objects.
1341
1342 If the optional argument *exclude_empty* is false, then
1343 :meth:`DocTestFinder.find` will include tests for objects with empty docstrings.
1344
Georg Brandl116aa622007-08-15 14:28:22 +00001345
Benjamin Petersone41251e2008-04-25 01:59:09 +00001346 :class:`DocTestFinder` defines the following method:
Georg Brandl116aa622007-08-15 14:28:22 +00001347
1348
Benjamin Petersone41251e2008-04-25 01:59:09 +00001349 .. method:: find(obj[, name][, module][, globs][, extraglobs])
Georg Brandl116aa622007-08-15 14:28:22 +00001350
Benjamin Petersone41251e2008-04-25 01:59:09 +00001351 Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
1352 docstring, or by any of its contained objects' docstrings.
Georg Brandl116aa622007-08-15 14:28:22 +00001353
Benjamin Petersone41251e2008-04-25 01:59:09 +00001354 The optional argument *name* specifies the object's name; this name will be
1355 used to construct names for the returned :class:`DocTest`\ s. If *name* is
1356 not specified, then ``obj.__name__`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001357
Benjamin Petersone41251e2008-04-25 01:59:09 +00001358 The optional parameter *module* is the module that contains the given object.
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001359 If the module is not specified or is ``None``, then the test finder will attempt
Benjamin Petersone41251e2008-04-25 01:59:09 +00001360 to automatically determine the correct module. The object's module is used:
Georg Brandl116aa622007-08-15 14:28:22 +00001361
Benjamin Petersone41251e2008-04-25 01:59:09 +00001362 * As a default namespace, if *globs* is not specified.
Georg Brandl116aa622007-08-15 14:28:22 +00001363
Benjamin Petersone41251e2008-04-25 01:59:09 +00001364 * To prevent the DocTestFinder from extracting DocTests from objects that are
1365 imported from other modules. (Contained objects with modules other than
1366 *module* are ignored.)
Georg Brandl116aa622007-08-15 14:28:22 +00001367
Benjamin Petersone41251e2008-04-25 01:59:09 +00001368 * To find the name of the file containing the object.
Georg Brandl116aa622007-08-15 14:28:22 +00001369
Benjamin Petersone41251e2008-04-25 01:59:09 +00001370 * To help find the line number of the object within its file.
Georg Brandl116aa622007-08-15 14:28:22 +00001371
Benjamin Petersone41251e2008-04-25 01:59:09 +00001372 If *module* is ``False``, no attempt to find the module will be made. This is
1373 obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
1374 is ``None`` but cannot be found automatically, then all objects are considered
1375 to belong to the (non-existent) module, so all contained objects will
1376 (recursively) be searched for doctests.
Georg Brandl116aa622007-08-15 14:28:22 +00001377
Benjamin Petersone41251e2008-04-25 01:59:09 +00001378 The globals for each :class:`DocTest` is formed by combining *globs* and
1379 *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
1380 shallow copy of the globals dictionary is created for each :class:`DocTest`.
1381 If *globs* is not specified, then it defaults to the module's *__dict__*, if
1382 specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
1383 defaults to ``{}``.
Georg Brandl116aa622007-08-15 14:28:22 +00001384
1385
1386.. _doctest-doctestparser:
1387
1388DocTestParser objects
1389^^^^^^^^^^^^^^^^^^^^^
1390
1391
1392.. class:: DocTestParser()
1393
1394 A processing class used to extract interactive examples from a string, and use
1395 them to create a :class:`DocTest` object.
1396
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Benjamin Petersone41251e2008-04-25 01:59:09 +00001398 :class:`DocTestParser` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400
Benjamin Petersone41251e2008-04-25 01:59:09 +00001401 .. method:: get_doctest(string, globs, name, filename, lineno)
Georg Brandl116aa622007-08-15 14:28:22 +00001402
Benjamin Petersone41251e2008-04-25 01:59:09 +00001403 Extract all doctest examples from the given string, and collect them into a
1404 :class:`DocTest` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001405
Benjamin Petersone41251e2008-04-25 01:59:09 +00001406 *globs*, *name*, *filename*, and *lineno* are attributes for the new
1407 :class:`DocTest` object. See the documentation for :class:`DocTest` for more
1408 information.
Georg Brandl116aa622007-08-15 14:28:22 +00001409
1410
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001411 .. method:: get_examples(string, name='<string>')
Georg Brandl116aa622007-08-15 14:28:22 +00001412
Benjamin Petersone41251e2008-04-25 01:59:09 +00001413 Extract all doctest examples from the given string, and return them as a list
1414 of :class:`Example` objects. Line numbers are 0-based. The optional argument
1415 *name* is a name identifying this string, and is only used for error messages.
Georg Brandl116aa622007-08-15 14:28:22 +00001416
1417
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001418 .. method:: parse(string, name='<string>')
Georg Brandl116aa622007-08-15 14:28:22 +00001419
Benjamin Petersone41251e2008-04-25 01:59:09 +00001420 Divide the given string into examples and intervening text, and return them as
1421 a list of alternating :class:`Example`\ s and strings. Line numbers for the
1422 :class:`Example`\ s are 0-based. The optional argument *name* is a name
1423 identifying this string, and is only used for error messages.
Georg Brandl116aa622007-08-15 14:28:22 +00001424
1425
1426.. _doctest-doctestrunner:
1427
1428DocTestRunner objects
1429^^^^^^^^^^^^^^^^^^^^^
1430
1431
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001432.. class:: DocTestRunner(checker=None, verbose=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434 A processing class used to execute and verify the interactive examples in a
1435 :class:`DocTest`.
1436
1437 The comparison between expected outputs and actual outputs is done by an
1438 :class:`OutputChecker`. This comparison may be customized with a number of
1439 option flags; see section :ref:`doctest-options` for more information. If the
1440 option flags are insufficient, then the comparison may also be customized by
1441 passing a subclass of :class:`OutputChecker` to the constructor.
1442
1443 The test runner's display output can be controlled in two ways. First, an output
1444 function can be passed to :meth:`TestRunner.run`; this function will be called
1445 with strings that should be displayed. It defaults to ``sys.stdout.write``. If
1446 capturing the output is not sufficient, then the display output can be also
1447 customized by subclassing DocTestRunner, and overriding the methods
1448 :meth:`report_start`, :meth:`report_success`,
1449 :meth:`report_unexpected_exception`, and :meth:`report_failure`.
1450
1451 The optional keyword argument *checker* specifies the :class:`OutputChecker`
1452 object (or drop-in replacement) that should be used to compare the expected
1453 outputs to the actual outputs of doctest examples.
1454
1455 The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s
1456 verbosity. If *verbose* is ``True``, then information is printed about each
1457 example, as it is run. If *verbose* is ``False``, then only failures are
1458 printed. If *verbose* is unspecified, or ``None``, then verbose output is used
Éric Araujo713d3032010-11-18 16:38:46 +00001459 iff the command-line switch ``-v`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001460
1461 The optional keyword argument *optionflags* can be used to control how the test
1462 runner compares expected output to actual output, and how it displays failures.
1463 For more information, see section :ref:`doctest-options`.
1464
Georg Brandl116aa622007-08-15 14:28:22 +00001465
Benjamin Petersone41251e2008-04-25 01:59:09 +00001466 :class:`DocTestParser` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001467
1468
Benjamin Petersone41251e2008-04-25 01:59:09 +00001469 .. method:: report_start(out, test, example)
Georg Brandl116aa622007-08-15 14:28:22 +00001470
Benjamin Petersone41251e2008-04-25 01:59:09 +00001471 Report that the test runner is about to process the given example. This method
1472 is provided to allow subclasses of :class:`DocTestRunner` to customize their
1473 output; it should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001474
Benjamin Petersone41251e2008-04-25 01:59:09 +00001475 *example* is the example about to be processed. *test* is the test
1476 *containing example*. *out* is the output function that was passed to
1477 :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001478
1479
Benjamin Petersone41251e2008-04-25 01:59:09 +00001480 .. method:: report_success(out, test, example, got)
Georg Brandl116aa622007-08-15 14:28:22 +00001481
Benjamin Petersone41251e2008-04-25 01:59:09 +00001482 Report that the given example ran successfully. This method is provided to
1483 allow subclasses of :class:`DocTestRunner` to customize their output; it
1484 should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001485
Benjamin Petersone41251e2008-04-25 01:59:09 +00001486 *example* is the example about to be processed. *got* is the actual output
1487 from the example. *test* is the test containing *example*. *out* is the
1488 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001489
1490
Benjamin Petersone41251e2008-04-25 01:59:09 +00001491 .. method:: report_failure(out, test, example, got)
Georg Brandl116aa622007-08-15 14:28:22 +00001492
Benjamin Petersone41251e2008-04-25 01:59:09 +00001493 Report that the given example failed. This method is provided to allow
1494 subclasses of :class:`DocTestRunner` to customize their output; it should not
1495 be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001496
Benjamin Petersone41251e2008-04-25 01:59:09 +00001497 *example* is the example about to be processed. *got* is the actual output
1498 from the example. *test* is the test containing *example*. *out* is the
1499 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001500
1501
Benjamin Petersone41251e2008-04-25 01:59:09 +00001502 .. method:: report_unexpected_exception(out, test, example, exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00001503
Benjamin Petersone41251e2008-04-25 01:59:09 +00001504 Report that the given example raised an unexpected exception. This method is
1505 provided to allow subclasses of :class:`DocTestRunner` to customize their
1506 output; it should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Benjamin Petersone41251e2008-04-25 01:59:09 +00001508 *example* is the example about to be processed. *exc_info* is a tuple
1509 containing information about the unexpected exception (as returned by
1510 :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
1511 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001512
1513
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001514 .. method:: run(test, compileflags=None, out=None, clear_globs=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001515
Benjamin Petersone41251e2008-04-25 01:59:09 +00001516 Run the examples in *test* (a :class:`DocTest` object), and display the
1517 results using the writer function *out*.
Georg Brandl116aa622007-08-15 14:28:22 +00001518
Benjamin Petersone41251e2008-04-25 01:59:09 +00001519 The examples are run in the namespace ``test.globs``. If *clear_globs* is
1520 true (the default), then this namespace will be cleared after the test runs,
1521 to help with garbage collection. If you would like to examine the namespace
1522 after the test completes, then use *clear_globs=False*.
Georg Brandl116aa622007-08-15 14:28:22 +00001523
Benjamin Petersone41251e2008-04-25 01:59:09 +00001524 *compileflags* gives the set of flags that should be used by the Python
1525 compiler when running the examples. If not specified, then it will default to
1526 the set of future-import flags that apply to *globs*.
Georg Brandl116aa622007-08-15 14:28:22 +00001527
Benjamin Petersone41251e2008-04-25 01:59:09 +00001528 The output of each example is checked using the :class:`DocTestRunner`'s
1529 output checker, and the results are formatted by the
1530 :meth:`DocTestRunner.report_\*` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001531
1532
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001533 .. method:: summarize(verbose=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001534
Benjamin Petersone41251e2008-04-25 01:59:09 +00001535 Print a summary of all the test cases that have been run by this DocTestRunner,
1536 and return a :term:`named tuple` ``TestResults(failed, attempted)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001537
Benjamin Petersone41251e2008-04-25 01:59:09 +00001538 The optional *verbose* argument controls how detailed the summary is. If the
1539 verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
1540 used.
Georg Brandl116aa622007-08-15 14:28:22 +00001541
1542.. _doctest-outputchecker:
1543
1544OutputChecker objects
1545^^^^^^^^^^^^^^^^^^^^^
1546
1547
1548.. class:: OutputChecker()
1549
1550 A class used to check the whether the actual output from a doctest example
1551 matches the expected output. :class:`OutputChecker` defines two methods:
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001552 :meth:`check_output`, which compares a given pair of outputs, and returns ``True``
Georg Brandl116aa622007-08-15 14:28:22 +00001553 if they match; and :meth:`output_difference`, which returns a string describing
1554 the differences between two outputs.
1555
Georg Brandl116aa622007-08-15 14:28:22 +00001556
Benjamin Petersone41251e2008-04-25 01:59:09 +00001557 :class:`OutputChecker` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001558
Benjamin Petersone41251e2008-04-25 01:59:09 +00001559 .. method:: check_output(want, got, optionflags)
Georg Brandl116aa622007-08-15 14:28:22 +00001560
Benjamin Petersone41251e2008-04-25 01:59:09 +00001561 Return ``True`` iff the actual output from an example (*got*) matches the
1562 expected output (*want*). These strings are always considered to match if
1563 they are identical; but depending on what option flags the test runner is
1564 using, several non-exact match types are also possible. See section
1565 :ref:`doctest-options` for more information about option flags.
Georg Brandl116aa622007-08-15 14:28:22 +00001566
1567
Benjamin Petersone41251e2008-04-25 01:59:09 +00001568 .. method:: output_difference(example, got, optionflags)
Georg Brandl116aa622007-08-15 14:28:22 +00001569
Benjamin Petersone41251e2008-04-25 01:59:09 +00001570 Return a string describing the differences between the expected output for a
1571 given example (*example*) and the actual output (*got*). *optionflags* is the
1572 set of option flags used to compare *want* and *got*.
Georg Brandl116aa622007-08-15 14:28:22 +00001573
1574
1575.. _doctest-debugging:
1576
1577Debugging
1578---------
1579
1580Doctest provides several mechanisms for debugging doctest examples:
1581
1582* Several functions convert doctests to executable Python programs, which can be
1583 run under the Python debugger, :mod:`pdb`.
1584
1585* The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that
1586 raises an exception for the first failing example, containing information about
1587 that example. This information can be used to perform post-mortem debugging on
1588 the example.
1589
1590* The :mod:`unittest` cases generated by :func:`DocTestSuite` support the
1591 :meth:`debug` method defined by :class:`unittest.TestCase`.
1592
1593* You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll
1594 drop into the Python debugger when that line is executed. Then you can inspect
1595 current values of variables, and so on. For example, suppose :file:`a.py`
1596 contains just this module docstring::
1597
1598 """
1599 >>> def f(x):
1600 ... g(x*2)
1601 >>> def g(x):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001602 ... print(x+3)
Georg Brandl116aa622007-08-15 14:28:22 +00001603 ... import pdb; pdb.set_trace()
1604 >>> f(3)
1605 9
1606 """
1607
1608 Then an interactive Python session may look like this::
1609
1610 >>> import a, doctest
1611 >>> doctest.testmod(a)
1612 --Return--
1613 > <doctest a[1]>(3)g()->None
1614 -> import pdb; pdb.set_trace()
1615 (Pdb) list
1616 1 def g(x):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001617 2 print(x+3)
Georg Brandl116aa622007-08-15 14:28:22 +00001618 3 -> import pdb; pdb.set_trace()
1619 [EOF]
Georg Brandl6911e3c2007-09-04 07:15:32 +00001620 (Pdb) p x
Georg Brandl116aa622007-08-15 14:28:22 +00001621 6
1622 (Pdb) step
1623 --Return--
1624 > <doctest a[0]>(2)f()->None
1625 -> g(x*2)
1626 (Pdb) list
1627 1 def f(x):
1628 2 -> g(x*2)
1629 [EOF]
Georg Brandl6911e3c2007-09-04 07:15:32 +00001630 (Pdb) p x
Georg Brandl116aa622007-08-15 14:28:22 +00001631 3
1632 (Pdb) step
1633 --Return--
1634 > <doctest a[2]>(1)?()->None
1635 -> f(3)
1636 (Pdb) cont
1637 (0, 3)
1638 >>>
1639
Georg Brandl116aa622007-08-15 14:28:22 +00001640
1641Functions that convert doctests to Python code, and possibly run the synthesized
1642code under the debugger:
1643
1644
1645.. function:: script_from_examples(s)
1646
1647 Convert text with examples to a script.
1648
1649 Argument *s* is a string containing doctest examples. The string is converted
1650 to a Python script, where doctest examples in *s* are converted to regular code,
1651 and everything else is converted to Python comments. The generated script is
1652 returned as a string. For example, ::
1653
1654 import doctest
Georg Brandl6911e3c2007-09-04 07:15:32 +00001655 print(doctest.script_from_examples(r"""
Georg Brandl116aa622007-08-15 14:28:22 +00001656 Set x and y to 1 and 2.
1657 >>> x, y = 1, 2
1658
1659 Print their sum:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001660 >>> print(x+y)
Georg Brandl116aa622007-08-15 14:28:22 +00001661 3
Georg Brandl6911e3c2007-09-04 07:15:32 +00001662 """))
Georg Brandl116aa622007-08-15 14:28:22 +00001663
1664 displays::
1665
1666 # Set x and y to 1 and 2.
1667 x, y = 1, 2
1668 #
1669 # Print their sum:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001670 print(x+y)
Georg Brandl116aa622007-08-15 14:28:22 +00001671 # Expected:
1672 ## 3
1673
1674 This function is used internally by other functions (see below), but can also be
1675 useful when you want to transform an interactive Python session into a Python
1676 script.
1677
Georg Brandl116aa622007-08-15 14:28:22 +00001678
1679.. function:: testsource(module, name)
1680
1681 Convert the doctest for an object to a script.
1682
1683 Argument *module* is a module object, or dotted name of a module, containing the
1684 object whose doctests are of interest. Argument *name* is the name (within the
1685 module) of the object with the doctests of interest. The result is a string,
1686 containing the object's docstring converted to a Python script, as described for
1687 :func:`script_from_examples` above. For example, if module :file:`a.py`
1688 contains a top-level function :func:`f`, then ::
1689
1690 import a, doctest
Georg Brandl6911e3c2007-09-04 07:15:32 +00001691 print(doctest.testsource(a, "a.f"))
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693 prints a script version of function :func:`f`'s docstring, with doctests
1694 converted to code, and the rest placed in comments.
1695
Georg Brandl116aa622007-08-15 14:28:22 +00001696
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001697.. function:: debug(module, name, pm=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001698
1699 Debug the doctests for an object.
1700
1701 The *module* and *name* arguments are the same as for function
1702 :func:`testsource` above. The synthesized Python script for the named object's
1703 docstring is written to a temporary file, and then that file is run under the
1704 control of the Python debugger, :mod:`pdb`.
1705
1706 A shallow copy of ``module.__dict__`` is used for both local and global
1707 execution context.
1708
1709 Optional argument *pm* controls whether post-mortem debugging is used. If *pm*
1710 has a true value, the script file is run directly, and the debugger gets
1711 involved only if the script terminates via raising an unhandled exception. If
1712 it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`,
1713 passing the traceback object from the unhandled exception. If *pm* is not
1714 specified, or is false, the script is run under the debugger from the start, via
1715 passing an appropriate :func:`exec` call to :func:`pdb.run`.
1716
Georg Brandl116aa622007-08-15 14:28:22 +00001717
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001718.. function:: debug_src(src, pm=False, globs=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001719
1720 Debug the doctests in a string.
1721
1722 This is like function :func:`debug` above, except that a string containing
1723 doctest examples is specified directly, via the *src* argument.
1724
1725 Optional argument *pm* has the same meaning as in function :func:`debug` above.
1726
1727 Optional argument *globs* gives a dictionary to use as both local and global
1728 execution context. If not specified, or ``None``, an empty dictionary is used.
1729 If specified, a shallow copy of the dictionary is used.
1730
Georg Brandl116aa622007-08-15 14:28:22 +00001731
1732The :class:`DebugRunner` class, and the special exceptions it may raise, are of
1733most interest to testing framework authors, and will only be sketched here. See
1734the source code, and especially :class:`DebugRunner`'s docstring (which is a
1735doctest!) for more details:
1736
1737
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001738.. class:: DebugRunner(checker=None, verbose=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001739
1740 A subclass of :class:`DocTestRunner` that raises an exception as soon as a
1741 failure is encountered. If an unexpected exception occurs, an
1742 :exc:`UnexpectedException` exception is raised, containing the test, the
1743 example, and the original exception. If the output doesn't match, then a
1744 :exc:`DocTestFailure` exception is raised, containing the test, the example, and
1745 the actual output.
1746
1747 For information about the constructor parameters and methods, see the
1748 documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`.
1749
1750There are two exceptions that may be raised by :class:`DebugRunner` instances:
1751
1752
1753.. exception:: DocTestFailure(test, example, got)
1754
Georg Brandl7cb13192010-08-03 12:06:29 +00001755 An exception raised by :class:`DocTestRunner` to signal that a doctest example's
Georg Brandl116aa622007-08-15 14:28:22 +00001756 actual output did not match its expected output. The constructor arguments are
Senthil Kumarana6bac952011-07-04 11:28:30 -07001757 used to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001758
Senthil Kumarana6bac952011-07-04 11:28:30 -07001759:exc:`DocTestFailure` defines the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001760
1761
1762.. attribute:: DocTestFailure.test
1763
1764 The :class:`DocTest` object that was being run when the example failed.
1765
1766
1767.. attribute:: DocTestFailure.example
1768
1769 The :class:`Example` that failed.
1770
1771
1772.. attribute:: DocTestFailure.got
1773
1774 The example's actual output.
1775
1776
1777.. exception:: UnexpectedException(test, example, exc_info)
1778
Georg Brandl7cb13192010-08-03 12:06:29 +00001779 An exception raised by :class:`DocTestRunner` to signal that a doctest
1780 example raised an unexpected exception. The constructor arguments are used
Senthil Kumarana6bac952011-07-04 11:28:30 -07001781 to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001782
Senthil Kumarana6bac952011-07-04 11:28:30 -07001783:exc:`UnexpectedException` defines the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001784
1785
1786.. attribute:: UnexpectedException.test
1787
1788 The :class:`DocTest` object that was being run when the example failed.
1789
1790
1791.. attribute:: UnexpectedException.example
1792
1793 The :class:`Example` that failed.
1794
1795
1796.. attribute:: UnexpectedException.exc_info
1797
1798 A tuple containing information about the unexpected exception, as returned by
1799 :func:`sys.exc_info`.
1800
1801
1802.. _doctest-soapbox:
1803
1804Soapbox
1805-------
1806
1807As mentioned in the introduction, :mod:`doctest` has grown to have three primary
1808uses:
1809
1810#. Checking examples in docstrings.
1811
1812#. Regression testing.
1813
1814#. Executable documentation / literate testing.
1815
1816These uses have different requirements, and it is important to distinguish them.
1817In particular, filling your docstrings with obscure test cases makes for bad
1818documentation.
1819
1820When writing a docstring, choose docstring examples with care. There's an art to
1821this that needs to be learned---it may not be natural at first. Examples should
1822add genuine value to the documentation. A good example can often be worth many
1823words. If done with care, the examples will be invaluable for your users, and
1824will pay back the time it takes to collect them many times over as the years go
1825by and things change. I'm still amazed at how often one of my :mod:`doctest`
1826examples stops working after a "harmless" change.
1827
1828Doctest also makes an excellent tool for regression testing, especially if you
1829don't skimp on explanatory text. By interleaving prose and examples, it becomes
1830much easier to keep track of what's actually being tested, and why. When a test
1831fails, good prose can make it much easier to figure out what the problem is, and
1832how it should be fixed. It's true that you could write extensive comments in
1833code-based testing, but few programmers do. Many have found that using doctest
1834approaches instead leads to much clearer tests. Perhaps this is simply because
1835doctest makes writing prose a little easier than writing code, while writing
1836comments in code is a little harder. I think it goes deeper than just that:
1837the natural attitude when writing a doctest-based test is that you want to
1838explain the fine points of your software, and illustrate them with examples.
1839This in turn naturally leads to test files that start with the simplest
1840features, and logically progress to complications and edge cases. A coherent
1841narrative is the result, instead of a collection of isolated functions that test
1842isolated bits of functionality seemingly at random. It's a different attitude,
1843and produces different results, blurring the distinction between testing and
1844explaining.
1845
1846Regression testing is best confined to dedicated objects or files. There are
1847several options for organizing tests:
1848
1849* Write text files containing test cases as interactive examples, and test the
1850 files using :func:`testfile` or :func:`DocFileSuite`. This is recommended,
1851 although is easiest to do for new projects, designed from the start to use
1852 doctest.
1853
1854* Define functions named ``_regrtest_topic`` that consist of single docstrings,
1855 containing test cases for the named topics. These functions can be included in
1856 the same file as the module, or separated out into a separate test file.
1857
1858* Define a ``__test__`` dictionary mapping from regression test topics to
1859 docstrings containing test cases.
1860
Ethan Furman2a5f9da2015-09-17 22:20:41 -07001861When you have placed your tests in a module, the module can itself be the test
1862runner. When a test fails, you can arrange for your test runner to re-run only
1863the failing doctest while you debug the problem. Here is a minimal example of
1864such a test runner::
1865
1866 if __name__ == '__main__':
1867 import doctest
1868 flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
1869 if len(sys.argv) > 1:
1870 name = sys.argv[1]
1871 if name in globals():
1872 obj = globals()[name]
1873 else:
1874 obj = __test__[name]
1875 doctest.run_docstring_examples(obj, globals(), name=name,
1876 optionflags=flags)
1877 else:
1878 fail, total = doctest.testmod(optionflags=flags)
1879 print("{} failures out of {} tests".format(fail, total))
1880
1881
Georg Brandl116aa622007-08-15 14:28:22 +00001882.. rubric:: Footnotes
1883
1884.. [#] Examples containing both expected output and an exception are not supported.
1885 Trying to guess where one ends and the other begins is too error-prone, and that
1886 also makes for a confusing test.