blob: a77322f83acbdef19d464ba1d196a700f309defb [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
Georg Brandl83e51f42012-10-10 16:45:11 +0200722For example, this test passes::
Nick Coghlan8f80e0a2012-10-03 12:21:44 +0530723
Georg Brandl83e51f42012-10-10 16:45:11 +0200724 >>> print(list(range(20))) # doctest: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000725 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
726 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
727
728Without the directive it would fail, both because the actual output doesn't have
729two blanks before the single-digit list elements, and because the actual output
730is on a single line. This test also passes, and also requires a directive to do
Georg Brandl83e51f42012-10-10 16:45:11 +0200731so::
Georg Brandl116aa622007-08-15 14:28:22 +0000732
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000733 >>> print(list(range(20))) # doctest: +ELLIPSIS
Georg Brandl116aa622007-08-15 14:28:22 +0000734 [0, 1, ..., 18, 19]
735
Nick Coghlan0b26ccf2012-10-03 13:52:48 +0530736Multiple directives can be used on a single physical line, separated by
Georg Brandl83e51f42012-10-10 16:45:11 +0200737commas::
Georg Brandl116aa622007-08-15 14:28:22 +0000738
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000739 >>> print(list(range(20))) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000740 [0, 1, ..., 18, 19]
741
742If multiple directive comments are used for a single example, then they are
Georg Brandl83e51f42012-10-10 16:45:11 +0200743combined::
Georg Brandl116aa622007-08-15 14:28:22 +0000744
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000745 >>> print(list(range(20))) # doctest: +ELLIPSIS
746 ... # doctest: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000747 [0, 1, ..., 18, 19]
748
749As the previous example shows, you can add ``...`` lines to your example
750containing only directives. This can be useful when an example is too long for
Georg Brandl83e51f42012-10-10 16:45:11 +0200751a directive to comfortably fit on the same line::
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000753 >>> print(list(range(5)) + list(range(10, 20)) + list(range(30, 40)))
Georg Brandl116aa622007-08-15 14:28:22 +0000754 ... # doctest: +ELLIPSIS
Georg Brandl8f80a5b2010-03-21 09:25:54 +0000755 [0, ..., 4, 10, ..., 19, 30, ..., 39]
Georg Brandl116aa622007-08-15 14:28:22 +0000756
757Note that since all options are disabled by default, and directives apply only
758to the example they appear in, enabling options (via ``+`` in a directive) is
759usually the only meaningful choice. However, option flags can also be passed to
760functions that run doctests, establishing different defaults. In such cases,
761disabling an option via ``-`` in a directive can be useful.
762
Georg Brandl116aa622007-08-15 14:28:22 +0000763
764.. _doctest-warnings:
765
766Warnings
767^^^^^^^^
768
769:mod:`doctest` is serious about requiring exact matches in expected output. If
770even a single character doesn't match, the test fails. This will probably
771surprise you a few times, as you learn exactly what Python does and doesn't
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200772guarantee about output. For example, when printing a set, Python doesn't
773guarantee that the element is printed in any particular order, so a test like ::
Georg Brandl116aa622007-08-15 14:28:22 +0000774
775 >>> foo()
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200776 {"Hermione", "Harry"}
Georg Brandl116aa622007-08-15 14:28:22 +0000777
778is vulnerable! One workaround is to do ::
779
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200780 >>> foo() == {"Hermione", "Harry"}
Georg Brandl116aa622007-08-15 14:28:22 +0000781 True
782
783instead. Another is to do ::
784
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200785 >>> d = sorted(foo())
Georg Brandl116aa622007-08-15 14:28:22 +0000786 >>> d
Stéphane Wirtel0522fd82018-10-20 10:43:32 +0200787 ['Harry', 'Hermione']
788
789.. note::
790
791 Before Python 3.6, when printing a dict, Python did not guarantee that
792 the key-value pairs was printed in any particular order.
Georg Brandl116aa622007-08-15 14:28:22 +0000793
794There are others, but you get the idea.
795
796Another bad idea is to print things that embed an object address, like ::
797
798 >>> id(1.0) # certain to fail some of the time
799 7948648
800 >>> class C: pass
801 >>> C() # the default repr() for instances embeds an address
802 <__main__.C instance at 0x00AC18F0>
803
Georg Brandl23a87de2012-10-10 16:56:15 +0200804The :const:`ELLIPSIS` directive gives a nice approach for the last example::
Georg Brandl116aa622007-08-15 14:28:22 +0000805
806 >>> C() #doctest: +ELLIPSIS
807 <__main__.C instance at 0x...>
808
809Floating-point numbers are also subject to small output variations across
810platforms, because Python defers to the platform C library for float formatting,
811and C libraries vary widely in quality here. ::
812
813 >>> 1./7 # risky
814 0.14285714285714285
Georg Brandl6911e3c2007-09-04 07:15:32 +0000815 >>> print(1./7) # safer
Georg Brandl116aa622007-08-15 14:28:22 +0000816 0.142857142857
Georg Brandl6911e3c2007-09-04 07:15:32 +0000817 >>> print(round(1./7, 6)) # much safer
Georg Brandl116aa622007-08-15 14:28:22 +0000818 0.142857
819
820Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
821contrive doctest examples to produce numbers of that form::
822
823 >>> 3./4 # utterly safe
824 0.75
825
826Simple fractions are also easier for people to understand, and that makes for
827better documentation.
828
829
830.. _doctest-basic-api:
831
832Basic API
833---------
834
835The functions :func:`testmod` and :func:`testfile` provide a simple interface to
836doctest that should be sufficient for most basic uses. For a less formal
837introduction to these two functions, see sections :ref:`doctest-simple-testmod`
838and :ref:`doctest-simple-testfile`.
839
840
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000841.. 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 +0000842
843 All arguments except *filename* are optional, and should be specified in keyword
844 form.
845
846 Test examples in the file named *filename*. Return ``(failure_count,
847 test_count)``.
848
849 Optional argument *module_relative* specifies how the filename should be
850 interpreted:
851
852 * If *module_relative* is ``True`` (the default), then *filename* specifies an
853 OS-independent module-relative path. By default, this path is relative to the
854 calling module's directory; but if the *package* argument is specified, then it
855 is relative to that package. To ensure OS-independence, *filename* should use
856 ``/`` characters to separate path segments, and may not be an absolute path
857 (i.e., it may not begin with ``/``).
858
859 * If *module_relative* is ``False``, then *filename* specifies an OS-specific
860 path. The path may be absolute or relative; relative paths are resolved with
861 respect to the current working directory.
862
863 Optional argument *name* gives the name of the test; by default, or if ``None``,
864 ``os.path.basename(filename)`` is used.
865
866 Optional argument *package* is a Python package or the name of a Python package
867 whose directory should be used as the base directory for a module-relative
868 filename. If no package is specified, then the calling module's directory is
869 used as the base directory for module-relative filenames. It is an error to
870 specify *package* if *module_relative* is ``False``.
871
872 Optional argument *globs* gives a dict to be used as the globals when executing
873 examples. A new shallow copy of this dict is created for the doctest, so its
874 examples start with a clean slate. By default, or if ``None``, a new empty dict
875 is used.
876
877 Optional argument *extraglobs* gives a dict merged into the globals used to
878 execute examples. This works like :meth:`dict.update`: if *globs* and
879 *extraglobs* have a common key, the associated value in *extraglobs* appears in
880 the combined dict. By default, or if ``None``, no extra globals are used. This
881 is an advanced feature that allows parameterization of doctests. For example, a
882 doctest can be written for a base class, using a generic name for the class,
883 then reused to test any number of subclasses by passing an *extraglobs* dict
884 mapping the generic name to the subclass to be tested.
885
886 Optional argument *verbose* prints lots of stuff if true, and prints only
887 failures if false; by default, or if ``None``, it's true if and only if ``'-v'``
888 is in ``sys.argv``.
889
890 Optional argument *report* prints a summary at the end when true, else prints
891 nothing at the end. In verbose mode, the summary is detailed, else the summary
892 is very brief (in fact, empty if all tests passed).
893
Mariatta Wijaya81b89772017-02-06 20:15:01 -0800894 Optional argument *optionflags* (default value 0) takes the
895 :ref:`bitwise OR <bitwise>` of option flags.
896 See section :ref:`doctest-options`.
Georg Brandl116aa622007-08-15 14:28:22 +0000897
898 Optional argument *raise_on_error* defaults to false. If true, an exception is
899 raised upon the first failure or unexpected exception in an example. This
900 allows failures to be post-mortem debugged. Default behavior is to continue
901 running examples.
902
903 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) that
904 should be used to extract tests from the files. It defaults to a normal parser
905 (i.e., ``DocTestParser()``).
906
907 Optional argument *encoding* specifies an encoding that should be used to
908 convert the file to unicode.
909
Georg Brandl116aa622007-08-15 14:28:22 +0000910
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000911.. 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 +0000912
913 All arguments are optional, and all except for *m* should be specified in
914 keyword form.
915
916 Test examples in docstrings in functions and classes reachable from module *m*
917 (or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with
918 ``m.__doc__``.
919
920 Also test examples reachable from dict ``m.__test__``, if it exists and is not
921 ``None``. ``m.__test__`` maps names (strings) to functions, classes and
922 strings; function and class docstrings are searched for examples; strings are
923 searched directly, as if they were docstrings.
924
925 Only docstrings attached to objects belonging to module *m* are searched.
926
927 Return ``(failure_count, test_count)``.
928
929 Optional argument *name* gives the name of the module; by default, or if
930 ``None``, ``m.__name__`` is used.
931
932 Optional argument *exclude_empty* defaults to false. If true, objects for which
933 no doctests are found are excluded from consideration. The default is a backward
934 compatibility hack, so that code still using :meth:`doctest.master.summarize` in
935 conjunction with :func:`testmod` continues to get output for objects with no
936 tests. The *exclude_empty* argument to the newer :class:`DocTestFinder`
937 constructor defaults to true.
938
939 Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*,
940 *raise_on_error*, and *globs* are the same as for function :func:`testfile`
941 above, except that *globs* defaults to ``m.__dict__``.
942
Georg Brandl116aa622007-08-15 14:28:22 +0000943
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000944.. function:: run_docstring_examples(f, globs, verbose=False, name="NoName", compileflags=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +0000945
Ethan Furman2a5f9da2015-09-17 22:20:41 -0700946 Test examples associated with object *f*; for example, *f* may be a string,
947 a module, a function, or a class object.
Georg Brandl116aa622007-08-15 14:28:22 +0000948
949 A shallow copy of dictionary argument *globs* is used for the execution context.
950
951 Optional argument *name* is used in failure messages, and defaults to
952 ``"NoName"``.
953
954 If optional argument *verbose* is true, output is generated even if there are no
955 failures. By default, output is generated only in case of an example failure.
956
957 Optional argument *compileflags* gives the set of flags that should be used by
958 the Python compiler when running the examples. By default, or if ``None``,
959 flags are deduced corresponding to the set of future features found in *globs*.
960
961 Optional argument *optionflags* works as for function :func:`testfile` above.
962
963
964.. _doctest-unittest-api:
965
966Unittest API
967------------
968
969As your collection of doctest'ed modules grows, you'll want a way to run all
Georg Brandl31835852008-05-12 17:38:56 +0000970their doctests systematically. :mod:`doctest` provides two functions that can
971be used to create :mod:`unittest` test suites from modules and text files
Georg Brandla8514832010-07-10 12:20:38 +0000972containing doctests. To integrate with :mod:`unittest` test discovery, include
973a :func:`load_tests` function in your test module::
Georg Brandl116aa622007-08-15 14:28:22 +0000974
975 import unittest
976 import doctest
Georg Brandla8514832010-07-10 12:20:38 +0000977 import my_module_with_doctests
Georg Brandl116aa622007-08-15 14:28:22 +0000978
Georg Brandla8514832010-07-10 12:20:38 +0000979 def load_tests(loader, tests, ignore):
980 tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
R. David Murray796343b2010-12-13 22:50:30 +0000981 return tests
Georg Brandl116aa622007-08-15 14:28:22 +0000982
983There are two main functions for creating :class:`unittest.TestSuite` instances
984from text files and modules with doctests:
985
986
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000987.. 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 +0000988
989 Convert doctest tests from one or more text files to a
990 :class:`unittest.TestSuite`.
991
992 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
993 and runs the interactive examples in each file. If an example in any file
994 fails, then the synthesized unit test fails, and a :exc:`failureException`
995 exception is raised showing the name of the file containing the test and a
996 (sometimes approximate) line number.
997
998 Pass one or more paths (as strings) to text files to be examined.
999
1000 Options may be provided as keyword arguments:
1001
1002 Optional argument *module_relative* specifies how the filenames in *paths*
1003 should be interpreted:
1004
Benjamin Petersond23f8222009-04-05 19:13:16 +00001005 * If *module_relative* is ``True`` (the default), then each filename in
1006 *paths* specifies an OS-independent module-relative path. By default, this
1007 path is relative to the calling module's directory; but if the *package*
1008 argument is specified, then it is relative to that package. To ensure
1009 OS-independence, each filename should use ``/`` characters to separate path
1010 segments, and may not be an absolute path (i.e., it may not begin with
1011 ``/``).
Georg Brandl116aa622007-08-15 14:28:22 +00001012
Benjamin Petersond23f8222009-04-05 19:13:16 +00001013 * If *module_relative* is ``False``, then each filename in *paths* specifies
1014 an OS-specific path. The path may be absolute or relative; relative paths
1015 are resolved with respect to the current working directory.
Georg Brandl116aa622007-08-15 14:28:22 +00001016
Benjamin Petersond23f8222009-04-05 19:13:16 +00001017 Optional argument *package* is a Python package or the name of a Python
1018 package whose directory should be used as the base directory for
1019 module-relative filenames in *paths*. If no package is specified, then the
1020 calling module's directory is used as the base directory for module-relative
1021 filenames. It is an error to specify *package* if *module_relative* is
1022 ``False``.
Georg Brandl116aa622007-08-15 14:28:22 +00001023
Benjamin Petersond23f8222009-04-05 19:13:16 +00001024 Optional argument *setUp* specifies a set-up function for the test suite.
1025 This is called before running the tests in each file. The *setUp* function
Georg Brandl116aa622007-08-15 14:28:22 +00001026 will be passed a :class:`DocTest` object. The setUp function can access the
1027 test globals as the *globs* attribute of the test passed.
1028
Benjamin Petersond23f8222009-04-05 19:13:16 +00001029 Optional argument *tearDown* specifies a tear-down function for the test
1030 suite. This is called after running the tests in each file. The *tearDown*
1031 function will be passed a :class:`DocTest` object. The setUp function can
1032 access the test globals as the *globs* attribute of the test passed.
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034 Optional argument *globs* is a dictionary containing the initial global
1035 variables for the tests. A new copy of this dictionary is created for each
1036 test. By default, *globs* is a new empty dictionary.
1037
1038 Optional argument *optionflags* specifies the default doctest options for the
1039 tests, created by or-ing together individual option flags. See section
Benjamin Petersond23f8222009-04-05 19:13:16 +00001040 :ref:`doctest-options`. See function :func:`set_unittest_reportflags` below
1041 for a better way to set reporting options.
Georg Brandl116aa622007-08-15 14:28:22 +00001042
Benjamin Petersond23f8222009-04-05 19:13:16 +00001043 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass)
1044 that should be used to extract tests from the files. It defaults to a normal
1045 parser (i.e., ``DocTestParser()``).
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047 Optional argument *encoding* specifies an encoding that should be used to
1048 convert the file to unicode.
1049
Georg Brandl55ac8f02007-09-01 13:51:09 +00001050 The global ``__file__`` is added to the globals provided to doctests loaded
1051 from a text file using :func:`DocFileSuite`.
Georg Brandl116aa622007-08-15 14:28:22 +00001052
1053
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001054.. function:: DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, setUp=None, tearDown=None, checker=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001055
1056 Convert doctest tests for a module to a :class:`unittest.TestSuite`.
1057
1058 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
1059 and runs each doctest in the module. If any of the doctests fail, then the
1060 synthesized unit test fails, and a :exc:`failureException` exception is raised
1061 showing the name of the file containing the test and a (sometimes approximate)
1062 line number.
1063
1064 Optional argument *module* provides the module to be tested. It can be a module
1065 object or a (possibly dotted) module name. If not specified, the module calling
1066 this function is used.
1067
1068 Optional argument *globs* is a dictionary containing the initial global
1069 variables for the tests. A new copy of this dictionary is created for each
1070 test. By default, *globs* is a new empty dictionary.
1071
1072 Optional argument *extraglobs* specifies an extra set of global variables, which
1073 is merged into *globs*. By default, no extra globals are used.
1074
1075 Optional argument *test_finder* is the :class:`DocTestFinder` object (or a
1076 drop-in replacement) that is used to extract doctests from the module.
1077
1078 Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for
1079 function :func:`DocFileSuite` above.
1080
Georg Brandl55ac8f02007-09-01 13:51:09 +00001081 This function uses the same search technique as :func:`testmod`.
Georg Brandl116aa622007-08-15 14:28:22 +00001082
R David Murray1976d9b2014-04-14 20:28:36 -04001083 .. versionchanged:: 3.5
1084 :func:`DocTestSuite` returns an empty :class:`unittest.TestSuite` if *module*
1085 contains no docstrings instead of raising :exc:`ValueError`.
R David Murray5abd76a2012-09-10 10:15:58 -04001086
Georg Brandl116aa622007-08-15 14:28:22 +00001087
1088Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
1089of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
1090subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented
1091here (it's an internal detail), but studying its code can answer questions about
1092the exact details of :mod:`unittest` integration.
1093
1094Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of
1095:class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass
1096of :class:`DocTestCase`.
1097
1098So both ways of creating a :class:`unittest.TestSuite` run instances of
1099:class:`DocTestCase`. This is important for a subtle reason: when you run
1100:mod:`doctest` functions yourself, you can control the :mod:`doctest` options in
1101use directly, by passing option flags to :mod:`doctest` functions. However, if
1102you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls
1103when and how tests get run. The framework author typically wants to control
1104:mod:`doctest` reporting options (perhaps, e.g., specified by command line
1105options), but there's no way to pass options through :mod:`unittest` to
1106:mod:`doctest` test runners.
1107
1108For this reason, :mod:`doctest` also supports a notion of :mod:`doctest`
1109reporting flags specific to :mod:`unittest` support, via this function:
1110
1111
1112.. function:: set_unittest_reportflags(flags)
1113
1114 Set the :mod:`doctest` reporting flags to use.
1115
Mariatta Wijaya81b89772017-02-06 20:15:01 -08001116 Argument *flags* takes the :ref:`bitwise OR <bitwise>` of option flags. See
1117 section :ref:`doctest-options`. Only "reporting flags" can be used.
Georg Brandl116aa622007-08-15 14:28:22 +00001118
1119 This is a module-global setting, and affects all future doctests run by module
1120 :mod:`unittest`: the :meth:`runTest` method of :class:`DocTestCase` looks at
1121 the option flags specified for the test case when the :class:`DocTestCase`
1122 instance was constructed. If no reporting flags were specified (which is the
1123 typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are
Mariatta Wijaya81b89772017-02-06 20:15:01 -08001124 :ref:`bitwise ORed <bitwise>` into the option flags, and the option flags
1125 so augmented are passed to the :class:`DocTestRunner` instance created to
1126 run the doctest. If any reporting flags were specified when the
1127 :class:`DocTestCase` instance was constructed, :mod:`doctest`'s
1128 :mod:`unittest` reporting flags are ignored.
Georg Brandl116aa622007-08-15 14:28:22 +00001129
1130 The value of the :mod:`unittest` reporting flags in effect before the function
1131 was called is returned by the function.
1132
Georg Brandl116aa622007-08-15 14:28:22 +00001133
1134.. _doctest-advanced-api:
1135
1136Advanced API
1137------------
1138
1139The basic API is a simple wrapper that's intended to make doctest easy to use.
1140It is fairly flexible, and should meet most users' needs; however, if you
1141require more fine-grained control over testing, or wish to extend doctest's
1142capabilities, then you should use the advanced API.
1143
1144The advanced API revolves around two container classes, which are used to store
1145the interactive examples extracted from doctest cases:
1146
Ezio Melotti0639d5a2009-12-19 23:26:38 +00001147* :class:`Example`: A single Python :term:`statement`, paired with its expected
Christian Heimesd8654cf2007-12-02 15:22:16 +00001148 output.
Georg Brandl116aa622007-08-15 14:28:22 +00001149
1150* :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted
1151 from a single docstring or text file.
1152
1153Additional processing classes are defined to find, parse, and run, and check
1154doctest examples:
1155
1156* :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a
1157 :class:`DocTestParser` to create a :class:`DocTest` from every docstring that
1158 contains interactive examples.
1159
1160* :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such
1161 as an object's docstring).
1162
1163* :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses
1164 an :class:`OutputChecker` to verify their output.
1165
1166* :class:`OutputChecker`: Compares the actual output from a doctest example with
1167 the expected output, and decides whether they match.
1168
1169The relationships among these processing classes are summarized in the following
1170diagram::
1171
1172 list of:
1173 +------+ +---------+
1174 |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1175 +------+ | ^ +---------+ | ^ (printed)
1176 | | | Example | | |
1177 v | | ... | v |
1178 DocTestParser | Example | OutputChecker
1179 +---------+
1180
1181
1182.. _doctest-doctest:
1183
1184DocTest Objects
1185^^^^^^^^^^^^^^^
1186
1187
1188.. class:: DocTest(examples, globs, name, filename, lineno, docstring)
1189
1190 A collection of doctest examples that should be run in a single namespace. The
Senthil Kumarana6bac952011-07-04 11:28:30 -07001191 constructor arguments are used to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001192
Georg Brandl116aa622007-08-15 14:28:22 +00001193
Senthil Kumarana6bac952011-07-04 11:28:30 -07001194 :class:`DocTest` defines the following attributes. They are initialized by
Benjamin Petersone41251e2008-04-25 01:59:09 +00001195 the constructor, and should not be modified directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001196
1197
Benjamin Petersone41251e2008-04-25 01:59:09 +00001198 .. attribute:: examples
Georg Brandl116aa622007-08-15 14:28:22 +00001199
Benjamin Petersone41251e2008-04-25 01:59:09 +00001200 A list of :class:`Example` objects encoding the individual interactive Python
1201 examples that should be run by this test.
Georg Brandl116aa622007-08-15 14:28:22 +00001202
1203
Benjamin Petersone41251e2008-04-25 01:59:09 +00001204 .. attribute:: globs
Georg Brandl116aa622007-08-15 14:28:22 +00001205
Benjamin Petersone41251e2008-04-25 01:59:09 +00001206 The namespace (aka globals) that the examples should be run in. This is a
1207 dictionary mapping names to values. Any changes to the namespace made by the
1208 examples (such as binding new variables) will be reflected in :attr:`globs`
1209 after the test is run.
Georg Brandl116aa622007-08-15 14:28:22 +00001210
1211
Benjamin Petersone41251e2008-04-25 01:59:09 +00001212 .. attribute:: name
Georg Brandl116aa622007-08-15 14:28:22 +00001213
Benjamin Petersone41251e2008-04-25 01:59:09 +00001214 A string name identifying the :class:`DocTest`. Typically, this is the name
1215 of the object or file that the test was extracted from.
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217
Benjamin Petersone41251e2008-04-25 01:59:09 +00001218 .. attribute:: filename
Georg Brandl116aa622007-08-15 14:28:22 +00001219
Benjamin Petersone41251e2008-04-25 01:59:09 +00001220 The name of the file that this :class:`DocTest` was extracted from; or
1221 ``None`` if the filename is unknown, or if the :class:`DocTest` was not
1222 extracted from a file.
Georg Brandl116aa622007-08-15 14:28:22 +00001223
1224
Benjamin Petersone41251e2008-04-25 01:59:09 +00001225 .. attribute:: lineno
Georg Brandl116aa622007-08-15 14:28:22 +00001226
Benjamin Petersone41251e2008-04-25 01:59:09 +00001227 The line number within :attr:`filename` where this :class:`DocTest` begins, or
1228 ``None`` if the line number is unavailable. This line number is zero-based
1229 with respect to the beginning of the file.
Georg Brandl116aa622007-08-15 14:28:22 +00001230
1231
Benjamin Petersone41251e2008-04-25 01:59:09 +00001232 .. attribute:: docstring
Georg Brandl116aa622007-08-15 14:28:22 +00001233
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001234 The string that the test was extracted from, or ``None`` if the string is
Benjamin Petersone41251e2008-04-25 01:59:09 +00001235 unavailable, or if the test was not extracted from a string.
Georg Brandl116aa622007-08-15 14:28:22 +00001236
1237
1238.. _doctest-example:
1239
1240Example Objects
1241^^^^^^^^^^^^^^^
1242
1243
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001244.. class:: Example(source, want, exc_msg=None, lineno=0, indent=0, options=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001245
1246 A single interactive example, consisting of a Python statement and its expected
Senthil Kumarana6bac952011-07-04 11:28:30 -07001247 output. The constructor arguments are used to initialize the attributes of
1248 the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001249
Georg Brandl116aa622007-08-15 14:28:22 +00001250
Senthil Kumarana6bac952011-07-04 11:28:30 -07001251 :class:`Example` defines the following attributes. They are initialized by
Benjamin Petersone41251e2008-04-25 01:59:09 +00001252 the constructor, and should not be modified directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001253
1254
Benjamin Petersone41251e2008-04-25 01:59:09 +00001255 .. attribute:: source
Georg Brandl116aa622007-08-15 14:28:22 +00001256
Benjamin Petersone41251e2008-04-25 01:59:09 +00001257 A string containing the example's source code. This source code consists of a
1258 single Python statement, and always ends with a newline; the constructor adds
1259 a newline when necessary.
Georg Brandl116aa622007-08-15 14:28:22 +00001260
1261
Benjamin Petersone41251e2008-04-25 01:59:09 +00001262 .. attribute:: want
Georg Brandl116aa622007-08-15 14:28:22 +00001263
Benjamin Petersone41251e2008-04-25 01:59:09 +00001264 The expected output from running the example's source code (either from
1265 stdout, or a traceback in case of exception). :attr:`want` ends with a
1266 newline unless no output is expected, in which case it's an empty string. The
1267 constructor adds a newline when necessary.
Georg Brandl116aa622007-08-15 14:28:22 +00001268
1269
Benjamin Petersone41251e2008-04-25 01:59:09 +00001270 .. attribute:: exc_msg
Georg Brandl116aa622007-08-15 14:28:22 +00001271
Benjamin Petersone41251e2008-04-25 01:59:09 +00001272 The exception message generated by the example, if the example is expected to
1273 generate an exception; or ``None`` if it is not expected to generate an
1274 exception. This exception message is compared against the return value of
1275 :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline
1276 unless it's ``None``. The constructor adds a newline if needed.
Georg Brandl116aa622007-08-15 14:28:22 +00001277
1278
Benjamin Petersone41251e2008-04-25 01:59:09 +00001279 .. attribute:: lineno
Georg Brandl116aa622007-08-15 14:28:22 +00001280
Benjamin Petersone41251e2008-04-25 01:59:09 +00001281 The line number within the string containing this example where the example
1282 begins. This line number is zero-based with respect to the beginning of the
1283 containing string.
Georg Brandl116aa622007-08-15 14:28:22 +00001284
1285
Benjamin Petersone41251e2008-04-25 01:59:09 +00001286 .. attribute:: indent
Georg Brandl116aa622007-08-15 14:28:22 +00001287
Benjamin Petersone41251e2008-04-25 01:59:09 +00001288 The example's indentation in the containing string, i.e., the number of space
1289 characters that precede the example's first prompt.
Georg Brandl116aa622007-08-15 14:28:22 +00001290
1291
Benjamin Petersone41251e2008-04-25 01:59:09 +00001292 .. attribute:: options
Georg Brandl116aa622007-08-15 14:28:22 +00001293
Benjamin Petersone41251e2008-04-25 01:59:09 +00001294 A dictionary mapping from option flags to ``True`` or ``False``, which is used
1295 to override default options for this example. Any option flags not contained
1296 in this dictionary are left at their default value (as specified by the
1297 :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
Georg Brandl116aa622007-08-15 14:28:22 +00001298
1299
1300.. _doctest-doctestfinder:
1301
1302DocTestFinder objects
1303^^^^^^^^^^^^^^^^^^^^^
1304
1305
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001306.. class:: DocTestFinder(verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001307
1308 A processing class used to extract the :class:`DocTest`\ s that are relevant to
1309 a given object, from its docstring and the docstrings of its contained objects.
Zachary Warea4b7a752013-11-24 01:19:09 -06001310 :class:`DocTest`\ s can be extracted from modules, classes, functions,
1311 methods, staticmethods, classmethods, and properties.
Georg Brandl116aa622007-08-15 14:28:22 +00001312
1313 The optional argument *verbose* can be used to display the objects searched by
1314 the finder. It defaults to ``False`` (no output).
1315
1316 The optional argument *parser* specifies the :class:`DocTestParser` object (or a
1317 drop-in replacement) that is used to extract doctests from docstrings.
1318
1319 If the optional argument *recurse* is false, then :meth:`DocTestFinder.find`
1320 will only examine the given object, and not any contained objects.
1321
1322 If the optional argument *exclude_empty* is false, then
1323 :meth:`DocTestFinder.find` will include tests for objects with empty docstrings.
1324
Georg Brandl116aa622007-08-15 14:28:22 +00001325
Benjamin Petersone41251e2008-04-25 01:59:09 +00001326 :class:`DocTestFinder` defines the following method:
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328
Benjamin Petersone41251e2008-04-25 01:59:09 +00001329 .. method:: find(obj[, name][, module][, globs][, extraglobs])
Georg Brandl116aa622007-08-15 14:28:22 +00001330
Benjamin Petersone41251e2008-04-25 01:59:09 +00001331 Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
1332 docstring, or by any of its contained objects' docstrings.
Georg Brandl116aa622007-08-15 14:28:22 +00001333
Benjamin Petersone41251e2008-04-25 01:59:09 +00001334 The optional argument *name* specifies the object's name; this name will be
1335 used to construct names for the returned :class:`DocTest`\ s. If *name* is
1336 not specified, then ``obj.__name__`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Benjamin Petersone41251e2008-04-25 01:59:09 +00001338 The optional parameter *module* is the module that contains the given object.
Serhiy Storchakaecf41da2016-10-19 16:29:26 +03001339 If the module is not specified or is ``None``, then the test finder will attempt
Benjamin Petersone41251e2008-04-25 01:59:09 +00001340 to automatically determine the correct module. The object's module is used:
Georg Brandl116aa622007-08-15 14:28:22 +00001341
Benjamin Petersone41251e2008-04-25 01:59:09 +00001342 * As a default namespace, if *globs* is not specified.
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Benjamin Petersone41251e2008-04-25 01:59:09 +00001344 * To prevent the DocTestFinder from extracting DocTests from objects that are
1345 imported from other modules. (Contained objects with modules other than
1346 *module* are ignored.)
Georg Brandl116aa622007-08-15 14:28:22 +00001347
Benjamin Petersone41251e2008-04-25 01:59:09 +00001348 * To find the name of the file containing the object.
Georg Brandl116aa622007-08-15 14:28:22 +00001349
Benjamin Petersone41251e2008-04-25 01:59:09 +00001350 * To help find the line number of the object within its file.
Georg Brandl116aa622007-08-15 14:28:22 +00001351
Benjamin Petersone41251e2008-04-25 01:59:09 +00001352 If *module* is ``False``, no attempt to find the module will be made. This is
1353 obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
1354 is ``None`` but cannot be found automatically, then all objects are considered
1355 to belong to the (non-existent) module, so all contained objects will
1356 (recursively) be searched for doctests.
Georg Brandl116aa622007-08-15 14:28:22 +00001357
Benjamin Petersone41251e2008-04-25 01:59:09 +00001358 The globals for each :class:`DocTest` is formed by combining *globs* and
1359 *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
1360 shallow copy of the globals dictionary is created for each :class:`DocTest`.
1361 If *globs* is not specified, then it defaults to the module's *__dict__*, if
1362 specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
1363 defaults to ``{}``.
Georg Brandl116aa622007-08-15 14:28:22 +00001364
1365
1366.. _doctest-doctestparser:
1367
1368DocTestParser objects
1369^^^^^^^^^^^^^^^^^^^^^
1370
1371
1372.. class:: DocTestParser()
1373
1374 A processing class used to extract interactive examples from a string, and use
1375 them to create a :class:`DocTest` object.
1376
Georg Brandl116aa622007-08-15 14:28:22 +00001377
Benjamin Petersone41251e2008-04-25 01:59:09 +00001378 :class:`DocTestParser` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380
Benjamin Petersone41251e2008-04-25 01:59:09 +00001381 .. method:: get_doctest(string, globs, name, filename, lineno)
Georg Brandl116aa622007-08-15 14:28:22 +00001382
Benjamin Petersone41251e2008-04-25 01:59:09 +00001383 Extract all doctest examples from the given string, and collect them into a
1384 :class:`DocTest` object.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Benjamin Petersone41251e2008-04-25 01:59:09 +00001386 *globs*, *name*, *filename*, and *lineno* are attributes for the new
1387 :class:`DocTest` object. See the documentation for :class:`DocTest` for more
1388 information.
Georg Brandl116aa622007-08-15 14:28:22 +00001389
1390
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001391 .. method:: get_examples(string, name='<string>')
Georg Brandl116aa622007-08-15 14:28:22 +00001392
Benjamin Petersone41251e2008-04-25 01:59:09 +00001393 Extract all doctest examples from the given string, and return them as a list
1394 of :class:`Example` objects. Line numbers are 0-based. The optional argument
1395 *name* is a name identifying this string, and is only used for error messages.
Georg Brandl116aa622007-08-15 14:28:22 +00001396
1397
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001398 .. method:: parse(string, name='<string>')
Georg Brandl116aa622007-08-15 14:28:22 +00001399
Benjamin Petersone41251e2008-04-25 01:59:09 +00001400 Divide the given string into examples and intervening text, and return them as
1401 a list of alternating :class:`Example`\ s and strings. Line numbers for the
1402 :class:`Example`\ s are 0-based. The optional argument *name* is a name
1403 identifying this string, and is only used for error messages.
Georg Brandl116aa622007-08-15 14:28:22 +00001404
1405
1406.. _doctest-doctestrunner:
1407
1408DocTestRunner objects
1409^^^^^^^^^^^^^^^^^^^^^
1410
1411
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001412.. class:: DocTestRunner(checker=None, verbose=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001413
1414 A processing class used to execute and verify the interactive examples in a
1415 :class:`DocTest`.
1416
1417 The comparison between expected outputs and actual outputs is done by an
1418 :class:`OutputChecker`. This comparison may be customized with a number of
1419 option flags; see section :ref:`doctest-options` for more information. If the
1420 option flags are insufficient, then the comparison may also be customized by
1421 passing a subclass of :class:`OutputChecker` to the constructor.
1422
1423 The test runner's display output can be controlled in two ways. First, an output
1424 function can be passed to :meth:`TestRunner.run`; this function will be called
1425 with strings that should be displayed. It defaults to ``sys.stdout.write``. If
1426 capturing the output is not sufficient, then the display output can be also
1427 customized by subclassing DocTestRunner, and overriding the methods
1428 :meth:`report_start`, :meth:`report_success`,
1429 :meth:`report_unexpected_exception`, and :meth:`report_failure`.
1430
1431 The optional keyword argument *checker* specifies the :class:`OutputChecker`
1432 object (or drop-in replacement) that should be used to compare the expected
1433 outputs to the actual outputs of doctest examples.
1434
1435 The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s
1436 verbosity. If *verbose* is ``True``, then information is printed about each
1437 example, as it is run. If *verbose* is ``False``, then only failures are
1438 printed. If *verbose* is unspecified, or ``None``, then verbose output is used
Éric Araujo713d3032010-11-18 16:38:46 +00001439 iff the command-line switch ``-v`` is used.
Georg Brandl116aa622007-08-15 14:28:22 +00001440
1441 The optional keyword argument *optionflags* can be used to control how the test
1442 runner compares expected output to actual output, and how it displays failures.
1443 For more information, see section :ref:`doctest-options`.
1444
Georg Brandl116aa622007-08-15 14:28:22 +00001445
Benjamin Petersone41251e2008-04-25 01:59:09 +00001446 :class:`DocTestParser` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001447
1448
Benjamin Petersone41251e2008-04-25 01:59:09 +00001449 .. method:: report_start(out, test, example)
Georg Brandl116aa622007-08-15 14:28:22 +00001450
Benjamin Petersone41251e2008-04-25 01:59:09 +00001451 Report that the test runner is about to process the given example. This method
1452 is provided to allow subclasses of :class:`DocTestRunner` to customize their
1453 output; it should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001454
Benjamin Petersone41251e2008-04-25 01:59:09 +00001455 *example* is the example about to be processed. *test* is the test
1456 *containing example*. *out* is the output function that was passed to
1457 :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001458
1459
Benjamin Petersone41251e2008-04-25 01:59:09 +00001460 .. method:: report_success(out, test, example, got)
Georg Brandl116aa622007-08-15 14:28:22 +00001461
Benjamin Petersone41251e2008-04-25 01:59:09 +00001462 Report that the given example ran successfully. This method is provided to
1463 allow subclasses of :class:`DocTestRunner` to customize their output; it
1464 should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001465
Benjamin Petersone41251e2008-04-25 01:59:09 +00001466 *example* is the example about to be processed. *got* is the actual output
1467 from the example. *test* is the test containing *example*. *out* is the
1468 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001469
1470
Benjamin Petersone41251e2008-04-25 01:59:09 +00001471 .. method:: report_failure(out, test, example, got)
Georg Brandl116aa622007-08-15 14:28:22 +00001472
Benjamin Petersone41251e2008-04-25 01:59:09 +00001473 Report that the given example failed. This method is provided to allow
1474 subclasses of :class:`DocTestRunner` to customize their output; it should not
1475 be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001476
Benjamin Petersone41251e2008-04-25 01:59:09 +00001477 *example* is the example about to be processed. *got* is the actual output
1478 from the example. *test* is the test containing *example*. *out* is the
1479 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001480
1481
Benjamin Petersone41251e2008-04-25 01:59:09 +00001482 .. method:: report_unexpected_exception(out, test, example, exc_info)
Georg Brandl116aa622007-08-15 14:28:22 +00001483
Benjamin Petersone41251e2008-04-25 01:59:09 +00001484 Report that the given example raised an unexpected exception. This method is
1485 provided to allow subclasses of :class:`DocTestRunner` to customize their
1486 output; it should not be called directly.
Georg Brandl116aa622007-08-15 14:28:22 +00001487
Benjamin Petersone41251e2008-04-25 01:59:09 +00001488 *example* is the example about to be processed. *exc_info* is a tuple
1489 containing information about the unexpected exception (as returned by
1490 :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
1491 output function that was passed to :meth:`DocTestRunner.run`.
Georg Brandl116aa622007-08-15 14:28:22 +00001492
1493
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001494 .. method:: run(test, compileflags=None, out=None, clear_globs=True)
Georg Brandl116aa622007-08-15 14:28:22 +00001495
Benjamin Petersone41251e2008-04-25 01:59:09 +00001496 Run the examples in *test* (a :class:`DocTest` object), and display the
1497 results using the writer function *out*.
Georg Brandl116aa622007-08-15 14:28:22 +00001498
Benjamin Petersone41251e2008-04-25 01:59:09 +00001499 The examples are run in the namespace ``test.globs``. If *clear_globs* is
1500 true (the default), then this namespace will be cleared after the test runs,
1501 to help with garbage collection. If you would like to examine the namespace
1502 after the test completes, then use *clear_globs=False*.
Georg Brandl116aa622007-08-15 14:28:22 +00001503
Benjamin Petersone41251e2008-04-25 01:59:09 +00001504 *compileflags* gives the set of flags that should be used by the Python
1505 compiler when running the examples. If not specified, then it will default to
1506 the set of future-import flags that apply to *globs*.
Georg Brandl116aa622007-08-15 14:28:22 +00001507
Benjamin Petersone41251e2008-04-25 01:59:09 +00001508 The output of each example is checked using the :class:`DocTestRunner`'s
1509 output checker, and the results are formatted by the
1510 :meth:`DocTestRunner.report_\*` methods.
Georg Brandl116aa622007-08-15 14:28:22 +00001511
1512
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001513 .. method:: summarize(verbose=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001514
Benjamin Petersone41251e2008-04-25 01:59:09 +00001515 Print a summary of all the test cases that have been run by this DocTestRunner,
1516 and return a :term:`named tuple` ``TestResults(failed, attempted)``.
Georg Brandl116aa622007-08-15 14:28:22 +00001517
Benjamin Petersone41251e2008-04-25 01:59:09 +00001518 The optional *verbose* argument controls how detailed the summary is. If the
1519 verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
1520 used.
Georg Brandl116aa622007-08-15 14:28:22 +00001521
1522.. _doctest-outputchecker:
1523
1524OutputChecker objects
1525^^^^^^^^^^^^^^^^^^^^^
1526
1527
1528.. class:: OutputChecker()
1529
1530 A class used to check the whether the actual output from a doctest example
1531 matches the expected output. :class:`OutputChecker` defines two methods:
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +02001532 :meth:`check_output`, which compares a given pair of outputs, and returns ``True``
Georg Brandl116aa622007-08-15 14:28:22 +00001533 if they match; and :meth:`output_difference`, which returns a string describing
1534 the differences between two outputs.
1535
Georg Brandl116aa622007-08-15 14:28:22 +00001536
Benjamin Petersone41251e2008-04-25 01:59:09 +00001537 :class:`OutputChecker` defines the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +00001538
Benjamin Petersone41251e2008-04-25 01:59:09 +00001539 .. method:: check_output(want, got, optionflags)
Georg Brandl116aa622007-08-15 14:28:22 +00001540
Benjamin Petersone41251e2008-04-25 01:59:09 +00001541 Return ``True`` iff the actual output from an example (*got*) matches the
1542 expected output (*want*). These strings are always considered to match if
1543 they are identical; but depending on what option flags the test runner is
1544 using, several non-exact match types are also possible. See section
1545 :ref:`doctest-options` for more information about option flags.
Georg Brandl116aa622007-08-15 14:28:22 +00001546
1547
Benjamin Petersone41251e2008-04-25 01:59:09 +00001548 .. method:: output_difference(example, got, optionflags)
Georg Brandl116aa622007-08-15 14:28:22 +00001549
Benjamin Petersone41251e2008-04-25 01:59:09 +00001550 Return a string describing the differences between the expected output for a
1551 given example (*example*) and the actual output (*got*). *optionflags* is the
1552 set of option flags used to compare *want* and *got*.
Georg Brandl116aa622007-08-15 14:28:22 +00001553
1554
1555.. _doctest-debugging:
1556
1557Debugging
1558---------
1559
1560Doctest provides several mechanisms for debugging doctest examples:
1561
1562* Several functions convert doctests to executable Python programs, which can be
1563 run under the Python debugger, :mod:`pdb`.
1564
1565* The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that
1566 raises an exception for the first failing example, containing information about
1567 that example. This information can be used to perform post-mortem debugging on
1568 the example.
1569
1570* The :mod:`unittest` cases generated by :func:`DocTestSuite` support the
1571 :meth:`debug` method defined by :class:`unittest.TestCase`.
1572
1573* You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll
1574 drop into the Python debugger when that line is executed. Then you can inspect
1575 current values of variables, and so on. For example, suppose :file:`a.py`
1576 contains just this module docstring::
1577
1578 """
1579 >>> def f(x):
1580 ... g(x*2)
1581 >>> def g(x):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001582 ... print(x+3)
Georg Brandl116aa622007-08-15 14:28:22 +00001583 ... import pdb; pdb.set_trace()
1584 >>> f(3)
1585 9
1586 """
1587
1588 Then an interactive Python session may look like this::
1589
1590 >>> import a, doctest
1591 >>> doctest.testmod(a)
1592 --Return--
1593 > <doctest a[1]>(3)g()->None
1594 -> import pdb; pdb.set_trace()
1595 (Pdb) list
1596 1 def g(x):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001597 2 print(x+3)
Georg Brandl116aa622007-08-15 14:28:22 +00001598 3 -> import pdb; pdb.set_trace()
1599 [EOF]
Georg Brandl6911e3c2007-09-04 07:15:32 +00001600 (Pdb) p x
Georg Brandl116aa622007-08-15 14:28:22 +00001601 6
1602 (Pdb) step
1603 --Return--
1604 > <doctest a[0]>(2)f()->None
1605 -> g(x*2)
1606 (Pdb) list
1607 1 def f(x):
1608 2 -> g(x*2)
1609 [EOF]
Georg Brandl6911e3c2007-09-04 07:15:32 +00001610 (Pdb) p x
Georg Brandl116aa622007-08-15 14:28:22 +00001611 3
1612 (Pdb) step
1613 --Return--
1614 > <doctest a[2]>(1)?()->None
1615 -> f(3)
1616 (Pdb) cont
1617 (0, 3)
1618 >>>
1619
Georg Brandl116aa622007-08-15 14:28:22 +00001620
1621Functions that convert doctests to Python code, and possibly run the synthesized
1622code under the debugger:
1623
1624
1625.. function:: script_from_examples(s)
1626
1627 Convert text with examples to a script.
1628
1629 Argument *s* is a string containing doctest examples. The string is converted
1630 to a Python script, where doctest examples in *s* are converted to regular code,
1631 and everything else is converted to Python comments. The generated script is
1632 returned as a string. For example, ::
1633
1634 import doctest
Georg Brandl6911e3c2007-09-04 07:15:32 +00001635 print(doctest.script_from_examples(r"""
Georg Brandl116aa622007-08-15 14:28:22 +00001636 Set x and y to 1 and 2.
1637 >>> x, y = 1, 2
1638
1639 Print their sum:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001640 >>> print(x+y)
Georg Brandl116aa622007-08-15 14:28:22 +00001641 3
Georg Brandl6911e3c2007-09-04 07:15:32 +00001642 """))
Georg Brandl116aa622007-08-15 14:28:22 +00001643
1644 displays::
1645
1646 # Set x and y to 1 and 2.
1647 x, y = 1, 2
1648 #
1649 # Print their sum:
Georg Brandl6911e3c2007-09-04 07:15:32 +00001650 print(x+y)
Georg Brandl116aa622007-08-15 14:28:22 +00001651 # Expected:
1652 ## 3
1653
1654 This function is used internally by other functions (see below), but can also be
1655 useful when you want to transform an interactive Python session into a Python
1656 script.
1657
Georg Brandl116aa622007-08-15 14:28:22 +00001658
1659.. function:: testsource(module, name)
1660
1661 Convert the doctest for an object to a script.
1662
1663 Argument *module* is a module object, or dotted name of a module, containing the
1664 object whose doctests are of interest. Argument *name* is the name (within the
1665 module) of the object with the doctests of interest. The result is a string,
1666 containing the object's docstring converted to a Python script, as described for
1667 :func:`script_from_examples` above. For example, if module :file:`a.py`
1668 contains a top-level function :func:`f`, then ::
1669
1670 import a, doctest
Georg Brandl6911e3c2007-09-04 07:15:32 +00001671 print(doctest.testsource(a, "a.f"))
Georg Brandl116aa622007-08-15 14:28:22 +00001672
1673 prints a script version of function :func:`f`'s docstring, with doctests
1674 converted to code, and the rest placed in comments.
1675
Georg Brandl116aa622007-08-15 14:28:22 +00001676
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001677.. function:: debug(module, name, pm=False)
Georg Brandl116aa622007-08-15 14:28:22 +00001678
1679 Debug the doctests for an object.
1680
1681 The *module* and *name* arguments are the same as for function
1682 :func:`testsource` above. The synthesized Python script for the named object's
1683 docstring is written to a temporary file, and then that file is run under the
1684 control of the Python debugger, :mod:`pdb`.
1685
1686 A shallow copy of ``module.__dict__`` is used for both local and global
1687 execution context.
1688
1689 Optional argument *pm* controls whether post-mortem debugging is used. If *pm*
1690 has a true value, the script file is run directly, and the debugger gets
1691 involved only if the script terminates via raising an unhandled exception. If
1692 it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`,
1693 passing the traceback object from the unhandled exception. If *pm* is not
1694 specified, or is false, the script is run under the debugger from the start, via
1695 passing an appropriate :func:`exec` call to :func:`pdb.run`.
1696
Georg Brandl116aa622007-08-15 14:28:22 +00001697
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001698.. function:: debug_src(src, pm=False, globs=None)
Georg Brandl116aa622007-08-15 14:28:22 +00001699
1700 Debug the doctests in a string.
1701
1702 This is like function :func:`debug` above, except that a string containing
1703 doctest examples is specified directly, via the *src* argument.
1704
1705 Optional argument *pm* has the same meaning as in function :func:`debug` above.
1706
1707 Optional argument *globs* gives a dictionary to use as both local and global
1708 execution context. If not specified, or ``None``, an empty dictionary is used.
1709 If specified, a shallow copy of the dictionary is used.
1710
Georg Brandl116aa622007-08-15 14:28:22 +00001711
1712The :class:`DebugRunner` class, and the special exceptions it may raise, are of
1713most interest to testing framework authors, and will only be sketched here. See
1714the source code, and especially :class:`DebugRunner`'s docstring (which is a
1715doctest!) for more details:
1716
1717
Georg Brandlc2a4f4f2009-04-10 09:03:43 +00001718.. class:: DebugRunner(checker=None, verbose=None, optionflags=0)
Georg Brandl116aa622007-08-15 14:28:22 +00001719
1720 A subclass of :class:`DocTestRunner` that raises an exception as soon as a
1721 failure is encountered. If an unexpected exception occurs, an
1722 :exc:`UnexpectedException` exception is raised, containing the test, the
1723 example, and the original exception. If the output doesn't match, then a
1724 :exc:`DocTestFailure` exception is raised, containing the test, the example, and
1725 the actual output.
1726
1727 For information about the constructor parameters and methods, see the
1728 documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`.
1729
1730There are two exceptions that may be raised by :class:`DebugRunner` instances:
1731
1732
1733.. exception:: DocTestFailure(test, example, got)
1734
Georg Brandl7cb13192010-08-03 12:06:29 +00001735 An exception raised by :class:`DocTestRunner` to signal that a doctest example's
Georg Brandl116aa622007-08-15 14:28:22 +00001736 actual output did not match its expected output. The constructor arguments are
Senthil Kumarana6bac952011-07-04 11:28:30 -07001737 used to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001738
Senthil Kumarana6bac952011-07-04 11:28:30 -07001739:exc:`DocTestFailure` defines the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001740
1741
1742.. attribute:: DocTestFailure.test
1743
1744 The :class:`DocTest` object that was being run when the example failed.
1745
1746
1747.. attribute:: DocTestFailure.example
1748
1749 The :class:`Example` that failed.
1750
1751
1752.. attribute:: DocTestFailure.got
1753
1754 The example's actual output.
1755
1756
1757.. exception:: UnexpectedException(test, example, exc_info)
1758
Georg Brandl7cb13192010-08-03 12:06:29 +00001759 An exception raised by :class:`DocTestRunner` to signal that a doctest
1760 example raised an unexpected exception. The constructor arguments are used
Senthil Kumarana6bac952011-07-04 11:28:30 -07001761 to initialize the attributes of the same names.
Georg Brandl116aa622007-08-15 14:28:22 +00001762
Senthil Kumarana6bac952011-07-04 11:28:30 -07001763:exc:`UnexpectedException` defines the following attributes:
Georg Brandl116aa622007-08-15 14:28:22 +00001764
1765
1766.. attribute:: UnexpectedException.test
1767
1768 The :class:`DocTest` object that was being run when the example failed.
1769
1770
1771.. attribute:: UnexpectedException.example
1772
1773 The :class:`Example` that failed.
1774
1775
1776.. attribute:: UnexpectedException.exc_info
1777
1778 A tuple containing information about the unexpected exception, as returned by
1779 :func:`sys.exc_info`.
1780
1781
1782.. _doctest-soapbox:
1783
1784Soapbox
1785-------
1786
1787As mentioned in the introduction, :mod:`doctest` has grown to have three primary
1788uses:
1789
1790#. Checking examples in docstrings.
1791
1792#. Regression testing.
1793
1794#. Executable documentation / literate testing.
1795
1796These uses have different requirements, and it is important to distinguish them.
1797In particular, filling your docstrings with obscure test cases makes for bad
1798documentation.
1799
1800When writing a docstring, choose docstring examples with care. There's an art to
1801this that needs to be learned---it may not be natural at first. Examples should
1802add genuine value to the documentation. A good example can often be worth many
1803words. If done with care, the examples will be invaluable for your users, and
1804will pay back the time it takes to collect them many times over as the years go
1805by and things change. I'm still amazed at how often one of my :mod:`doctest`
1806examples stops working after a "harmless" change.
1807
1808Doctest also makes an excellent tool for regression testing, especially if you
1809don't skimp on explanatory text. By interleaving prose and examples, it becomes
1810much easier to keep track of what's actually being tested, and why. When a test
1811fails, good prose can make it much easier to figure out what the problem is, and
1812how it should be fixed. It's true that you could write extensive comments in
1813code-based testing, but few programmers do. Many have found that using doctest
1814approaches instead leads to much clearer tests. Perhaps this is simply because
1815doctest makes writing prose a little easier than writing code, while writing
1816comments in code is a little harder. I think it goes deeper than just that:
1817the natural attitude when writing a doctest-based test is that you want to
1818explain the fine points of your software, and illustrate them with examples.
1819This in turn naturally leads to test files that start with the simplest
1820features, and logically progress to complications and edge cases. A coherent
1821narrative is the result, instead of a collection of isolated functions that test
1822isolated bits of functionality seemingly at random. It's a different attitude,
1823and produces different results, blurring the distinction between testing and
1824explaining.
1825
1826Regression testing is best confined to dedicated objects or files. There are
1827several options for organizing tests:
1828
1829* Write text files containing test cases as interactive examples, and test the
1830 files using :func:`testfile` or :func:`DocFileSuite`. This is recommended,
1831 although is easiest to do for new projects, designed from the start to use
1832 doctest.
1833
1834* Define functions named ``_regrtest_topic`` that consist of single docstrings,
1835 containing test cases for the named topics. These functions can be included in
1836 the same file as the module, or separated out into a separate test file.
1837
1838* Define a ``__test__`` dictionary mapping from regression test topics to
1839 docstrings containing test cases.
1840
Ethan Furman2a5f9da2015-09-17 22:20:41 -07001841When you have placed your tests in a module, the module can itself be the test
1842runner. When a test fails, you can arrange for your test runner to re-run only
1843the failing doctest while you debug the problem. Here is a minimal example of
1844such a test runner::
1845
1846 if __name__ == '__main__':
1847 import doctest
1848 flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
1849 if len(sys.argv) > 1:
1850 name = sys.argv[1]
1851 if name in globals():
1852 obj = globals()[name]
1853 else:
1854 obj = __test__[name]
1855 doctest.run_docstring_examples(obj, globals(), name=name,
1856 optionflags=flags)
1857 else:
1858 fail, total = doctest.testmod(optionflags=flags)
1859 print("{} failures out of {} tests".format(fail, total))
1860
1861
Georg Brandl116aa622007-08-15 14:28:22 +00001862.. rubric:: Footnotes
1863
1864.. [#] Examples containing both expected output and an exception are not supported.
1865 Trying to guess where one ends and the other begins is too error-prone, and that
1866 also makes for a confusing test.