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