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