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