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 <tim (a] python.org> 9 .. sectionauthor:: Tim Peters <tim (a] python.org> 10 .. sectionauthor:: Moshe Zadka <moshez (a] debian.org> 11 .. sectionauthor:: Edward Loper <edloper (a] users.sourceforge.net> 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 ? 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 ? 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 or'ed together and passed to various functions. The names can also be used in 534 :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 ? 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 or'ed into the option flags, and the option flags so augmented are passed to the 1165 :class:`DocTestRunner` instance created to run the doctest. If any reporting 1166 flags were specified when the :class:`DocTestCase` instance was constructed, 1167 :mod:`doctest`'s :mod:`unittest` reporting flags are ignored. 1168 1169 The value of the :mod:`unittest` reporting flags in effect before the function 1170 was called is returned by the function. 1171 1172 .. versionadded:: 2.4 1173 1174 1175 .. _doctest-advanced-api: 1176 1177 Advanced API 1178 ------------ 1179 1180 The basic API is a simple wrapper that's intended to make doctest easy to use. 1181 It is fairly flexible, and should meet most users' needs; however, if you 1182 require more fine-grained control over testing, or wish to extend doctest's 1183 capabilities, then you should use the advanced API. 1184 1185 The advanced API revolves around two container classes, which are used to store 1186 the interactive examples extracted from doctest cases: 1187 1188 * :class:`Example`: A single Python :term:`statement`, paired with its expected 1189 output. 1190 1191 * :class:`DocTest`: A collection of :class:`Example`\ s, typically extracted 1192 from a single docstring or text file. 1193 1194 Additional processing classes are defined to find, parse, and run, and check 1195 doctest examples: 1196 1197 * :class:`DocTestFinder`: Finds all docstrings in a given module, and uses a 1198 :class:`DocTestParser` to create a :class:`DocTest` from every docstring that 1199 contains interactive examples. 1200 1201 * :class:`DocTestParser`: Creates a :class:`DocTest` object from a string (such 1202 as an object's docstring). 1203 1204 * :class:`DocTestRunner`: Executes the examples in a :class:`DocTest`, and uses 1205 an :class:`OutputChecker` to verify their output. 1206 1207 * :class:`OutputChecker`: Compares the actual output from a doctest example with 1208 the expected output, and decides whether they match. 1209 1210 The relationships among these processing classes are summarized in the following 1211 diagram:: 1212 1213 list of: 1214 +------+ +---------+ 1215 |module| --DocTestFinder-> | DocTest | --DocTestRunner-> results 1216 +------+ | ^ +---------+ | ^ (printed) 1217 | | | Example | | | 1218 v | | ... | v | 1219 DocTestParser | Example | OutputChecker 1220 +---------+ 1221 1222 1223 .. _doctest-doctest: 1224 1225 DocTest Objects 1226 ^^^^^^^^^^^^^^^ 1227 1228 1229 .. class:: DocTest(examples, globs, name, filename, lineno, docstring) 1230 1231 A collection of doctest examples that should be run in a single namespace. The 1232 constructor arguments are used to initialize the attributes of the same names. 1233 1234 .. versionadded:: 2.4 1235 1236 :class:`DocTest` defines the following attributes. They are initialized by 1237 the constructor, and should not be modified directly. 1238 1239 1240 .. attribute:: examples 1241 1242 A list of :class:`Example` objects encoding the individual interactive Python 1243 examples that should be run by this test. 1244 1245 1246 .. attribute:: globs 1247 1248 The namespace (aka globals) that the examples should be run in. This is a 1249 dictionary mapping names to values. Any changes to the namespace made by the 1250 examples (such as binding new variables) will be reflected in :attr:`globs` 1251 after the test is run. 1252 1253 1254 .. attribute:: name 1255 1256 A string name identifying the :class:`DocTest`. Typically, this is the name 1257 of the object or file that the test was extracted from. 1258 1259 1260 .. attribute:: filename 1261 1262 The name of the file that this :class:`DocTest` was extracted from; or 1263 ``None`` if the filename is unknown, or if the :class:`DocTest` was not 1264 extracted from a file. 1265 1266 1267 .. attribute:: lineno 1268 1269 The line number within :attr:`filename` where this :class:`DocTest` begins, or 1270 ``None`` if the line number is unavailable. This line number is zero-based 1271 with respect to the beginning of the file. 1272 1273 1274 .. attribute:: docstring 1275 1276 The string that the test was extracted from, or ``None`` if the string is 1277 unavailable, or if the test was not extracted from a string. 1278 1279 1280 .. _doctest-example: 1281 1282 Example Objects 1283 ^^^^^^^^^^^^^^^ 1284 1285 1286 .. class:: Example(source, want[, exc_msg][, lineno][, indent][, options]) 1287 1288 A single interactive example, consisting of a Python statement and its expected 1289 output. The constructor arguments are used to initialize the attributes of the 1290 same names. 1291 1292 .. versionadded:: 2.4 1293 1294 :class:`Example` defines the following attributes. They are initialized by 1295 the constructor, and should not be modified directly. 1296 1297 1298 .. attribute:: source 1299 1300 A string containing the example's source code. This source code consists of a 1301 single Python statement, and always ends with a newline; the constructor adds 1302 a newline when necessary. 1303 1304 1305 .. attribute:: want 1306 1307 The expected output from running the example's source code (either from 1308 stdout, or a traceback in case of exception). :attr:`want` ends with a 1309 newline unless no output is expected, in which case it's an empty string. The 1310 constructor adds a newline when necessary. 1311 1312 1313 .. attribute:: exc_msg 1314 1315 The exception message generated by the example, if the example is expected to 1316 generate an exception; or ``None`` if it is not expected to generate an 1317 exception. This exception message is compared against the return value of 1318 :func:`traceback.format_exception_only`. :attr:`exc_msg` ends with a newline 1319 unless it's ``None``. The constructor adds a newline if needed. 1320 1321 1322 .. attribute:: lineno 1323 1324 The line number within the string containing this example where the example 1325 begins. This line number is zero-based with respect to the beginning of the 1326 containing string. 1327 1328 1329 .. attribute:: indent 1330 1331 The example's indentation in the containing string, i.e., the number of space 1332 characters that precede the example's first prompt. 1333 1334 1335 .. attribute:: options 1336 1337 A dictionary mapping from option flags to ``True`` or ``False``, which is used 1338 to override default options for this example. Any option flags not contained 1339 in this dictionary are left at their default value (as specified by the 1340 :class:`DocTestRunner`'s :attr:`optionflags`). By default, no options are set. 1341 1342 1343 .. _doctest-doctestfinder: 1344 1345 DocTestFinder objects 1346 ^^^^^^^^^^^^^^^^^^^^^ 1347 1348 1349 .. class:: DocTestFinder([verbose][, parser][, recurse][, exclude_empty]) 1350 1351 A processing class used to extract the :class:`DocTest`\ s that are relevant to 1352 a given object, from its docstring and the docstrings of its contained objects. 1353 :class:`DocTest`\ s can currently be extracted from the following object types: 1354 modules, functions, classes, methods, staticmethods, classmethods, and 1355 properties. 1356 1357 The optional argument *verbose* can be used to display the objects searched by 1358 the finder. It defaults to ``False`` (no output). 1359 1360 The optional argument *parser* specifies the :class:`DocTestParser` object (or a 1361 drop-in replacement) that is used to extract doctests from docstrings. 1362 1363 If the optional argument *recurse* is false, then :meth:`DocTestFinder.find` 1364 will only examine the given object, and not any contained objects. 1365 1366 If the optional argument *exclude_empty* is false, then 1367 :meth:`DocTestFinder.find` will include tests for objects with empty docstrings. 1368 1369 .. versionadded:: 2.4 1370 1371 :class:`DocTestFinder` defines the following method: 1372 1373 1374 .. method:: find(obj[, name][, module][, globs][, extraglobs]) 1375 1376 Return a list of the :class:`DocTest`\ s that are defined by *obj*'s 1377 docstring, or by any of its contained objects' docstrings. 1378 1379 The optional argument *name* specifies the object's name; this name will be 1380 used to construct names for the returned :class:`DocTest`\ s. If *name* is 1381 not specified, then ``obj.__name__`` is used. 1382 1383 The optional parameter *module* is the module that contains the given object. 1384 If the module is not specified or is ``None``, then the test finder will attempt 1385 to automatically determine the correct module. The object's module is used: 1386 1387 * As a default namespace, if *globs* is not specified. 1388 1389 * To prevent the DocTestFinder from extracting DocTests from objects that are 1390 imported from other modules. (Contained objects with modules other than 1391 *module* are ignored.) 1392 1393 * To find the name of the file containing the object. 1394 1395 * To help find the line number of the object within its file. 1396 1397 If *module* is ``False``, no attempt to find the module will be made. This is 1398 obscure, of use mostly in testing doctest itself: if *module* is ``False``, or 1399 is ``None`` but cannot be found automatically, then all objects are considered 1400 to belong to the (non-existent) module, so all contained objects will 1401 (recursively) be searched for doctests. 1402 1403 The globals for each :class:`DocTest` is formed by combining *globs* and 1404 *extraglobs* (bindings in *extraglobs* override bindings in *globs*). A new 1405 shallow copy of the globals dictionary is created for each :class:`DocTest`. 1406 If *globs* is not specified, then it defaults to the module's *__dict__*, if 1407 specified, or ``{}`` otherwise. If *extraglobs* is not specified, then it 1408 defaults to ``{}``. 1409 1410 1411 .. _doctest-doctestparser: 1412 1413 DocTestParser objects 1414 ^^^^^^^^^^^^^^^^^^^^^ 1415 1416 1417 .. class:: DocTestParser() 1418 1419 A processing class used to extract interactive examples from a string, and use 1420 them to create a :class:`DocTest` object. 1421 1422 .. versionadded:: 2.4 1423 1424 :class:`DocTestParser` defines the following methods: 1425 1426 1427 .. method:: get_doctest(string, globs, name, filename, lineno) 1428 1429 Extract all doctest examples from the given string, and collect them into a 1430 :class:`DocTest` object. 1431 1432 *globs*, *name*, *filename*, and *lineno* are attributes for the new 1433 :class:`DocTest` object. See the documentation for :class:`DocTest` for more 1434 information. 1435 1436 1437 .. method:: get_examples(string[, name]) 1438 1439 Extract all doctest examples from the given string, and return them as a list 1440 of :class:`Example` objects. Line numbers are 0-based. The optional argument 1441 *name* is a name identifying this string, and is only used for error messages. 1442 1443 1444 .. method:: parse(string[, name]) 1445 1446 Divide the given string into examples and intervening text, and return them as 1447 a list of alternating :class:`Example`\ s and strings. Line numbers for the 1448 :class:`Example`\ s are 0-based. The optional argument *name* is a name 1449 identifying this string, and is only used for error messages. 1450 1451 1452 .. _doctest-doctestrunner: 1453 1454 DocTestRunner objects 1455 ^^^^^^^^^^^^^^^^^^^^^ 1456 1457 1458 .. class:: DocTestRunner([checker][, verbose][, optionflags]) 1459 1460 A processing class used to execute and verify the interactive examples in a 1461 :class:`DocTest`. 1462 1463 The comparison between expected outputs and actual outputs is done by an 1464 :class:`OutputChecker`. This comparison may be customized with a number of 1465 option flags; see section :ref:`doctest-options` for more information. If the 1466 option flags are insufficient, then the comparison may also be customized by 1467 passing a subclass of :class:`OutputChecker` to the constructor. 1468 1469 The test runner's display output can be controlled in two ways. First, an output 1470 function can be passed to :meth:`TestRunner.run`; this function will be called 1471 with strings that should be displayed. It defaults to ``sys.stdout.write``. If 1472 capturing the output is not sufficient, then the display output can be also 1473 customized by subclassing DocTestRunner, and overriding the methods 1474 :meth:`report_start`, :meth:`report_success`, 1475 :meth:`report_unexpected_exception`, and :meth:`report_failure`. 1476 1477 The optional keyword argument *checker* specifies the :class:`OutputChecker` 1478 object (or drop-in replacement) that should be used to compare the expected 1479 outputs to the actual outputs of doctest examples. 1480 1481 The optional keyword argument *verbose* controls the :class:`DocTestRunner`'s 1482 verbosity. If *verbose* is ``True``, then information is printed about each 1483 example, as it is run. If *verbose* is ``False``, then only failures are 1484 printed. If *verbose* is unspecified, or ``None``, then verbose output is used 1485 iff the command-line switch ``-v`` is used. 1486 1487 The optional keyword argument *optionflags* can be used to control how the test 1488 runner compares expected output to actual output, and how it displays failures. 1489 For more information, see section :ref:`doctest-options`. 1490 1491 .. versionadded:: 2.4 1492 1493 :class:`DocTestParser` defines the following methods: 1494 1495 1496 .. method:: report_start(out, test, example) 1497 1498 Report that the test runner is about to process the given example. This method 1499 is provided to allow subclasses of :class:`DocTestRunner` to customize their 1500 output; it should not be called directly. 1501 1502 *example* is the example about to be processed. *test* is the test 1503 *containing example*. *out* is the output function that was passed to 1504 :meth:`DocTestRunner.run`. 1505 1506 1507 .. method:: report_success(out, test, example, got) 1508 1509 Report that the given example ran successfully. This method is provided to 1510 allow subclasses of :class:`DocTestRunner` to customize their output; it 1511 should not be called directly. 1512 1513 *example* is the example about to be processed. *got* is the actual output 1514 from the example. *test* is the test containing *example*. *out* is the 1515 output function that was passed to :meth:`DocTestRunner.run`. 1516 1517 1518 .. method:: report_failure(out, test, example, got) 1519 1520 Report that the given example failed. This method is provided to allow 1521 subclasses of :class:`DocTestRunner` to customize their output; it should not 1522 be called directly. 1523 1524 *example* is the example about to be processed. *got* is the actual output 1525 from the example. *test* is the test containing *example*. *out* is the 1526 output function that was passed to :meth:`DocTestRunner.run`. 1527 1528 1529 .. method:: report_unexpected_exception(out, test, example, exc_info) 1530 1531 Report that the given example raised an unexpected exception. This method is 1532 provided to allow subclasses of :class:`DocTestRunner` to customize their 1533 output; it should not be called directly. 1534 1535 *example* is the example about to be processed. *exc_info* is a tuple 1536 containing information about the unexpected exception (as returned by 1537 :func:`sys.exc_info`). *test* is the test containing *example*. *out* is the 1538 output function that was passed to :meth:`DocTestRunner.run`. 1539 1540 1541 .. method:: run(test[, compileflags][, out][, clear_globs]) 1542 1543 Run the examples in *test* (a :class:`DocTest` object), and display the 1544 results using the writer function *out*. 1545 1546 The examples are run in the namespace ``test.globs``. If *clear_globs* is 1547 true (the default), then this namespace will be cleared after the test runs, 1548 to help with garbage collection. If you would like to examine the namespace 1549 after the test completes, then use *clear_globs=False*. 1550 1551 *compileflags* gives the set of flags that should be used by the Python 1552 compiler when running the examples. If not specified, then it will default to 1553 the set of future-import flags that apply to *globs*. 1554 1555 The output of each example is checked using the :class:`DocTestRunner`'s 1556 output checker, and the results are formatted by the 1557 :meth:`DocTestRunner.report_\*` methods. 1558 1559 1560 .. method:: summarize([verbose]) 1561 1562 Print a summary of all the test cases that have been run by this DocTestRunner, 1563 and return a :term:`named tuple` ``TestResults(failed, attempted)``. 1564 1565 The optional *verbose* argument controls how detailed the summary is. If the 1566 verbosity is not specified, then the :class:`DocTestRunner`'s verbosity is 1567 used. 1568 1569 .. versionchanged:: 2.6 1570 Use a named tuple. 1571 1572 1573 .. _doctest-outputchecker: 1574 1575 OutputChecker objects 1576 ^^^^^^^^^^^^^^^^^^^^^ 1577 1578 1579 .. class:: OutputChecker() 1580 1581 A class used to check the whether the actual output from a doctest example 1582 matches the expected output. :class:`OutputChecker` defines two methods: 1583 :meth:`check_output`, which compares a given pair of outputs, and returns true 1584 if they match; and :meth:`output_difference`, which returns a string describing 1585 the differences between two outputs. 1586 1587 .. versionadded:: 2.4 1588 1589 :class:`OutputChecker` defines the following methods: 1590 1591 1592 .. method:: check_output(want, got, optionflags) 1593 1594 Return ``True`` iff the actual output from an example (*got*) matches the 1595 expected output (*want*). These strings are always considered to match if 1596 they are identical; but depending on what option flags the test runner is 1597 using, several non-exact match types are also possible. See section 1598 :ref:`doctest-options` for more information about option flags. 1599 1600 1601 .. method:: output_difference(example, got, optionflags) 1602 1603 Return a string describing the differences between the expected output for a 1604 given example (*example*) and the actual output (*got*). *optionflags* is the 1605 set of option flags used to compare *want* and *got*. 1606 1607 1608 .. _doctest-debugging: 1609 1610 Debugging 1611 --------- 1612 1613 Doctest provides several mechanisms for debugging doctest examples: 1614 1615 * Several functions convert doctests to executable Python programs, which can be 1616 run under the Python debugger, :mod:`pdb`. 1617 1618 * The :class:`DebugRunner` class is a subclass of :class:`DocTestRunner` that 1619 raises an exception for the first failing example, containing information about 1620 that example. This information can be used to perform post-mortem debugging on 1621 the example. 1622 1623 * The :mod:`unittest` cases generated by :func:`DocTestSuite` support the 1624 :meth:`debug` method defined by :class:`unittest.TestCase`. 1625 1626 * You can add a call to :func:`pdb.set_trace` in a doctest example, and you'll 1627 drop into the Python debugger when that line is executed. Then you can inspect 1628 current values of variables, and so on. For example, suppose :file:`a.py` 1629 contains just this module docstring:: 1630 1631 """ 1632 >>> def f(x): 1633 ... g(x*2) 1634 >>> def g(x): 1635 ... print x+3 1636 ... import pdb; pdb.set_trace() 1637 >>> f(3) 1638 9 1639 """ 1640 1641 Then an interactive Python session may look like this:: 1642 1643 >>> import a, doctest 1644 >>> doctest.testmod(a) 1645 --Return-- 1646 > <doctest a[1]>(3)g()->None 1647 -> import pdb; pdb.set_trace() 1648 (Pdb) list 1649 1 def g(x): 1650 2 print x+3 1651 3 -> import pdb; pdb.set_trace() 1652 [EOF] 1653 (Pdb) print x 1654 6 1655 (Pdb) step 1656 --Return-- 1657 > <doctest a[0]>(2)f()->None 1658 -> g(x*2) 1659 (Pdb) list 1660 1 def f(x): 1661 2 -> g(x*2) 1662 [EOF] 1663 (Pdb) print x 1664 3 1665 (Pdb) step 1666 --Return-- 1667 > <doctest a[2]>(1)?()->None 1668 -> f(3) 1669 (Pdb) cont 1670 (0, 3) 1671 >>> 1672 1673 .. versionchanged:: 2.4 1674 The ability to use :func:`pdb.set_trace` usefully inside doctests was added. 1675 1676 Functions that convert doctests to Python code, and possibly run the synthesized 1677 code under the debugger: 1678 1679 1680 .. function:: script_from_examples(s) 1681 1682 Convert text with examples to a script. 1683 1684 Argument *s* is a string containing doctest examples. The string is converted 1685 to a Python script, where doctest examples in *s* are converted to regular code, 1686 and everything else is converted to Python comments. The generated script is 1687 returned as a string. For example, :: 1688 1689 import doctest 1690 print doctest.script_from_examples(r""" 1691 Set x and y to 1 and 2. 1692 >>> x, y = 1, 2 1693 1694 Print their sum: 1695 >>> print x+y 1696 3 1697 """) 1698 1699 displays:: 1700 1701 # Set x and y to 1 and 2. 1702 x, y = 1, 2 1703 # 1704 # Print their sum: 1705 print x+y 1706 # Expected: 1707 ## 3 1708 1709 This function is used internally by other functions (see below), but can also be 1710 useful when you want to transform an interactive Python session into a Python 1711 script. 1712 1713 .. versionadded:: 2.4 1714 1715 1716 .. function:: testsource(module, name) 1717 1718 Convert the doctest for an object to a script. 1719 1720 Argument *module* is a module object, or dotted name of a module, containing the 1721 object whose doctests are of interest. Argument *name* is the name (within the 1722 module) of the object with the doctests of interest. The result is a string, 1723 containing the object's docstring converted to a Python script, as described for 1724 :func:`script_from_examples` above. For example, if module :file:`a.py` 1725 contains a top-level function :func:`f`, then :: 1726 1727 import a, doctest 1728 print doctest.testsource(a, "a.f") 1729 1730 prints a script version of function :func:`f`'s docstring, with doctests 1731 converted to code, and the rest placed in comments. 1732 1733 .. versionadded:: 2.3 1734 1735 1736 .. function:: debug(module, name[, pm]) 1737 1738 Debug the doctests for an object. 1739 1740 The *module* and *name* arguments are the same as for function 1741 :func:`testsource` above. The synthesized Python script for the named object's 1742 docstring is written to a temporary file, and then that file is run under the 1743 control of the Python debugger, :mod:`pdb`. 1744 1745 A shallow copy of ``module.__dict__`` is used for both local and global 1746 execution context. 1747 1748 Optional argument *pm* controls whether post-mortem debugging is used. If *pm* 1749 has a true value, the script file is run directly, and the debugger gets 1750 involved only if the script terminates via raising an unhandled exception. If 1751 it does, then post-mortem debugging is invoked, via :func:`pdb.post_mortem`, 1752 passing the traceback object from the unhandled exception. If *pm* is not 1753 specified, or is false, the script is run under the debugger from the start, via 1754 passing an appropriate :func:`execfile` call to :func:`pdb.run`. 1755 1756 .. versionadded:: 2.3 1757 1758 .. versionchanged:: 2.4 1759 The *pm* argument was added. 1760 1761 1762 .. function:: debug_src(src[, pm][, globs]) 1763 1764 Debug the doctests in a string. 1765 1766 This is like function :func:`debug` above, except that a string containing 1767 doctest examples is specified directly, via the *src* argument. 1768 1769 Optional argument *pm* has the same meaning as in function :func:`debug` above. 1770 1771 Optional argument *globs* gives a dictionary to use as both local and global 1772 execution context. If not specified, or ``None``, an empty dictionary is used. 1773 If specified, a shallow copy of the dictionary is used. 1774 1775 .. versionadded:: 2.4 1776 1777 The :class:`DebugRunner` class, and the special exceptions it may raise, are of 1778 most interest to testing framework authors, and will only be sketched here. See 1779 the source code, and especially :class:`DebugRunner`'s docstring (which is a 1780 doctest!) for more details: 1781 1782 1783 .. class:: DebugRunner([checker][, verbose][, optionflags]) 1784 1785 A subclass of :class:`DocTestRunner` that raises an exception as soon as a 1786 failure is encountered. If an unexpected exception occurs, an 1787 :exc:`UnexpectedException` exception is raised, containing the test, the 1788 example, and the original exception. If the output doesn't match, then a 1789 :exc:`DocTestFailure` exception is raised, containing the test, the example, and 1790 the actual output. 1791 1792 For information about the constructor parameters and methods, see the 1793 documentation for :class:`DocTestRunner` in section :ref:`doctest-advanced-api`. 1794 1795 There are two exceptions that may be raised by :class:`DebugRunner` instances: 1796 1797 1798 .. exception:: DocTestFailure(test, example, got) 1799 1800 An exception raised by :class:`DocTestRunner` to signal that a doctest example's 1801 actual output did not match its expected output. The constructor arguments are 1802 used to initialize the attributes of the same names. 1803 1804 :exc:`DocTestFailure` defines the following attributes: 1805 1806 1807 .. attribute:: DocTestFailure.test 1808 1809 The :class:`DocTest` object that was being run when the example failed. 1810 1811 1812 .. attribute:: DocTestFailure.example 1813 1814 The :class:`Example` that failed. 1815 1816 1817 .. attribute:: DocTestFailure.got 1818 1819 The example's actual output. 1820 1821 1822 .. exception:: UnexpectedException(test, example, exc_info) 1823 1824 An exception raised by :class:`DocTestRunner` to signal that a doctest 1825 example raised an unexpected exception. The constructor arguments are used 1826 to initialize the attributes of the same names. 1827 1828 :exc:`UnexpectedException` defines the following attributes: 1829 1830 1831 .. attribute:: UnexpectedException.test 1832 1833 The :class:`DocTest` object that was being run when the example failed. 1834 1835 1836 .. attribute:: UnexpectedException.example 1837 1838 The :class:`Example` that failed. 1839 1840 1841 .. attribute:: UnexpectedException.exc_info 1842 1843 A tuple containing information about the unexpected exception, as returned by 1844 :func:`sys.exc_info`. 1845 1846 1847 .. _doctest-soapbox: 1848 1849 Soapbox 1850 ------- 1851 1852 As mentioned in the introduction, :mod:`doctest` has grown to have three primary 1853 uses: 1854 1855 #. Checking examples in docstrings. 1856 1857 #. Regression testing. 1858 1859 #. Executable documentation / literate testing. 1860 1861 These uses have different requirements, and it is important to distinguish them. 1862 In particular, filling your docstrings with obscure test cases makes for bad 1863 documentation. 1864 1865 When writing a docstring, choose docstring examples with care. There's an art to 1866 this that needs to be learned---it may not be natural at first. Examples should 1867 add genuine value to the documentation. A good example can often be worth many 1868 words. If done with care, the examples will be invaluable for your users, and 1869 will pay back the time it takes to collect them many times over as the years go 1870 by and things change. I'm still amazed at how often one of my :mod:`doctest` 1871 examples stops working after a "harmless" change. 1872 1873 Doctest also makes an excellent tool for regression testing, especially if you 1874 don't skimp on explanatory text. By interleaving prose and examples, it becomes 1875 much easier to keep track of what's actually being tested, and why. When a test 1876 fails, good prose can make it much easier to figure out what the problem is, and 1877 how it should be fixed. It's true that you could write extensive comments in 1878 code-based testing, but few programmers do. Many have found that using doctest 1879 approaches instead leads to much clearer tests. Perhaps this is simply because 1880 doctest makes writing prose a little easier than writing code, while writing 1881 comments in code is a little harder. I think it goes deeper than just that: 1882 the natural attitude when writing a doctest-based test is that you want to 1883 explain the fine points of your software, and illustrate them with examples. 1884 This in turn naturally leads to test files that start with the simplest 1885 features, and logically progress to complications and edge cases. A coherent 1886 narrative is the result, instead of a collection of isolated functions that test 1887 isolated bits of functionality seemingly at random. It's a different attitude, 1888 and produces different results, blurring the distinction between testing and 1889 explaining. 1890 1891 Regression testing is best confined to dedicated objects or files. There are 1892 several options for organizing tests: 1893 1894 * Write text files containing test cases as interactive examples, and test the 1895 files using :func:`testfile` or :func:`DocFileSuite`. This is recommended, 1896 although is easiest to do for new projects, designed from the start to use 1897 doctest. 1898 1899 * Define functions named ``_regrtest_topic`` that consist of single docstrings, 1900 containing test cases for the named topics. These functions can be included in 1901 the same file as the module, or separated out into a separate test file. 1902 1903 * Define a ``__test__`` dictionary mapping from regression test topics to 1904 docstrings containing test cases. 1905 1906 When you have placed your tests in a module, the module can itself be the test 1907 runner. When a test fails, you can arrange for your test runner to re-run only 1908 the failing doctest while you debug the problem. Here is a minimal example of 1909 such a test runner:: 1910 1911 if __name__ == '__main__': 1912 import doctest 1913 flags = doctest.REPORT_NDIFF|doctest.REPORT_ONLY_FIRST_FAILURE 1914 if len(sys.argv) > 1: 1915 name = sys.argv[1] 1916 if name in globals(): 1917 obj = globals()[name] 1918 else: 1919 obj = __test__[name] 1920 doctest.run_docstring_examples(obj, globals(), name=name, 1921 optionflags=flags) 1922 else: 1923 fail, total = doctest.testmod(optionflags=flags) 1924 print("{} failures out of {} tests".format(fail, total)) 1925 1926 1927 .. rubric:: Footnotes 1928 1929 .. [#] Examples containing both expected output and an exception are not supported. 1930 Trying to guess where one ends and the other begins is too error-prone, and that 1931 also makes for a confusing test. 1932