Debian Codegraph @

cpython27/Doc/library/doctest.rst

raw
1 :keepdoctest:
2
3 :mod:`doctest` --- Test interactive Python examples
4 ===================================================
5
6 .. module:: doctest
7 :synopsis: Test pieces of code within docstrings.
8 .. moduleauthor:: Tim Peters <[email protected]>
9 .. sectionauthor:: Tim Peters <[email protected]>
10 .. sectionauthor:: Moshe Zadka <[email protected]>
11 .. sectionauthor:: Edward Loper <[email protected]>
12
13
14 The :mod:`doctest` module searches for pieces of text that look like interactive
15 Python sessions, and then executes those sessions to verify that they work
16 exactly as shown. There are several common ways to use doctest:
17
18 * To check that a module's docstrings are up-to-date by verifying that all
19 interactive examples still work as documented.
20
21 * To perform regression testing by verifying that interactive examples from a
22 test file or a test object work as expected.
23
24 * To write tutorial documentation for a package, liberally illustrated with
25 input-output examples. Depending on whether the examples or the expository text
26 are emphasized, this has the flavor of "literate testing" or "executable
27 documentation".
28
29 Here's a complete but small example module::
30
31 """
32 This is the "example" module.
33
34 The example module supplies one function, factorial(). For example,
35
36 >>> factorial(5)
37 120
38 """
39
40 def factorial(n):
41 """Return the factorial of n, an exact integer >= 0.
42
43 If the result is small enough to fit in an int, return an int.
44 Else return a long.
45
46 >>> [factorial(n) for n in range(6)]
47 [1, 1, 2, 6, 24, 120]
48 >>> [factorial(long(n)) for n in range(6)]
49 [1, 1, 2, 6, 24, 120]
50 >>> factorial(30)
51 265252859812191058636308480000000L
52 >>> factorial(30L)
53 265252859812191058636308480000000L
54 >>> factorial(-1)
55 Traceback (most recent call last):
56 ...
57 ValueError: n must be >= 0
58
59 Factorials of floats are OK, but the float must be an exact integer:
60 >>> factorial(30.1)
61 Traceback (most recent call last):
62 ...
63 ValueError: n must be exact integer
64 >>> factorial(30.0)
65 265252859812191058636308480000000L
66
67 It must also not be ridiculously large:
68 >>> factorial(1e100)
69 Traceback (most recent call last):
70 ...
71 OverflowError: n too large
72 """
73
74 import math
75 if not n >= 0:
76 raise ValueError("n must be >= 0")
77 if math.floor(n) != n:
78 raise ValueError("n must be exact integer")
79 if n+1 == n: # catch a value like 1e300
80 raise OverflowError("n too large")
81 result = 1
82 factor = 2
83 while factor <= n:
84 result *= factor
85 factor += 1
86 return result
87
88
89 if __name__ == "__main__":
90 import doctest
91 doctest.testmod()
92
93 If you run :file:`example.py` directly from the command line, :mod:`doctest`
94 works its magic:
95
96 .. code-block:: shell-session
97
98 $ python example.py
99 $
100
101 There's no output! That's normal, and it means all the examples worked. Pass
102 ``-v`` to the script, and :mod:`doctest` prints a detailed log of what
103 it's trying, and prints a summary at the end:
104
105 .. code-block:: shell-session
106
107 $ python example.py -v
108 Trying:
109 factorial(5)
110 Expecting:
111 120
112 ok
113 Trying:
114 [factorial(n) for n in range(6)]
115 Expecting:
116 [1, 1, 2, 6, 24, 120]
117 ok
118 Trying:
119 [factorial(long(n)) for n in range(6)]
120 Expecting:
121 [1, 1, 2, 6, 24, 120]
122 ok
123
124 And so on, eventually ending with:
125
126 .. code-block:: none
127
128 Trying:
129 factorial(1e100)
130 Expecting:
131 Traceback (most recent call last):
132 ...
133 OverflowError: n too large
134 ok
135 2 items passed all tests:
136 1 tests in __main__
137 8 tests in __main__.factorial
138 9 tests in 2 items.
139 9 passed and 0 failed.
140 Test passed.
141 $
142
143 That's all you need to know to start making productive use of :mod:`doctest`!
144 Jump in. The following sections provide full details. Note that there are many
145 examples of doctests in the standard Python test suite and libraries.
146 Especially useful examples can be found in the standard test file
147 :file:`Lib/test/test_doctest.py`.
148
149
150 .. _doctest-simple-testmod:
151
152 Simple Usage: Checking Examples in Docstrings
153 ---------------------------------------------
154
155 The simplest way to start using doctest (but not necessarily the way you'll
156 continue to do it) is to end each module :mod:`M` with::
157
158 if __name__ == "__main__":
159 import doctest
160 doctest.testmod()
161
162 :mod:`doctest` then examines docstrings in module :mod:`M`.
163
164 Running the module as a script causes the examples in the docstrings to get
165 executed and verified::
166
167 python M.py
168
169 This won't display anything unless an example fails, in which case the failing
170 example(s) and the cause(s) of the failure(s) are printed to stdout, and the
171 final line of output is ``***Test Failed*** N failures.``, where *N* is the
172 number of examples that failed.
173
174 Run it with the ``-v`` switch instead::
175
176 python M.py -v
177
178 and a detailed report of all examples tried is printed to standard output, along
179 with assorted summaries at the end.
180
181 You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or
182 prohibit it by passing ``verbose=False``. In either of those cases,
183 ``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not
184 has no effect).
185
186 Since Python 2.6, there is also a command line shortcut for running
187 :func:`testmod`. You can instruct the Python interpreter to run the doctest
188 module directly from the standard library and pass the module name(s) on the
189 command line::
190
191 python -m doctest -v example.py
192
193 This will import :file:`example.py` as a standalone module and run
194 :func:`testmod` on it. Note that this may not work correctly if the file is
195 part of a package and imports other submodules from that package.
196
197 For more information on :func:`testmod`, see section :ref:`doctest-basic-api`.
198
199
200 .. _doctest-simple-testfile:
201
202 Simple Usage: Checking Examples in a Text File
203 ----------------------------------------------
204
205 Another simple application of doctest is testing interactive examples in a text
206 file. This can be done with the :func:`testfile` function::
207
208 import doctest
209 doctest.testfile("example.txt")
210
211 That short script executes and verifies any interactive Python examples
212 contained in the file :file:`example.txt`. The file content is treated as if it
213 were a single giant docstring; the file doesn't need to contain a Python
214 program! For example, perhaps :file:`example.txt` contains this:
215
216 .. code-block:: none
217
218 The ``example`` module
219 ======================
220
221 Using ``factorial``
222 -------------------
223
224 This is an example text file in reStructuredText format. First import
225 ``factorial`` from the ``example`` module:
226
227 >>> from example import factorial
228
229 Now use it:
230
231 >>> factorial(6)
232 120
233
234 Running ``doctest.testfile("example.txt")`` then finds the error in this
235 documentation::
236
237 File "./example.txt", line 14, in example.txt
238 Failed example:
239 factorial(6)
240 Expected:
241 120
242 Got:
243 720
244
245 As with :func:`testmod`, :func:`testfile` won't display anything unless an
246 example fails. If an example does fail, then the failing example(s) and the
247 cause(s) of the failure(s) are printed to stdout, using the same format as
248 :func:`testmod`.
249
250 By default, :func:`testfile` looks for files in the calling module's directory.
251 See section :ref:`doctest-basic-api` for a description of the optional arguments
252 that can be used to tell it to look for files in other locations.
253
254 Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the
255 ``-v`` command-line switch or with the optional keyword argument
256 *verbose*.
257
258 Since Python 2.6, there is also a command line shortcut for running
259 :func:`testfile`. You can instruct the Python interpreter to run the doctest
260 module directly from the standard library and pass the file name(s) on the
261 command line::
262
263 python -m doctest -v example.txt
264
265 Because the file name does not end with :file:`.py`, :mod:`doctest` infers that
266 it must be run with :func:`testfile`, not :func:`testmod`.
267
268 For more information on :func:`testfile`, see section :ref:`doctest-basic-api`.
269
270
271 .. _doctest-how-it-works:
272
273 How It Works
274 ------------
275
276 This section examines in detail how doctest works: which docstrings it looks at,
277 how it finds interactive examples, what execution context it uses, how it
278 handles exceptions, and how option flags can be used to control its behavior.
279 This is the information that you need to know to write doctest examples; for
280 information about actually running doctest on these examples, see the following
281 sections.
282
283
284 .. _doctest-which-docstrings:
285
286 Which Docstrings Are Examined?
287 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
288
289 The module docstring, and all function, class and method docstrings are
290 searched. Objects imported into the module are not searched.
291
292 In addition, if ``M.__test__`` exists and "is true", it must be a dict, and each
293 entry maps a (string) name to a function object, class object, or string.
294 Function and class object docstrings found from ``M.__test__`` are searched, and
295 strings are treated as if they were docstrings. In output, a key ``K`` in
296 ``M.__test__`` appears with name ::
297
298 <name of M>.__test__.K
299
300 Any classes found are recursively searched similarly, to test docstrings in
301 their contained methods and nested classes.
302
303 .. versionchanged:: 2.4
304 A "private name" concept is deprecated and no longer documented.
305
306
307 .. _doctest-finding-examples:
308
309 How are Docstring Examples Recognized?
310 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
311
312 In most cases a copy-and-paste of an interactive console session works fine,
313 but doctest isn't trying to do an exact emulation of any specific Python shell.
314
315 ::
316
317 >>> # comments are ignored
318 >>> x = 12
319 >>> x
320 12
321 >>> if x == 13:
322 ... print "yes"
323 ... else:
324 ... print "no"
325 ... print "NO"
326 ... print "NO!!!"
327 ...
328 no
329 NO
330 NO!!!
331 >>>
332
333 Any expected output must immediately follow the final ``'>>> '`` or ``'... '``
334 line containing the code, and the expected output (if any) extends to the next
335 ``'>>> '`` or all-whitespace line.
336
337 The fine print:
338
339 * Expected output cannot contain an all-whitespace line, since such a line is
340 taken to signal the end of expected output. If expected output does contain a
341 blank line, put ``<BLANKLINE>`` in your doctest example each place a blank line
342 is expected.
343
344 .. versionadded:: 2.4
345 ``<BLANKLINE>`` was added; there was no way to use expected output containing
346 empty lines in previous versions.
347
348 * All hard tab characters are expanded to spaces, using 8-column tab stops.
349 Tabs in output generated by the tested code are not modified. Because any
350 hard tabs in the sample output *are* expanded, this means that if the code
351 output includes hard tabs, the only way the doctest can pass is if the
352 :const:`NORMALIZE_WHITESPACE` option or :ref:`directive <doctest-directives>`
353 is in effect.
354 Alternatively, the test can be rewritten to capture the output and compare it
355 to an expected value as part of the test. This handling of tabs in the
356 source was arrived at through trial and error, and has proven to be the least
357 error prone way of handling them. It is possible to use a different
358 algorithm for handling tabs by writing a custom :class:`DocTestParser` class.
359
360 .. versionchanged:: 2.4
361 Expanding tabs to spaces is new; previous versions tried to preserve hard tabs,
362 with confusing results.
363
364 * Output to stdout is captured, but not output to stderr (exception tracebacks
365 are captured via a different means).
366
367 * If you continue a line via backslashing in an interactive session, or for any
368 other reason use a backslash, you should use a raw docstring, which will
369 preserve your backslashes exactly as you type them::
370
371 >>> def f(x):
372 ... r'''Backslashes in a raw docstring: m\n'''
373 >>> print f.__doc__
374 Backslashes in a raw docstring: m\n
375
376 Otherwise, the backslash will be interpreted as part of the string. For example,
377 the ``\n`` above would be interpreted as a newline character. Alternatively, you
378 can double each backslash in the doctest version (and not use a raw string)::
379
380 >>> def f(x):
381 ... '''Backslashes in a raw docstring: m\\n'''
382 >>> print f.__doc__
383 Backslashes in a raw docstring: m\n
384
385 * The starting column doesn't matter::
386
387 >>> assert "Easy!"
388 >>> import math
389 >>> math.floor(1.9)
390 1.0
391
392 and as many leading whitespace characters are stripped from the expected output
393 as appeared in the initial ``'>>> '`` line that started the example.
394
395
396 .. _doctest-execution-context:
397
398 What's the Execution Context?
399 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
400
401 By default, each time :mod:`doctest` finds a docstring to test, it uses a
402 *shallow copy* of :mod:`M`'s globals, so that running tests doesn't change the
403 module's real globals, and so that one test in :mod:`M` can't leave behind
404 crumbs that accidentally allow another test to work. This means examples can
405 freely use any names defined at top-level in :mod:`M`, and names defined earlier
406 in the docstring being run. Examples cannot see names defined in other
407 docstrings.
408
409 You can force use of your own dict as the execution context by passing
410 ``globs=your_dict`` to :func:`testmod` or :func:`testfile` instead.
411
412
413 .. _doctest-exceptions:
414
415 What About Exceptions?
416 ^^^^^^^^^^^^^^^^^^^^^^
417
418 No problem, provided that the traceback is the only output produced by the
419 example: just paste in the traceback. [#]_ Since tracebacks contain details
420 that are likely to change rapidly (for example, exact file paths and line
421 numbers), this is one case where doctest works hard to be flexible in what it
422 accepts.
423
424 Simple example::
425
426 >>> [1, 2, 3].remove(42)
427 Traceback (most recent call last):
428 File "<stdin>", line 1, in <module>
429 ValueError: list.remove(x): x not in list
430
431 That doctest succeeds if :exc:`ValueError` is raised, with the ``list.remove(x):
432 x not in list`` detail as shown.
433
434 The expected output for an exception must start with a traceback header, which
435 may be either of the following two lines, indented the same as the first line of
436 the example::
437
438 Traceback (most recent call last):
439 Traceback (innermost last):
440
441 The traceback header is followed by an optional traceback stack, whose contents
442 are ignored by doctest. The traceback stack is typically omitted, or copied
443 verbatim from an interactive session.
444
445 The traceback stack is followed by the most interesting part: the line(s)
446 containing the exception type and detail. This is usually the last line of a
447 traceback, but can extend across multiple lines if the exception has a
448 multi-line detail::
449
450 >>> raise ValueError('multi\n line\ndetail')
451 Traceback (most recent call last):
452 File "<stdin>", line 1, in <module>
453 ValueError: multi
454 line
455 detail
456
457 The last three lines (starting with :exc:`ValueError`) are compared against the
458 exception's type and detail, and the rest are ignored.
459
460 .. versionchanged:: 2.4
461 Previous versions were unable to handle multi-line exception details.
462
463 Best practice is to omit the traceback stack, unless it adds significant
464 documentation value to the example. So the last example is probably better as::
465
466 >>> raise ValueError('multi\n line\ndetail')
467 Traceback (most recent call last):
468 ...
469 ValueError: multi
470 line
471 detail
472
473 Note that tracebacks are treated very specially. In particular, in the
474 rewritten example, the use of ``...`` is independent of doctest's
475 :const:`ELLIPSIS` option. The ellipsis in that example could be left out, or
476 could just as well be three (or three hundred) commas or digits, or an indented
477 transcript of a Monty Python skit.
478
479 Some details you should read once, but won't need to remember:
480
481 * Doctest can't guess whether your expected output came from an exception
482 traceback or from ordinary printing. So, e.g., an example that expects
483 ``ValueError: 42 is prime`` will pass whether :exc:`ValueError` is actually
484 raised or if the example merely prints that traceback text. In practice,
485 ordinary output rarely begins with a traceback header line, so this doesn't
486 create real problems.
487
488 * Each line of the traceback stack (if present) must be indented further than
489 the first line of the example, *or* start with a non-alphanumeric character.
490 The first line following the traceback header indented the same and starting
491 with an alphanumeric is taken to be the start of the exception detail. Of
492 course this does the right thing for genuine tracebacks.
493
494 * When the :const:`IGNORE_EXCEPTION_DETAIL` doctest option is specified,
495 everything following the leftmost colon and any module information in the
496 exception name is ignored.
497
498 * The interactive shell omits the traceback header line for some
499 :exc:`SyntaxError`\ s. But doctest uses the traceback header line to
500 distinguish exceptions from non-exceptions. So in the rare case where you need
501 to test a :exc:`SyntaxError` that omits the traceback header, you will need to
502 manually add the traceback header line to your test example.
503
504 * For some :exc:`SyntaxError`\ s, Python displays the character position of the
505 syntax error, using a ``^`` marker::
506
507 >>> 1 1
508 File "<stdin>", line 1
509 1 1
510 ^
511 SyntaxError: invalid syntax
512
513 Since the lines showing the position of the error come before the exception type
514 and detail, they are not checked by doctest. For example, the following test
515 would pass, even though it puts the ``^`` marker in the wrong location::
516
517 >>> 1 1
518 Traceback (most recent call last):
519 File "<stdin>", line 1
520 1 1
521 ^
522 SyntaxError: invalid syntax
523
524
525 .. _option-flags-and-directives:
526 .. _doctest-options:
527
528 Option Flags
529 ^^^^^^^^^^^^
530
531 A number of option flags control various aspects of doctest's behavior.
532 Symbolic names for the flags are supplied as module constants, which can be
533 :ref:`bitwise ORed <bitwise>` together and passed to various functions.
534 The names can also be used in :ref:`doctest directives <doctest-directives>`.
535
536 The first group of options define test semantics, controlling aspects of how
537 doctest decides whether actual output matches an example's expected output:
538
539
540 .. data:: DONT_ACCEPT_TRUE_FOR_1
541
542 By default, if an expected output block contains just ``1``, an actual output
543 block containing just ``1`` or just ``True`` is considered to be a match, and
544 similarly for ``0`` versus ``False``. When :const:`DONT_ACCEPT_TRUE_FOR_1` is
545 specified, neither substitution is allowed. The default behavior caters to that
546 Python changed the return type of many functions from integer to boolean;
547 doctests expecting "little integer" output still work in these cases. This
548 option will probably go away, but not for several years.
549
550
551 .. data:: DONT_ACCEPT_BLANKLINE
552
553 By default, if an expected output block contains a line containing only the
554 string ``<BLANKLINE>``, then that line will match a blank line in the actual
555 output. Because a genuinely blank line delimits the expected output, this is
556 the only way to communicate that a blank line is expected. When
557 :const:`DONT_ACCEPT_BLANKLINE` is specified, this substitution is not allowed.
558
559
560 .. data:: NORMALIZE_WHITESPACE
561
562 When specified, all sequences of whitespace (blanks and newlines) are treated as
563 equal. Any sequence of whitespace within the expected output will match any
564 sequence of whitespace within the actual output. By default, whitespace must
565 match exactly. :const:`NORMALIZE_WHITESPACE` is especially useful when a line of
566 expected output is very long, and you want to wrap it across multiple lines in
567 your source.
568
569
570 .. data:: ELLIPSIS
571
572 When specified, an ellipsis marker (``...``) in the expected output can match
573 any substring in the actual output. This includes substrings that span line
574 boundaries, and empty substrings, so it's best to keep usage of this simple.
575 Complicated uses can lead to the same kinds of "oops, it matched too much!"
576 surprises that ``.*`` is prone to in regular expressions.
577
578
579 .. data:: IGNORE_EXCEPTION_DETAIL
580
581 When specified, an example that expects an exception passes if an exception of
582 the expected type is raised, even if the exception detail does not match. For
583 example, an example expecting ``ValueError: 42`` will pass if the actual
584 exception raised is ``ValueError: 3*14``, but will fail, e.g., if
585 :exc:`TypeError` is raised.
586
587 It will also ignore the module name used in Python 3 doctest reports. Hence
588 both of these variations will work with the flag specified, regardless of
589 whether the test is run under Python 2.7 or Python 3.2 (or later versions)::
590
591 >>> raise CustomError('message')
592 Traceback (most recent call last):
593 CustomError: message
594
595 >>> raise CustomError('message')
596 Traceback (most recent call last):
597 my_module.CustomError: message
598
599 Note that :const:`ELLIPSIS` can also be used to ignore the
600 details of the exception message, but such a test may still fail based
601 on whether or not the module details are printed as part of the
602 exception name. Using :const:`IGNORE_EXCEPTION_DETAIL` and the details
603 from Python 2.3 is also the only clear way to write a doctest that doesn't
604 care about the exception detail yet continues to pass under Python 2.3 or
605 earlier (those releases do not support :ref:`doctest directives
606 <doctest-directives>` and ignore them as irrelevant comments). For example::
607
608 >>> (1, 2)[3] = 'moo'
609 Traceback (most recent call last):
610 File "<stdin>", line 1, in <module>
611 TypeError: object doesn't support item assignment
612
613 passes under Python 2.3 and later Python versions with the flag specified,
614 even though the detail
615 changed in Python 2.4 to say "does not" instead of "doesn't".
616
617 .. versionchanged:: 2.7
618 :const:`IGNORE_EXCEPTION_DETAIL` now also ignores any information
619 relating to the module containing the exception under test
620
621
622 .. data:: SKIP
623
624 When specified, do not run the example at all. This can be useful in contexts
625 where doctest examples serve as both documentation and test cases, and an
626 example should be included for documentation purposes, but should not be
627 checked. E.g., the example's output might be random; or the example might
628 depend on resources which would be unavailable to the test driver.
629
630 The SKIP flag can also be used for temporarily "commenting out" examples.
631
632 .. versionadded:: 2.5
633
634
635 .. data:: COMPARISON_FLAGS
636
637 A bitmask or'ing together all the comparison flags above.
638
639 The second group of options controls how test failures are reported:
640
641
642 .. data:: REPORT_UDIFF
643
644 When specified, failures that involve multi-line expected and actual outputs are
645 displayed using a unified diff.
646
647
648 .. data:: REPORT_CDIFF
649
650 When specified, failures that involve multi-line expected and actual outputs
651 will be displayed using a context diff.
652
653
654 .. data:: REPORT_NDIFF
655
656 When specified, differences are computed by ``difflib.Differ``, using the same
657 algorithm as the popular :file:`ndiff.py` utility. This is the only method that
658 marks differences within lines as well as across lines. For example, if a line
659 of expected output contains digit ``1`` where actual output contains letter
660 ``l``, a line is inserted with a caret marking the mismatching column positions.
661
662
663 .. data:: REPORT_ONLY_FIRST_FAILURE
664
665 When specified, display the first failing example in each doctest, but suppress
666 output for all remaining examples. This will prevent doctest from reporting
667 correct examples that break because of earlier failures; but it might also hide
668 incorrect examples that fail independently of the first failure. When
669 :const:`REPORT_ONLY_FIRST_FAILURE` is specified, the remaining examples are
670 still run, and still count towards the total number of failures reported; only
671 the output is suppressed.
672
673
674 .. data:: REPORTING_FLAGS
675
676 A bitmask or'ing together all the reporting flags above.
677
678
679 .. versionadded:: 2.4
680 The constants
681 :const:`DONT_ACCEPT_BLANKLINE`, :const:`NORMALIZE_WHITESPACE`,
682 :const:`ELLIPSIS`, :const:`IGNORE_EXCEPTION_DETAIL`, :const:`REPORT_UDIFF`,
683 :const:`REPORT_CDIFF`, :const:`REPORT_NDIFF`,
684 :const:`REPORT_ONLY_FIRST_FAILURE`, :const:`COMPARISON_FLAGS` and
685 :const:`REPORTING_FLAGS` were added.
686
687 There's also a way to register new option flag names, although this isn't useful
688 unless you intend to extend :mod:`doctest` internals via subclassing:
689
690
691 .. function:: register_optionflag(name)
692
693 Create a new option flag with a given name, and return the new flag's integer
694 value. :func:`register_optionflag` can be used when subclassing
695 :class:`OutputChecker` or :class:`DocTestRunner` to create new options that are
696 supported by your subclasses. :func:`register_optionflag` should always be
697 called using the following idiom::
698
699 MY_FLAG = register_optionflag('MY_FLAG')
700
701 .. versionadded:: 2.4
702
703
704 .. _doctest-directives:
705
706 Directives
707 ^^^^^^^^^^
708
709 Doctest directives may be used to modify the :ref:`option flags
710 <doctest-options>` for an individual example. Doctest directives are
711 special Python comments following an example's source code:
712
713 .. productionlist:: doctest
714 directive: "#" "doctest:" `directive_options`
715 directive_options: `directive_option` ("," `directive_option`)\*
716 directive_option: `on_or_off` `directive_option_name`
717 on_or_off: "+" \| "-"
718 directive_option_name: "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...
719
720 Whitespace is not allowed between the ``+`` or ``-`` and the directive option
721 name. The directive option name can be any of the option flag names explained
722 above.
723
724 An example's doctest directives modify doctest's behavior for that single
725 example. Use ``+`` to enable the named behavior, or ``-`` to disable it.
726
727 For example, this test passes::
728
729 >>> print range(20) # doctest: +NORMALIZE_WHITESPACE
730 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
731 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
732
733 Without the directive it would fail, both because the actual output doesn't have
734 two blanks before the single-digit list elements, and because the actual output
735 is on a single line. This test also passes, and also requires a directive to do
736 so::
737
738 >>> print range(20) # doctest: +ELLIPSIS
739 [0, 1, ..., 18, 19]
740
741 Multiple directives can be used on a single physical line, separated by
742 commas::
743
744 >>> print range(20) # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
745 [0, 1, ..., 18, 19]
746
747 If multiple directive comments are used for a single example, then they are
748 combined::
749
750 >>> print range(20) # doctest: +ELLIPSIS
751 ... # doctest: +NORMALIZE_WHITESPACE
752 [0, 1, ..., 18, 19]
753
754 As the previous example shows, you can add ``...`` lines to your example
755 containing only directives. This can be useful when an example is too long for
756 a directive to comfortably fit on the same line::
757
758 >>> print range(5) + range(10,20) + range(30,40) + range(50,60)
759 ... # doctest: +ELLIPSIS
760 [0, ..., 4, 10, ..., 19, 30, ..., 39, 50, ..., 59]
761
762 Note that since all options are disabled by default, and directives apply only
763 to the example they appear in, enabling options (via ``+`` in a directive) is
764 usually the only meaningful choice. However, option flags can also be passed to
765 functions that run doctests, establishing different defaults. In such cases,
766 disabling an option via ``-`` in a directive can be useful.
767
768 .. versionadded:: 2.4
769 Support for doctest directives was added.
770
771
772 .. _doctest-warnings:
773
774 Warnings
775 ^^^^^^^^
776
777 :mod:`doctest` is serious about requiring exact matches in expected output. If
778 even a single character doesn't match, the test fails. This will probably
779 surprise you a few times, as you learn exactly what Python does and doesn't
780 guarantee about output. For example, when printing a dict, Python doesn't
781 guarantee that the key-value pairs will be printed in any particular order, so a
782 test like ::
783
784 >>> foo()
785 {"Hermione": "hippogryph", "Harry": "broomstick"}
786
787 is vulnerable! One workaround is to do ::
788
789 >>> foo() == {"Hermione": "hippogryph", "Harry": "broomstick"}
790 True
791
792 instead. Another is to do ::
793
794 >>> d = foo().items()
795 >>> d.sort()
796 >>> d
797 [('Harry', 'broomstick'), ('Hermione', 'hippogryph')]
798
799 There are others, but you get the idea.
800
801 Another bad idea is to print things that embed an object address, like ::
802
803 >>> id(1.0) # certain to fail some of the time
804 7948648
805 >>> class C: pass
806 >>> C() # the default repr() for instances embeds an address
807 <__main__.C instance at 0x00AC18F0>
808
809 The :const:`ELLIPSIS` directive gives a nice approach for the last example::
810
811 >>> C() #doctest: +ELLIPSIS
812 <__main__.C instance at 0x...>
813
814 Floating-point numbers are also subject to small output variations across
815 platforms, because Python defers to the platform C library for float formatting,
816 and C libraries vary widely in quality here. ::
817
818 >>> 1./7 # risky
819 0.14285714285714285
820 >>> print 1./7 # safer
821 0.142857142857
822 >>> print round(1./7, 6) # much safer
823 0.142857
824
825 Numbers of the form ``I/2.**J`` are safe across all platforms, and I often
826 contrive doctest examples to produce numbers of that form::
827
828 >>> 3./4 # utterly safe
829 0.75
830
831 Simple fractions are also easier for people to understand, and that makes for
832 better documentation.
833
834
835 .. _doctest-basic-api:
836
837 Basic API
838 ---------
839
840 The functions :func:`testmod` and :func:`testfile` provide a simple interface to
841 doctest that should be sufficient for most basic uses. For a less formal
842 introduction to these two functions, see sections :ref:`doctest-simple-testmod`
843 and :ref:`doctest-simple-testfile`.
844
845
846 .. function:: testfile(filename[, module_relative][, name][, package][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, parser][, encoding])
847
848 All arguments except *filename* are optional, and should be specified in keyword
849 form.
850
851 Test examples in the file named *filename*. Return ``(failure_count,
852 test_count)``.
853
854 Optional argument *module_relative* specifies how the filename should be
855 interpreted:
856
857 * If *module_relative* is ``True`` (the default), then *filename* specifies an
858 OS-independent module-relative path. By default, this path is relative to the
859 calling module's directory; but if the *package* argument is specified, then it
860 is relative to that package. To ensure OS-independence, *filename* should use
861 ``/`` characters to separate path segments, and may not be an absolute path
862 (i.e., it may not begin with ``/``).
863
864 * If *module_relative* is ``False``, then *filename* specifies an OS-specific
865 path. The path may be absolute or relative; relative paths are resolved with
866 respect to the current working directory.
867
868 Optional argument *name* gives the name of the test; by default, or if ``None``,
869 ``os.path.basename(filename)`` is used.
870
871 Optional argument *package* is a Python package or the name of a Python package
872 whose directory should be used as the base directory for a module-relative
873 filename. If no package is specified, then the calling module's directory is
874 used as the base directory for module-relative filenames. It is an error to
875 specify *package* if *module_relative* is ``False``.
876
877 Optional argument *globs* gives a dict to be used as the globals when executing
878 examples. A new shallow copy of this dict is created for the doctest, so its
879 examples start with a clean slate. By default, or if ``None``, a new empty dict
880 is used.
881
882 Optional argument *extraglobs* gives a dict merged into the globals used to
883 execute examples. This works like :meth:`dict.update`: if *globs* and
884 *extraglobs* have a common key, the associated value in *extraglobs* appears in
885 the combined dict. By default, or if ``None``, no extra globals are used. This
886 is an advanced feature that allows parameterization of doctests. For example, a
887 doctest can be written for a base class, using a generic name for the class,
888 then reused to test any number of subclasses by passing an *extraglobs* dict
889 mapping the generic name to the subclass to be tested.
890
891 Optional argument *verbose* prints lots of stuff if true, and prints only
892 failures if false; by default, or if ``None``, it's true if and only if ``'-v'``
893 is in ``sys.argv``.
894
895 Optional argument *report* prints a summary at the end when true, else prints
896 nothing at the end. In verbose mode, the summary is detailed, else the summary
897 is very brief (in fact, empty if all tests passed).
898
899 Optional argument *optionflags* or's together option flags. See section
900 :ref:`doctest-options`.
901
902 Optional argument *raise_on_error* defaults to false. If true, an exception is
903 raised upon the first failure or unexpected exception in an example. This
904 allows failures to be post-mortem debugged. Default behavior is to continue
905 running examples.
906
907 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass) that
908 should be used to extract tests from the files. It defaults to a normal parser
909 (i.e., ``DocTestParser()``).
910
911 Optional argument *encoding* specifies an encoding that should be used to
912 convert the file to unicode.
913
914 .. versionadded:: 2.4
915
916 .. versionchanged:: 2.5
917 The parameter *encoding* was added.
918
919
920 .. function:: testmod([m][, name][, globs][, verbose][, report][, optionflags][, extraglobs][, raise_on_error][, exclude_empty])
921
922 All arguments are optional, and all except for *m* should be specified in
923 keyword form.
924
925 Test examples in docstrings in functions and classes reachable from module *m*
926 (or module :mod:`__main__` if *m* is not supplied or is ``None``), starting with
927 ``m.__doc__``.
928
929 Also test examples reachable from dict ``m.__test__``, if it exists and is not
930 ``None``. ``m.__test__`` maps names (strings) to functions, classes and
931 strings; function and class docstrings are searched for examples; strings are
932 searched directly, as if they were docstrings.
933
934 Only docstrings attached to objects belonging to module *m* are searched.
935
936 Return ``(failure_count, test_count)``.
937
938 Optional argument *name* gives the name of the module; by default, or if
939 ``None``, ``m.__name__`` is used.
940
941 Optional argument *exclude_empty* defaults to false. If true, objects for which
942 no doctests are found are excluded from consideration. The default is a backward
943 compatibility hack, so that code still using :meth:`doctest.master.summarize` in
944 conjunction with :func:`testmod` continues to get output for objects with no
945 tests. The *exclude_empty* argument to the newer :class:`DocTestFinder`
946 constructor defaults to true.
947
948 Optional arguments *extraglobs*, *verbose*, *report*, *optionflags*,
949 *raise_on_error*, and *globs* are the same as for function :func:`testfile`
950 above, except that *globs* defaults to ``m.__dict__``.
951
952 .. versionchanged:: 2.3
953 The parameter *optionflags* was added.
954
955 .. versionchanged:: 2.4
956 The parameters *extraglobs*, *raise_on_error* and *exclude_empty* were added.
957
958 .. versionchanged:: 2.5
959 The optional argument *isprivate*, deprecated in 2.4, was removed.
960
961
962 .. function:: run_docstring_examples(f, globs[, verbose][, name][, compileflags][, optionflags])
963
964 Test examples associated with object *f*; for example, *f* may be a string,
965 a module, a function, or a class object.
966
967 A shallow copy of dictionary argument *globs* is used for the execution context.
968
969 Optional argument *name* is used in failure messages, and defaults to
970 ``"NoName"``.
971
972 If optional argument *verbose* is true, output is generated even if there are no
973 failures. By default, output is generated only in case of an example failure.
974
975 Optional argument *compileflags* gives the set of flags that should be used by
976 the Python compiler when running the examples. By default, or if ``None``,
977 flags are deduced corresponding to the set of future features found in *globs*.
978
979 Optional argument *optionflags* works as for function :func:`testfile` above.
980
981
982 .. _doctest-unittest-api:
983
984 Unittest API
985 ------------
986
987 As your collection of doctest'ed modules grows, you'll want a way to run all
988 their doctests systematically. Prior to Python 2.4, :mod:`doctest` had a barely
989 documented :class:`Tester` class that supplied a rudimentary way to combine
990 doctests from multiple modules. :class:`Tester` was feeble, and in practice most
991 serious Python testing frameworks build on the :mod:`unittest` module, which
992 supplies many flexible ways to combine tests from multiple sources. So, in
993 Python 2.4, :mod:`doctest`'s :class:`Tester` class is deprecated, and
994 :mod:`doctest` provides two functions that can be used to create :mod:`unittest`
995 test suites from modules and text files containing doctests. To integrate with
996 :mod:`unittest` test discovery, include a :func:`load_tests` function in your
997 test module::
998
999 import unittest
1000 import doctest
1001 import my_module_with_doctests
1002
1003 def load_tests(loader, tests, ignore):
1004 tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
1005 return tests
1006
1007 There are two main functions for creating :class:`unittest.TestSuite` instances
1008 from text files and modules with doctests:
1009
1010
1011 .. function:: DocFileSuite(*paths, [module_relative][, package][, setUp][, tearDown][, globs][, optionflags][, parser][, encoding])
1012
1013 Convert doctest tests from one or more text files to a
1014 :class:`unittest.TestSuite`.
1015
1016 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
1017 and runs the interactive examples in each file. If an example in any file
1018 fails, then the synthesized unit test fails, and a :exc:`failureException`
1019 exception is raised showing the name of the file containing the test and a
1020 (sometimes approximate) line number.
1021
1022 Pass one or more paths (as strings) to text files to be examined.
1023
1024 Options may be provided as keyword arguments:
1025
1026 Optional argument *module_relative* specifies how the filenames in *paths*
1027 should be interpreted:
1028
1029 * If *module_relative* is ``True`` (the default), then each filename in
1030 *paths* specifies an OS-independent module-relative path. By default, this
1031 path is relative to the calling module's directory; but if the *package*
1032 argument is specified, then it is relative to that package. To ensure
1033 OS-independence, each filename should use ``/`` characters to separate path
1034 segments, and may not be an absolute path (i.e., it may not begin with
1035 ``/``).
1036
1037 * If *module_relative* is ``False``, then each filename in *paths* specifies
1038 an OS-specific path. The path may be absolute or relative; relative paths
1039 are resolved with respect to the current working directory.
1040
1041 Optional argument *package* is a Python package or the name of a Python
1042 package whose directory should be used as the base directory for
1043 module-relative filenames in *paths*. If no package is specified, then the
1044 calling module's directory is used as the base directory for module-relative
1045 filenames. It is an error to specify *package* if *module_relative* is
1046 ``False``.
1047
1048 Optional argument *setUp* specifies a set-up function for the test suite.
1049 This is called before running the tests in each file. The *setUp* function
1050 will be passed a :class:`DocTest` object. The setUp function can access the
1051 test globals as the *globs* attribute of the test passed.
1052
1053 Optional argument *tearDown* specifies a tear-down function for the test
1054 suite. This is called after running the tests in each file. The *tearDown*
1055 function will be passed a :class:`DocTest` object. The setUp function can
1056 access the test globals as the *globs* attribute of the test passed.
1057
1058 Optional argument *globs* is a dictionary containing the initial global
1059 variables for the tests. A new copy of this dictionary is created for each
1060 test. By default, *globs* is a new empty dictionary.
1061
1062 Optional argument *optionflags* specifies the default doctest options for the
1063 tests, created by or-ing together individual option flags. See section
1064 :ref:`doctest-options`. See function :func:`set_unittest_reportflags` below
1065 for a better way to set reporting options.
1066
1067 Optional argument *parser* specifies a :class:`DocTestParser` (or subclass)
1068 that should be used to extract tests from the files. It defaults to a normal
1069 parser (i.e., ``DocTestParser()``).
1070
1071 Optional argument *encoding* specifies an encoding that should be used to
1072 convert the file to unicode.
1073
1074 .. versionadded:: 2.4
1075
1076 .. versionchanged:: 2.5
1077 The global ``__file__`` was added to the globals provided to doctests
1078 loaded from a text file using :func:`DocFileSuite`.
1079
1080 .. versionchanged:: 2.5
1081 The parameter *encoding* was added.
1082
1083 .. note::
1084 Unlike :func:`testmod` and :class:`DocTestFinder`, this function raises
1085 a :exc:`ValueError` if *module* contains no docstrings. You can prevent
1086 this error by passing a :class:`DocTestFinder` instance as the
1087 *test_finder* argument with its *exclude_empty* keyword argument set
1088 to ``False``::
1089
1090 >>> finder = doctest.DocTestFinder(exclude_empty=False)
1091 >>> suite = doctest.DocTestSuite(test_finder=finder)
1092
1093
1094 .. function:: DocTestSuite([module][, globs][, extraglobs][, test_finder][, setUp][, tearDown][, checker])
1095
1096 Convert doctest tests for a module to a :class:`unittest.TestSuite`.
1097
1098 The returned :class:`unittest.TestSuite` is to be run by the unittest framework
1099 and runs each doctest in the module. If any of the doctests fail, then the
1100 synthesized unit test fails, and a :exc:`failureException` exception is raised
1101 showing the name of the file containing the test and a (sometimes approximate)
1102 line number.
1103
1104 Optional argument *module* provides the module to be tested. It can be a module
1105 object or a (possibly dotted) module name. If not specified, the module calling
1106 this function is used.
1107
1108 Optional argument *globs* is a dictionary containing the initial global
1109 variables for the tests. A new copy of this dictionary is created for each
1110 test. By default, *globs* is a new empty dictionary.
1111
1112 Optional argument *extraglobs* specifies an extra set of global variables, which
1113 is merged into *globs*. By default, no extra globals are used.
1114
1115 Optional argument *test_finder* is the :class:`DocTestFinder` object (or a
1116 drop-in replacement) that is used to extract doctests from the module.
1117
1118 Optional arguments *setUp*, *tearDown*, and *optionflags* are the same as for
1119 function :func:`DocFileSuite` above.
1120
1121 .. versionadded:: 2.3
1122
1123 .. versionchanged:: 2.4
1124 The parameters *globs*, *extraglobs*, *test_finder*, *setUp*, *tearDown*, and
1125 *optionflags* were added; this function now uses the same search technique as
1126 :func:`testmod`.
1127
1128 Under the covers, :func:`DocTestSuite` creates a :class:`unittest.TestSuite` out
1129 of :class:`doctest.DocTestCase` instances, and :class:`DocTestCase` is a
1130 subclass of :class:`unittest.TestCase`. :class:`DocTestCase` isn't documented
1131 here (it's an internal detail), but studying its code can answer questions about
1132 the exact details of :mod:`unittest` integration.
1133
1134 Similarly, :func:`DocFileSuite` creates a :class:`unittest.TestSuite` out of
1135 :class:`doctest.DocFileCase` instances, and :class:`DocFileCase` is a subclass
1136 of :class:`DocTestCase`.
1137
1138 So both ways of creating a :class:`unittest.TestSuite` run instances of
1139 :class:`DocTestCase`. This is important for a subtle reason: when you run
1140 :mod:`doctest` functions yourself, you can control the :mod:`doctest` options in
1141 use directly, by passing option flags to :mod:`doctest` functions. However, if
1142 you're writing a :mod:`unittest` framework, :mod:`unittest` ultimately controls
1143 when and how tests get run. The framework author typically wants to control
1144 :mod:`doctest` reporting options (perhaps, e.g., specified by command line
1145 options), but there's no way to pass options through :mod:`unittest` to
1146 :mod:`doctest` test runners.
1147
1148 For this reason, :mod:`doctest` also supports a notion of :mod:`doctest`
1149 reporting flags specific to :mod:`unittest` support, via this function:
1150
1151
1152 .. function:: set_unittest_reportflags(flags)
1153
1154 Set the :mod:`doctest` reporting flags to use.
1155
1156 Argument *flags* or's together option flags. See section
1157 :ref:`doctest-options`. Only "reporting flags" can be used.
1158
1159 This is a module-global setting, and affects all future doctests run by module
1160 :mod:`unittest`: the :meth:`runTest` method of :class:`DocTestCase` looks at
1161 the option flags specified for the test case when the :class:`DocTestCase`
1162 instance was constructed. If no reporting flags were specified (which is the
1163 typical and expected case), :mod:`doctest`'s :mod:`unittest` reporting flags are
1164 :ref:`bitwise ORed <bitwise>` into the option flags, and the option flags
1165 so augmented are passed to the :class:`DocTestRunner` instance created to
1166 run the doctest. If any reporting flags were specified when the
1167 :class:`DocTestCase` instance was constructed, :mod:`doctest`'s
1168 :mod:`unittest` reporting flags are ignored.
1169
1170 The value of the :mod:`unittest` reporting flags in effect before the function
1171 was called is returned by the function.
1172
1173 .. versionadded:: 2.4
1174
1175
1176 .. _doctest-advanced-api:
1177
1178 Advanced API
1179 ------------
1180
1181 The basic API is a simple wrapper that's intended to make doctest easy to use.
1182 It is fairly flexible, and should meet most users' needs; however, if you
1183 require more fine-grained control over testing, or wish to extend doctest's
1184 capabilities, then you should use the advanced API.
1185
1186 The advanced API revolves around two container classes, which are used to store
1187 the interactive examples extracted from doctest cases:
1188
1189 * :class:`Example`: A single Python :term:`statement`, paired with its expected
1190 output.
1191
1192 * :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted
1193 from a single docstring or text file.
1194
1195 Additional processing classes are defined to find, parse, and run, and check
1196 doctest examples:
1197
1198 * :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a
1199 :class:`DocTestParser` to create a :class:`DocTest` from every docstring that
1200 contains interactive examples.
1201
1202 * :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such
1203 as an object's docstring).
1204
1205 * :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses
1206 an :class:`OutputChecker` to verify their output.
1207
1208 * :class:`OutputChecker`: Compares the actual output from a doctest example with
1209 the expected output, and decides whether they match.
1210
1211 The relationships among these processing classes are summarized in the following
1212 diagram::
1213
1214 list of:
1215 +------+ +---------+
1216 |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results
1217 +------+ | ^ +---------+ | ^ (printed)
1218 | | | Example | | |
1219 v | | ... | v |
1220 DocTestParser | Example | OutputChecker
1221 +---------+
1222
1223
1224 .. _doctest-doctest:
1225
1226 DocTest Objects
1227 ^^^^^^^^^^^^^^^
1228
1229
1230 .. class:: DocTest(examples, globs, name, filename, lineno, docstring)
1231
1232 A collection of doctest examples that should be run in a single namespace. The
1233 constructor arguments are used to initialize the attributes of the same names.
1234
1235 .. versionadded:: 2.4
1236
1237 :class:`DocTest` defines the following attributes. They are initialized by
1238 the constructor, and should not be modified directly.
1239
1240
1241 .. attribute:: examples
1242
1243 A list of :class:`Example` objects encoding the individual interactive Python
1244 examples that should be run by this test.
1245
1246
1247 .. attribute:: globs
1248
1249 The namespace (aka globals) that the examples should be run in. This is a
1250 dictionary mapping names to values. Any changes to the namespace made by the
1251 examples (such as binding new variables) will be reflected in :attr:`globs`
1252 after the test is run.
1253
1254
1255 .. attribute:: name
1256
1257 A string name identifying the :class:`DocTest`. Typically, this is the name
1258 of the object or file that the test was extracted from.
1259
1260
1261 .. attribute:: filename
1262
1263 The name of the file that this :class:`DocTest` was extracted from; or
1264 ``None`` if the filename is unknown, or if the :class:`DocTest` was not
1265 extracted from a file.
1266
1267
1268 .. attribute:: lineno
1269
1270 The line number within :attr:`filename` where this :class:`DocTest` begins, or
1271 ``None`` if the line number is unavailable. This line number is zero-based
1272 with respect to the beginning of the file.
1273
1274
1275 .. attribute:: docstring
1276
1277 The string that the test was extracted from, or ``None`` if the string is
1278 unavailable, or if the test was not extracted from a string.
1279
1280
1281 .. _doctest-example:
1282
1283 Example Objects
1284 ^^^^^^^^^^^^^^^
1285
1286
1287 .. class:: Example(source, want[, exc_msg][, lineno][, indent][, options])
1288
1289 A single interactive example, consisting of a Python statement and its expected
1290 output. The constructor arguments are used to initialize the attributes of the
1291 same names.
1292
1293 .. versionadded:: 2.4
1294
1295 :class:`Example` defines the following attributes. They are initialized by
1296 the constructor, and should not be modified directly.
1297
1298
1299 .. attribute:: source
1300
1301 A string containing the example's source code. This source code consists of a
1302 single Python statement, and always ends with a newline; the constructor adds
1303 a newline when necessary.
1304
1305
1306 .. attribute:: want
1307
1308 The expected output from running the example's source code (either from
1309 stdout, or a traceback in case of exception). :attr:`want` ends with a
1310 newline unless no output is expected, in which case it's an empty string. The
1311 constructor adds a newline when necessary.
1312
1313
1314 .. attribute:: exc_msg
1315
1316 The exception message generated by the example, if the example is expected to
1317 generate an exception; or ``None`` if it is not expected to generate an
1318 exception. This exception message is compared against the return value of
1319 :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline
1320 unless it's ``None``. The constructor adds a newline if needed.
1321
1322
1323 .. attribute:: lineno
1324
1325 The line number within the string containing this example where the example
1326 begins. This line number is zero-based with respect to the beginning of the
1327 containing string.
1328
1329
1330 .. attribute:: indent
1331
1332 The example's indentation in the containing string, i.e., the number of space
1333 characters that precede the example's first prompt.
1334
1335
1336 .. attribute:: options
1337
1338 A dictionary mapping from option flags to ``True`` or ``False``, which is used
1339 to override default options for this example. Any option flags not contained
1340 in this dictionary are left at their default value (as specified by the
1341 :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set.
1342
1343
1344 .. _doctest-doctestfinder:
1345
1346 DocTestFinder objects
1347 ^^^^^^^^^^^^^^^^^^^^^
1348
1349
1350 .. class:: DocTestFinder([verbose][, parser][, recurse][, exclude_empty])
1351
1352 A processing class used to extract the :class:`DocTest`\ s that are relevant to
1353 a given object, from its docstring and the docstrings of its contained objects.
1354 :class:`DocTest`\ s can currently be extracted from the following object types:
1355 modules, functions, classes, methods, staticmethods, classmethods, and
1356 properties.
1357
1358 The optional argument *verbose* can be used to display the objects searched by
1359 the finder. It defaults to ``False`` (no output).
1360
1361 The optional argument *parser* specifies the :class:`DocTestParser` object (or a
1362 drop-in replacement) that is used to extract doctests from docstrings.
1363
1364 If the optional argument *recurse* is false, then :meth:`DocTestFinder.find`
1365 will only examine the given object, and not any contained objects.
1366
1367 If the optional argument *exclude_empty* is false, then
1368 :meth:`DocTestFinder.find` will include tests for objects with empty docstrings.
1369
1370 .. versionadded:: 2.4
1371
1372 :class:`DocTestFinder` defines the following method:
1373
1374
1375 .. method:: find(obj[, name][, module][, globs][, extraglobs])
1376
1377 Return a list of the :class:`DocTest`\ s that are defined by *obj*'s
1378 docstring, or by any of its contained objects' docstrings.
1379
1380 The optional argument *name* specifies the object's name; this name will be
1381 used to construct names for the returned :class:`DocTest`\ s. If *name* is
1382 not specified, then ``obj.__name__`` is used.
1383
1384 The optional parameter *module* is the module that contains the given object.
1385 If the module is not specified or is ``None``, then the test finder will attempt
1386 to automatically determine the correct module. The object's module is used:
1387
1388 * As a default namespace, if *globs* is not specified.
1389
1390 * To prevent the DocTestFinder from extracting DocTests from objects that are
1391 imported from other modules. (Contained objects with modules other than
1392 *module* are ignored.)
1393
1394 * To find the name of the file containing the object.
1395
1396 * To help find the line number of the object within its file.
1397
1398 If *module* is ``False``, no attempt to find the module will be made. This is
1399 obscure, of use mostly in testing doctest itself: if *module* is ``False``, or
1400 is ``None`` but cannot be found automatically, then all objects are considered
1401 to belong to the (non-existent) module, so all contained objects will
1402 (recursively) be searched for doctests.
1403
1404 The globals for each :class:`DocTest` is formed by combining *globs* and
1405 *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new
1406 shallow copy of the globals dictionary is created for each :class:`DocTest`.
1407 If *globs* is not specified, then it defaults to the module's *__dict__*, if
1408 specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it
1409 defaults to ``{}``.
1410
1411
1412 .. _doctest-doctestparser:
1413
1414 DocTestParser objects
1415 ^^^^^^^^^^^^^^^^^^^^^
1416
1417
1418 .. class:: DocTestParser()
1419
1420 A processing class used to extract interactive examples from a string, and use
1421 them to create a :class:`DocTest` object.
1422
1423 .. versionadded:: 2.4
1424
1425 :class:`DocTestParser` defines the following methods:
1426
1427
1428 .. method:: get_doctest(string, globs, name, filename, lineno)
1429
1430 Extract all doctest examples from the given string, and collect them into a
1431 :class:`DocTest` object.
1432
1433 *globs*, *name*, *filename*, and *lineno* are attributes for the new
1434 :class:`DocTest` object. See the documentation for :class:`DocTest` for more
1435 information.
1436
1437
1438 .. method:: get_examples(string[, name])
1439
1440 Extract all doctest examples from the given string, and return them as a list
1441 of :class:`Example` objects. Line numbers are 0-based. The optional argument
1442 *name* is a name identifying this string, and is only used for error messages.
1443
1444
1445 .. method:: parse(string[, name])
1446
1447 Divide the given string into examples and intervening text, and return them as
1448 a list of alternating :class:`Example`\ s and strings. Line numbers for the
1449 :class:`Example`\ s are 0-based. The optional argument *name* is a name
1450 identifying this string, and is only used for error messages.
1451
1452
1453 .. _doctest-doctestrunner:
1454
1455 DocTestRunner objects
1456 ^^^^^^^^^^^^^^^^^^^^^
1457
1458
1459 .. class:: DocTestRunner([checker][, verbose][, optionflags])
1460
1461 A processing class used to execute and verify the interactive examples in a
1462 :class:`DocTest`.
1463
1464 The comparison between expected outputs and actual outputs is done by an
1465 :class:`OutputChecker`. This comparison may be customized with a number of
1466 option flags; see section :ref:`doctest-options` for more information. If the
1467 option flags are insufficient, then the comparison may also be customized by
1468 passing a subclass of :class:`OutputChecker` to the constructor.
1469
1470 The test runner's display output can be controlled in two ways. First, an output
1471 function can be passed to :meth:`TestRunner.run`; this function will be called
1472 with strings that should be displayed. It defaults to ``sys.stdout.write``. If
1473 capturing the output is not sufficient, then the display output can be also
1474 customized by subclassing DocTestRunner, and overriding the methods
1475 :meth:`report_start`, :meth:`report_success`,
1476 :meth:`report_unexpected_exception`, and :meth:`report_failure`.
1477
1478 The optional keyword argument *checker* specifies the :class:`OutputChecker`
1479 object (or drop-in replacement) that should be used to compare the expected
1480 outputs to the actual outputs of doctest examples.
1481
1482 The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s
1483 verbosity. If *verbose* is ``True``, then information is printed about each
1484 example, as it is run. If *verbose* is ``False``, then only failures are
1485 printed. If *verbose* is unspecified, or ``None``, then verbose output is used
1486 iff the command-line switch ``-v`` is used.
1487
1488 The optional keyword argument *optionflags* can be used to control how the test
1489 runner compares expected output to actual output, and how it displays failures.
1490 For more information, see section :ref:`doctest-options`.
1491
1492 .. versionadded:: 2.4
1493
1494 :class:`DocTestParser` defines the following methods:
1495
1496
1497 .. method:: report_start(out, test, example)
1498
1499 Report that the test runner is about to process the given example. This method
1500 is provided to allow subclasses of :class:`DocTestRunner` to customize their
1501 output; it should not be called directly.
1502
1503 *example* is the example about to be processed. *test* is the test
1504 *containing example*. *out* is the output function that was passed to
1505 :meth:`DocTestRunner.run`.
1506
1507
1508 .. method:: report_success(out, test, example, got)
1509
1510 Report that the given example ran successfully. This method is provided to
1511 allow subclasses of :class:`DocTestRunner` to customize their output; it
1512 should not be called directly.
1513
1514 *example* is the example about to be processed. *got* is the actual output
1515 from the example. *test* is the test containing *example*. *out* is the
1516 output function that was passed to :meth:`DocTestRunner.run`.
1517
1518
1519 .. method:: report_failure(out, test, example, got)
1520
1521 Report that the given example failed. This method is provided to allow
1522 subclasses of :class:`DocTestRunner` to customize their output; it should not
1523 be called directly.
1524
1525 *example* is the example about to be processed. *got* is the actual output
1526 from the example. *test* is the test containing *example*. *out* is the
1527 output function that was passed to :meth:`DocTestRunner.run`.
1528
1529
1530 .. method:: report_unexpected_exception(out, test, example, exc_info)
1531
1532 Report that the given example raised an unexpected exception. This method is
1533 provided to allow subclasses of :class:`DocTestRunner` to customize their
1534 output; it should not be called directly.
1535
1536 *example* is the example about to be processed. *exc_info* is a tuple
1537 containing information about the unexpected exception (as returned by
1538 :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the
1539 output function that was passed to :meth:`DocTestRunner.run`.
1540
1541
1542 .. method:: run(test[, compileflags][, out][, clear_globs])
1543
1544 Run the examples in *test* (a :class:`DocTest` object), and display the
1545 results using the writer function *out*.
1546
1547 The examples are run in the namespace ``test.globs``. If *clear_globs* is
1548 true (the default), then this namespace will be cleared after the test runs,
1549 to help with garbage collection. If you would like to examine the namespace
1550 after the test completes, then use *clear_globs=False*.
1551
1552 *compileflags* gives the set of flags that should be used by the Python
1553 compiler when running the examples. If not specified, then it will default to
1554 the set of future-import flags that apply to *globs*.
1555
1556 The output of each example is checked using the :class:`DocTestRunner`'s
1557 output checker, and the results are formatted by the
1558 :meth:`DocTestRunner.report_\*` methods.
1559
1560
1561 .. method:: summarize([verbose])
1562
1563 Print a summary of all the test cases that have been run by this DocTestRunner,
1564 and return a :term:`named tuple` ``TestResults(failed, attempted)``.
1565
1566 The optional *verbose* argument controls how detailed the summary is. If the
1567 verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is
1568 used.
1569
1570 .. versionchanged:: 2.6
1571 Use a named tuple.
1572
1573
1574 .. _doctest-outputchecker:
1575
1576 OutputChecker objects
1577 ^^^^^^^^^^^^^^^^^^^^^
1578
1579
1580 .. class:: OutputChecker()
1581
1582 A class used to check the whether the actual output from a doctest example
1583 matches the expected output. :class:`OutputChecker` defines two methods:
1584 :meth:`check_output`, which compares a given pair of outputs, and returns true
1585 if they match; and :meth:`output_difference`, which returns a string describing
1586 the differences between two outputs.
1587
1588 .. versionadded:: 2.4
1589
1590 :class:`OutputChecker` defines the following methods:
1591
1592
1593 .. method:: check_output(want, got, optionflags)
1594
1595 Return ``True`` iff the actual output from an example (*got*) matches the
1596 expected output (*want*). These strings are always considered to match if
1597 they are identical; but depending on what option flags the test runner is
1598 using, several non-exact match types are also possible. See section
1599 :ref:`doctest-options` for more information about option flags.
1600
1601
1602 .. method:: output_difference(example, got, optionflags)
1603
1604 Return a string describing the differences between the expected output for a
1605 given example (*example*) and the actual output (*got*). *optionflags* is the
1606 set of option flags used to compare *want* and *got*.
1607
1608
1609 .. _doctest-debugging:
1610
1611 Debugging
1612 ---------
1613
1614 Doctest provides several mechanisms for debugging doctest examples:
1615
1616 * Several functions convert doctests to executable Python programs, which can be
1617 run under the Python debugger, :mod:`pdb`.
1618
1619 * The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that
1620 raises an exception for the first failing example, containing information about
1621 that example. This information can be used to perform post-mortem debugging on
1622 the example.
1623
1624 * The :mod:`unittest` cases generated by :func:`DocTestSuite` support the
1625 :meth:`debug` method defined by :class:`unittest.TestCase`.
1626
1627 * You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll
1628 drop into the Python debugger when that line is executed. Then you can inspect
1629 current values of variables, and so on. For example, suppose :file:`a.py`
1630 contains just this module docstring::
1631
1632 """
1633 >>> def f(x):
1634 ... g(x*2)
1635 >>> def g(x):
1636 ... print x+3
1637 ... import pdb; pdb.set_trace()
1638 >>> f(3)
1639 9
1640 """
1641
1642 Then an interactive Python session may look like this::
1643
1644 >>> import a, doctest
1645 >>> doctest.testmod(a)
1646 --Return--
1647 > <doctest a[1]>(3)g()->None
1648 -> import pdb; pdb.set_trace()
1649 (Pdb) list
1650 1 def g(x):
1651 2 print x+3
1652 3 -> import pdb; pdb.set_trace()
1653 [EOF]
1654 (Pdb) print x
1655 6
1656 (Pdb) step
1657 --Return--
1658 > <doctest a[0]>(2)f()->None
1659 -> g(x*2)
1660 (Pdb) list
1661 1 def f(x):
1662 2 -> g(x*2)
1663 [EOF]
1664 (Pdb) print x
1665 3
1666 (Pdb) step
1667 --Return--
1668 > <doctest a[2]>(1)?()->None
1669 -> f(3)
1670 (Pdb) cont
1671 (0, 3)
1672 >>>
1673
1674 .. versionchanged:: 2.4
1675 The ability to use :func:`pdb.set_trace` usefully inside doctests was added.
1676
1677 Functions that convert doctests to Python code, and possibly run the synthesized
1678 code under the debugger:
1679
1680
1681 .. function:: script_from_examples(s)
1682
1683 Convert text with examples to a script.
1684
1685 Argument *s* is a string containing doctest examples. The string is converted
1686 to a Python script, where doctest examples in *s* are converted to regular code,
1687 and everything else is converted to Python comments. The generated script is
1688 returned as a string. For example, ::
1689
1690 import doctest
1691 print doctest.script_from_examples(r"""
1692 Set x and y to 1 and 2.
1693 >>> x, y = 1, 2
1694
1695 Print their sum:
1696 >>> print x+y
1697 3
1698 """)
1699
1700 displays::
1701
1702 # Set x and y to 1 and 2.
1703 x, y = 1, 2
1704 #
1705 # Print their sum:
1706 print x+y
1707 # Expected:
1708 ## 3
1709
1710 This function is used internally by other functions (see below), but can also be
1711 useful when you want to transform an interactive Python session into a Python
1712 script.
1713
1714 .. versionadded:: 2.4
1715
1716
1717 .. function:: testsource(module, name)
1718
1719 Convert the doctest for an object to a script.
1720
1721 Argument *module* is a module object, or dotted name of a module, containing the
1722 object whose doctests are of interest. Argument *name* is the name (within the
1723 module) of the object with the doctests of interest. The result is a string,
1724 containing the object's docstring converted to a Python script, as described for
1725 :func:`script_from_examples` above. For example, if module :file:`a.py`
1726 contains a top-level function :func:`f`, then ::
1727
1728 import a, doctest
1729 print doctest.testsource(a, "a.f")
1730
1731 prints a script version of function :func:`f`'s docstring, with doctests
1732 converted to code, and the rest placed in comments.
1733
1734 .. versionadded:: 2.3
1735
1736
1737 .. function:: debug(module, name[, pm])
1738
1739 Debug the doctests for an object.
1740
1741 The *module* and *name* arguments are the same as for function
1742 :func:`testsource` above. The synthesized Python script for the named object's
1743 docstring is written to a temporary file, and then that file is run under the
1744 control of the Python debugger, :mod:`pdb`.
1745
1746 A shallow copy of ``module.__dict__`` is used for both local and global
1747 execution context.
1748
1749 Optional argument *pm* controls whether post-mortem debugging is used. If *pm*
1750 has a true value, the script file is run directly, and the debugger gets
1751 involved only if the script terminates via raising an unhandled exception. If
1752 it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`,
1753 passing the traceback object from the unhandled exception. If *pm* is not
1754 specified, or is false, the script is run under the debugger from the start, via
1755 passing an appropriate :func:`execfile` call to :func:`pdb.run`.
1756
1757 .. versionadded:: 2.3
1758
1759 .. versionchanged:: 2.4
1760 The *pm* argument was added.
1761
1762
1763 .. function:: debug_src(src[, pm][, globs])
1764
1765 Debug the doctests in a string.
1766
1767 This is like function :func:`debug` above, except that a string containing
1768 doctest examples is specified directly, via the *src* argument.
1769
1770 Optional argument *pm* has the same meaning as in function :func:`debug` above.
1771
1772 Optional argument *globs* gives a dictionary to use as both local and global
1773 execution context. If not specified, or ``None``, an empty dictionary is used.
1774 If specified, a shallow copy of the dictionary is used.
1775
1776 .. versionadded:: 2.4
1777
1778 The :class:`DebugRunner` class, and the special exceptions it may raise, are of
1779 most interest to testing framework authors, and will only be sketched here. See
1780 the source code, and especially :class:`DebugRunner`'s docstring (which is a
1781 doctest!) for more details:
1782
1783
1784 .. class:: DebugRunner([checker][, verbose][, optionflags])
1785
1786 A subclass of :class:`DocTestRunner` that raises an exception as soon as a
1787 failure is encountered. If an unexpected exception occurs, an
1788 :exc:`UnexpectedException` exception is raised, containing the test, the
1789 example, and the original exception. If the output doesn't match, then a
1790 :exc:`DocTestFailure` exception is raised, containing the test, the example, and
1791 the actual output.
1792
1793 For information about the constructor parameters and methods, see the
1794 documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`.
1795
1796 There are two exceptions that may be raised by :class:`DebugRunner` instances:
1797
1798
1799 .. exception:: DocTestFailure(test, example, got)
1800
1801 An exception raised by :class:`DocTestRunner` to signal that a doctest example's
1802 actual output did not match its expected output. The constructor arguments are
1803 used to initialize the attributes of the same names.
1804
1805 :exc:`DocTestFailure` defines the following attributes:
1806
1807
1808 .. attribute:: DocTestFailure.test
1809
1810 The :class:`DocTest` object that was being run when the example failed.
1811
1812
1813 .. attribute:: DocTestFailure.example
1814
1815 The :class:`Example` that failed.
1816
1817
1818 .. attribute:: DocTestFailure.got
1819
1820 The example's actual output.
1821
1822
1823 .. exception:: UnexpectedException(test, example, exc_info)
1824
1825 An exception raised by :class:`DocTestRunner` to signal that a doctest
1826 example raised an unexpected exception. The constructor arguments are used
1827 to initialize the attributes of the same names.
1828
1829 :exc:`UnexpectedException` defines the following attributes:
1830
1831
1832 .. attribute:: UnexpectedException.test
1833
1834 The :class:`DocTest` object that was being run when the example failed.
1835
1836
1837 .. attribute:: UnexpectedException.example
1838
1839 The :class:`Example` that failed.
1840
1841
1842 .. attribute:: UnexpectedException.exc_info
1843
1844 A tuple containing information about the unexpected exception, as returned by
1845 :func:`sys.exc_info`.
1846
1847
1848 .. _doctest-soapbox:
1849
1850 Soapbox
1851 -------
1852
1853 As mentioned in the introduction, :mod:`doctest` has grown to have three primary
1854 uses:
1855
1856 #. Checking examples in docstrings.
1857
1858 #. Regression testing.
1859
1860 #. Executable documentation / literate testing.
1861
1862 These uses have different requirements, and it is important to distinguish them.
1863 In particular, filling your docstrings with obscure test cases makes for bad
1864 documentation.
1865
1866 When writing a docstring, choose docstring examples with care. There's an art to
1867 this that needs to be learned---it may not be natural at first. Examples should
1868 add genuine value to the documentation. A good example can often be worth many
1869 words. If done with care, the examples will be invaluable for your users, and
1870 will pay back the time it takes to collect them many times over as the years go
1871 by and things change. I'm still amazed at how often one of my :mod:`doctest`
1872 examples stops working after a "harmless" change.
1873
1874 Doctest also makes an excellent tool for regression testing, especially if you
1875 don't skimp on explanatory text. By interleaving prose and examples, it becomes
1876 much easier to keep track of what's actually being tested, and why. When a test
1877 fails, good prose can make it much easier to figure out what the problem is, and
1878 how it should be fixed. It's true that you could write extensive comments in
1879 code-based testing, but few programmers do. Many have found that using doctest
1880 approaches instead leads to much clearer tests. Perhaps this is simply because
1881 doctest makes writing prose a little easier than writing code, while writing
1882 comments in code is a little harder. I think it goes deeper than just that:
1883 the natural attitude when writing a doctest-based test is that you want to
1884 explain the fine points of your software, and illustrate them with examples.
1885 This in turn naturally leads to test files that start with the simplest
1886 features, and logically progress to complications and edge cases. A coherent
1887 narrative is the result, instead of a collection of isolated functions that test
1888 isolated bits of functionality seemingly at random. It's a different attitude,
1889 and produces different results, blurring the distinction between testing and
1890 explaining.
1891
1892 Regression testing is best confined to dedicated objects or files. There are
1893 several options for organizing tests:
1894
1895 * Write text files containing test cases as interactive examples, and test the
1896 files using :func:`testfile` or :func:`DocFileSuite`. This is recommended,
1897 although is easiest to do for new projects, designed from the start to use
1898 doctest.
1899
1900 * Define functions named ``_regrtest_topic`` that consist of single docstrings,
1901 containing test cases for the named topics. These functions can be included in
1902 the same file as the module, or separated out into a separate test file.
1903
1904 * Define a ``__test__`` dictionary mapping from regression test topics to
1905 docstrings containing test cases.
1906
1907 When you have placed your tests in a module, the module can itself be the test
1908 runner. When a test fails, you can arrange for your test runner to re-run only
1909 the failing doctest while you debug the problem. Here is a minimal example of
1910 such a test runner::
1911
1912 if __name__ == '__main__':
1913 import doctest
1914 flags = doctest.REPORT_NDIFF|doctest.REPORT_ONLY_FIRST_FAILURE
1915 if len(sys.argv) > 1:
1916 name = sys.argv[1]
1917 if name in globals():
1918 obj = globals()[name]
1919 else:
1920 obj = __test__[name]
1921 doctest.run_docstring_examples(obj, globals(), name=name,
1922 optionflags=flags)
1923 else:
1924 fail, total = doctest.testmod(optionflags=flags)
1925 print("{} failures out of {} tests".format(fail, total))
1926
1927
1928 .. rubric:: Footnotes
1929
1930 .. [#] Examples containing both expected output and an exception are not supported.
1931 Trying to guess where one ends and the other begins is too error-prone, and that
1932 also makes for a confusing test.