doctest --- 測試互動式 Python 範例

原始碼:Lib/doctest.py


Thedoctest module searches for pieces of text that look like interactivePython sessions, and then executes those sessions to verify that they workexactly as shown. There are several common ways to use doctest:

  • To check that a module's docstrings are up-to-date by verifying that allinteractive examples still work as documented.

  • 透過驗證測試檔案或測試物件中的互動式範例是否按預期運作來執行迴歸測試。

  • To write tutorial documentation for a package, liberally illustrated withinput-output examples. Depending on whether the examples or the expository textare emphasized, this has the flavor of "literate testing" or "executabledocumentation".

Here's a complete but small example module:

"""This is the "example" module.The example module supplies one function, factorial().  For example,>>> factorial(5)120"""deffactorial(n):"""Return the factorial of n, an exact integer >= 0.    >>> [factorial(n) for n in range(6)]    [1, 1, 2, 6, 24, 120]    >>> factorial(30)    265252859812191058636308480000000    >>> factorial(-1)    Traceback (most recent call last):        ...    ValueError: n must be >= 0    Factorials of floats are OK, but the float must be an exact integer:    >>> factorial(30.1)    Traceback (most recent call last):        ...    ValueError: n must be exact integer    >>> factorial(30.0)    265252859812191058636308480000000    It must also not be ridiculously large:    >>> factorial(1e100)    Traceback (most recent call last):        ...    OverflowError: n too large    """importmathifnotn>=0:raiseValueError("n must be >= 0")ifmath.floor(n)!=n:raiseValueError("n must be exact integer")ifn+1==n:# catch a value like 1e300raiseOverflowError("n too large")result=1factor=2whilefactor<=n:result*=factorfactor+=1returnresultif__name__=="__main__":importdoctestdoctest.testmod()

If you runexample.py directly from the command line,doctestworks its magic:

$pythonexample.py$

There's no output! That's normal, and it means all the examples worked. Pass-v to the script, anddoctest prints a detailed log of whatit's trying, and prints a summary at the end:

$pythonexample.py-vTrying:    factorial(5)Expecting:    120okTrying:    [factorial(n) for n in range(6)]Expecting:    [1, 1, 2, 6, 24, 120]ok

And so on, eventually ending with:

Trying:    factorial(1e100)Expecting:    Traceback (most recent call last):        ...    OverflowError: n too largeok2 items passed all tests:   1 test in __main__   6 tests in __main__.factorial7 tests in 2 items.7 passed.Test passed.$

That's all you need to know to start making productive use ofdoctest!Jump in. The following sections provide full details. Note that there are manyexamples of doctests in the standard Python test suite and libraries.Especially useful examples can be found in the standard test fileLib/test/test_doctest/test_doctest.py.

Simple Usage: Checking Examples in Docstrings

The simplest way to start using doctest (but not necessarily the way you'llcontinue to do it) is to end each moduleM with:

if__name__=="__main__":importdoctestdoctest.testmod()

doctest then examines docstrings in moduleM.

Running the module as a script causes the examples in the docstrings to getexecuted and verified:

pythonM.py

This won't display anything unless an example fails, in which case the failingexample(s) and the cause(s) of the failure(s) are printed to stdout, and thefinal line of output is***TestFailed***Nfailures., whereN is thenumber of examples that failed.

Run it with the-v switch instead:

pythonM.py-v

and a detailed report of all examples tried is printed to standard output, alongwith assorted summaries at the end.

You can force verbose mode by passingverbose=True totestmod(), orprohibit it by passingverbose=False. In either of those cases,sys.argv is not examined bytestmod() (so passing-v or nothas no effect).

There is also a command line shortcut for runningtestmod(), see sectionCommand-line Usage.

For more information ontestmod(), see section基礎 API.

Simple Usage: Checking Examples in a Text File

Another simple application of doctest is testing interactive examples in a textfile. This can be done with thetestfile() function:

importdoctestdoctest.testfile("example.txt")

That short script executes and verifies any interactive Python examplescontained in the fileexample.txt. The file content is treated as if itwere a single giant docstring; the file doesn't need to contain a Pythonprogram! For example, perhapsexample.txt contains this:

The ``example`` module======================Using ``factorial``-------------------This is an example text file in reStructuredText format.  First import``factorial`` from the ``example`` module:    >>> from example import factorialNow use it:    >>> factorial(6)    120

Runningdoctest.testfile("example.txt") then finds the error in thisdocumentation:

File"./example.txt",line14,inexample.txtFailedexample:factorial(6)Expected:120Got:720

As withtestmod(),testfile() won't display anything unless anexample fails. If an example does fail, then the failing example(s) and thecause(s) of the failure(s) are printed to stdout, using the same format astestmod().

By default,testfile() looks for files in the calling module's directory.See section基礎 API for a description of the optional argumentsthat can be used to tell it to look for files in other locations.

Liketestmod(),testfile()'s verbosity can be set with the-v command-line switch or with the optional keyword argumentverbose.

There is also a command line shortcut for runningtestfile(), see sectionCommand-line Usage.

For more information ontestfile(), see section基礎 API.

Command-line Usage

Thedoctest module can be invoked as a script from the command line:

python-mdoctest[-v][-oOPTION][-f]file[file...]
-v,--verbose

Detailed report of all examples tried is printed to standard output,along with assorted summaries at the end:

python-mdoctest-vexample.py

This will importexample.py as a standalone module and runtestmod() on it. Note that this may not work correctly if thefile is part of a package and imports other submodules from that package.

If the file name does not end with.py,doctest infersthat it must be run withtestfile() instead:

python-mdoctest-vexample.txt
-o,--option<option>

Option flags control various aspects of doctest's behavior, see section可選旗標.

在 3.4 版被加入.

-f,--fail-fast

This is shorthand for-oFAIL_FAST.

在 3.4 版被加入.

How It Works

This section examines in detail how doctest works: which docstrings it looks at,how it finds interactive examples, what execution context it uses, how ithandles exceptions, and how option flags can be used to control its behavior.This is the information that you need to know to write doctest examples; forinformation about actually running doctest on these examples, see the followingsections.

Which Docstrings Are Examined?

The module docstring, and all function, class and method docstrings aresearched. Objects imported into the module are not searched.

In addition, there are cases when you want tests to be part of a module but not partof the help text, which requires that the tests not be included in the docstring.Doctest looks for a module-level variable called__test__ and uses it to locate othertests. IfM.__test__ exists, it must be a dict, and eachentry maps a (string) name to a function object, class object, or string.Function and class object docstrings found fromM.__test__ are searched, andstrings are treated as if they were docstrings. In output, a keyK inM.__test__ appears with nameM.__test__.K.

For example, place this block of code at the top ofexample.py:

__test__={'numbers':""">>> factorial(6)720>>> [factorial(n) for n in range(6)][1, 1, 2, 6, 24, 120]"""}

The value ofexample.__test__["numbers"] will be treated as adocstring and all the tests inside it will be run. It isimportant to note that the value can be mapped to a function,class object, or module; if so,doctestsearches them recursively for docstrings, which are then scanned for tests.

Any classes found are recursively searched similarly, to test docstrings intheir contained methods and nested classes.

How are Docstring Examples Recognized?

In most cases a copy-and-paste of an interactive console session works fine,but doctest isn't trying to do an exact emulation of any specific Python shell.

>>># 註解會被忽略>>>x=12>>>x12>>>ifx==13:...print("yes")...else:...print("no")...print("NO")...print("NO!!!")...noNONO!!!>>>

Any expected output must immediately follow the final'>>>' or'...'line containing the code, and the expected output (if any) extends to the next'>>>' or all-whitespace line.

The fine print:

  • Expected output cannot contain an all-whitespace line, since such a line istaken to signal the end of expected output. If expected output does contain ablank line, put<BLANKLINE> in your doctest example each place a blank lineis expected.

  • All hard tab characters are expanded to spaces, using 8-column tab stops.Tabs in output generated by the tested code are not modified. Because anyhard tabs in the sample outputare expanded, this means that if the codeoutput includes hard tabs, the only way the doctest can pass is if theNORMALIZE_WHITESPACE option ordirectiveis in effect.Alternatively, the test can be rewritten to capture the output and compare itto an expected value as part of the test. This handling of tabs in thesource was arrived at through trial and error, and has proven to be the leasterror prone way of handling them. It is possible to use a differentalgorithm for handling tabs by writing a customDocTestParser class.

  • Output to stdout is captured, but not output to stderr (exception tracebacksare captured via a different means).

  • If you continue a line via backslashing in an interactive session, or for anyother reason use a backslash, you should use a raw docstring, which willpreserve your backslashes exactly as you type them:

    >>>deff(x):...r'''Backslashes in a raw docstring: m\n'''...>>>print(f.__doc__)Backslashes in a raw docstring: m\n

    Otherwise, the backslash will be interpreted as part of the string. For example,the\n above would be interpreted as a newline character. Alternatively, youcan double each backslash in the doctest version (and not use a raw string):

    >>>deff(x):...'''Backslashes in a raw docstring: m\\n'''...>>>print(f.__doc__)Backslashes in a raw docstring: m\n
  • The starting column doesn't matter:

    >>>assert"Easy!"      >>> import math          >>> math.floor(1.9)          1

    and as many leading whitespace characters are stripped from the expected outputas appeared in the initial'>>>' line that started the example.

What's the Execution Context?

By default, each timedoctest finds a docstring to test, it uses ashallow copy ofM's globals, so that running tests doesn't change themodule's real globals, and so that one test inM can't leave behindcrumbs that accidentally allow another test to work. This means examples canfreely use any names defined at top-level inM, and names defined earlierin the docstring being run. Examples cannot see names defined in otherdocstrings.

You can force use of your own dict as the execution context by passingglobs=your_dict totestmod() ortestfile() instead.

What About Exceptions?

No problem, provided that the traceback is the only output produced by theexample: just paste in the traceback.[1] Since tracebacks contain detailsthat are likely to change rapidly (for example, exact file paths and linenumbers), this is one case where doctest works hard to be flexible in what itaccepts.

簡單範例:

>>>[1,2,3].remove(42)Traceback (most recent call last):  File"<stdin>", line1, in<module>ValueError:list.remove(x): x not in list

That doctest succeeds ifValueError is raised, with thelist.remove(x):xnotinlist detail as shown.

The expected output for an exception must start with a traceback header, whichmay be either of the following two lines, indented the same as the first line ofthe example:

Traceback(mostrecentcalllast):Traceback(innermostlast):

The traceback header is followed by an optional traceback stack, whose contentsare ignored by doctest. The traceback stack is typically omitted, or copiedverbatim from an interactive session.

The traceback stack is followed by the most interesting part: the line(s)containing the exception type and detail. This is usually the last line of atraceback, but can extend across multiple lines if the exception has amulti-line detail:

>>>raiseValueError('multi\n    line\ndetail')Traceback (most recent call last):  File"<stdin>", line1, in<module>ValueError:multi    linedetail

The last three lines (starting withValueError) are compared against theexception's type and detail, and the rest are ignored.

Best practice is to omit the traceback stack, unless it adds significantdocumentation value to the example. So the last example is probably better as:

>>>raiseValueError('multi\n    line\ndetail')Traceback (most recent call last):...ValueError:multi    linedetail

Note that tracebacks are treated very specially. In particular, in therewritten example, the use of... is independent of doctest'sELLIPSIS option. The ellipsis in that example could be left out, orcould just as well be three (or three hundred) commas or digits, or an indentedtranscript of a Monty Python skit.

Some details you should read once, but won't need to remember:

  • Doctest can't guess whether your expected output came from an exceptiontraceback or from ordinary printing. So, e.g., an example that expectsValueError:42isprime will pass whetherValueError is actuallyraised or if the example merely prints that traceback text. In practice,ordinary output rarely begins with a traceback header line, so this doesn'tcreate real problems.

  • Each line of the traceback stack (if present) must be indented further thanthe first line of the example,or start with a non-alphanumeric character.The first line following the traceback header indented the same and startingwith an alphanumeric is taken to be the start of the exception detail. Ofcourse this does the right thing for genuine tracebacks.

  • When theIGNORE_EXCEPTION_DETAIL doctest option is specified,everything following the leftmost colon and any module information in theexception name is ignored.

  • The interactive shell omits the traceback header line for someSyntaxErrors. But doctest uses the traceback header line todistinguish exceptions from non-exceptions. So in the rare case where you needto test aSyntaxError that omits the traceback header, you will need tomanually add the traceback header line to your test example.

  • For some exceptions, Python displays the position of the error using^markers and tildes:

    >>>1+None  File"<stdin>", line11+None~~^~~~~~TypeError:unsupported operand type(s) for +: 'int' and 'NoneType'

    Since the lines showing the position of the error come before the exception typeand detail, they are not checked by doctest. For example, the following testwould pass, even though it puts the^ marker in the wrong location:

    >>>1+None  File"<stdin>", line11+None^~~~~~~~TypeError:unsupported operand type(s) for +: 'int' and 'NoneType'

可選旗標

A number of option flags control various aspects of doctest's behavior.Symbolic names for the flags are supplied as module constants, which can bebitwise ORed together and passed to various functions.The names can also be used indoctest directives,and may be passed to the doctest command line interface via the-o option.

The first group of options define test semantics, controlling aspects of howdoctest decides whether actual output matches an example's expected output:

doctest.DONT_ACCEPT_TRUE_FOR_1

By default, if an expected output block contains just1, an actual outputblock containing just1 or justTrue is considered to be a match, andsimilarly for0 versusFalse. WhenDONT_ACCEPT_TRUE_FOR_1 isspecified, neither substitution is allowed. The default behavior caters to thatPython changed the return type of many functions from integer to boolean;doctests expecting "little integer" output still work in these cases. Thisoption will probably go away, but not for several years.

doctest.DONT_ACCEPT_BLANKLINE

By default, if an expected output block contains a line containing only thestring<BLANKLINE>, then that line will match a blank line in the actualoutput. Because a genuinely blank line delimits the expected output, this isthe only way to communicate that a blank line is expected. WhenDONT_ACCEPT_BLANKLINE is specified, this substitution is not allowed.

doctest.NORMALIZE_WHITESPACE

When specified, all sequences of whitespace (blanks and newlines) are treated asequal. Any sequence of whitespace within the expected output will match anysequence of whitespace within the actual output. By default, whitespace mustmatch exactly.NORMALIZE_WHITESPACE is especially useful when a line ofexpected output is very long, and you want to wrap it across multiple lines inyour source.

doctest.ELLIPSIS

When specified, an ellipsis marker (...) in the expected output can matchany substring in the actual output. This includes substrings that span lineboundaries, and empty substrings, so it's best to keep usage of this simple.Complicated uses can lead to the same kinds of "oops, it matched too much!"surprises that.* is prone to in regular expressions.

doctest.IGNORE_EXCEPTION_DETAIL

When specified, doctests expecting exceptions pass so long as an exceptionof the expected type is raised, even if the details(message and fully qualified exception name) don't match.

For example, an example expectingValueError:42 will pass if the actualexception raised isValueError:3*14, but will fail if, say, aTypeError is raised instead.It will also ignore any fully qualified name included before theexception class, which can vary between implementations and versionsof Python and the code/libraries in use.Hence, all three of these variations will work with the flag specified:

>>>raiseException('message')Traceback (most recent call last):Exception:message>>>raiseException('message')Traceback (most recent call last):builtins.Exception:message>>>raiseException('message')Traceback (most recent call last):__main__.Exception:message

Note thatELLIPSIS can also be used to ignore thedetails of the exception message, but such a test may still fail basedon whether the module name is present or matches exactly.

在 3.2 版的變更:IGNORE_EXCEPTION_DETAIL now also ignores any information relatingto the module containing the exception under test.

doctest.SKIP

When specified, do not run the example at all. This can be useful in contextswhere doctest examples serve as both documentation and test cases, and anexample should be included for documentation purposes, but should not bechecked. E.g., the example's output might be random; or the example mightdepend on resources which would be unavailable to the test driver.

The SKIP flag can also be used for temporarily "commenting out" examples.

doctest.COMPARISON_FLAGS

A bitmask or'ing together all the comparison flags above.

The second group of options controls how test failures are reported:

doctest.REPORT_UDIFF

When specified, failures that involve multi-line expected and actual outputs aredisplayed using a unified diff.

doctest.REPORT_CDIFF

When specified, failures that involve multi-line expected and actual outputswill be displayed using a context diff.

doctest.REPORT_NDIFF

When specified, differences are computed bydifflib.Differ, using the samealgorithm as the popularndiff.py utility. This is the only method thatmarks differences within lines as well as across lines. For example, if a lineof expected output contains digit1 where actual output contains letterl, a line is inserted with a caret marking the mismatching column positions.

doctest.REPORT_ONLY_FIRST_FAILURE

When specified, display the first failing example in each doctest, but suppressoutput for all remaining examples. This will prevent doctest from reportingcorrect examples that break because of earlier failures; but it might also hideincorrect examples that fail independently of the first failure. WhenREPORT_ONLY_FIRST_FAILURE is specified, the remaining examples arestill run, and still count towards the total number of failures reported; onlythe output is suppressed.

doctest.FAIL_FAST

When specified, exit after the first failing example and don't attempt to runthe remaining examples. Thus, the number of failures reported will be at most1. This flag may be useful during debugging, since examples after the firstfailure won't even produce debugging output.

doctest.REPORTING_FLAGS

A bitmask or'ing together all the reporting flags above.

There is also a way to register new option flag names, though this isn'tuseful unless you intend to extenddoctest internals via subclassing:

doctest.register_optionflag(name)

Create a new option flag with a given name, and return the new flag's integervalue.register_optionflag() can be used when subclassingOutputChecker orDocTestRunner to create new options that aresupported by your subclasses.register_optionflag() should always becalled using the following idiom:

MY_FLAG=register_optionflag('MY_FLAG')

Directives

Doctest directives may be used to modify theoption flags for an individual example. Doctest directives arespecial Python comments following an example's source code:

directive             ::= "#" "doctest:"directive_optionsdirective_options     ::=directive_option (","directive_option)*directive_option      ::=on_or_offdirective_option_nameon_or_off             ::= "+" | "-"directive_option_name ::= "DONT_ACCEPT_BLANKLINE" | "NORMALIZE_WHITESPACE" | ...

Whitespace is not allowed between the+ or- and the directive optionname. The directive option name can be any of the option flag names explainedabove.

An example's doctest directives modify doctest's behavior for that singleexample. Use+ to enable the named behavior, or- to disable it.

For example, this test passes:

>>>print(list(range(20)))# doctest: +NORMALIZE_WHITESPACE[0,   1,  2,  3,  4,  5,  6,  7,  8,  9,10,  11, 12, 13, 14, 15, 16, 17, 18, 19]

Without the directive it would fail, both because the actual output doesn't havetwo blanks before the single-digit list elements, and because the actual outputis on a single line. This test also passes, and also requires a directive to doso:

>>>print(list(range(20)))# doctest: +ELLIPSIS[0, 1, ..., 18, 19]

Multiple directives can be used on a single physical line, separated bycommas:

>>>print(list(range(20)))# doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE[0,    1, ...,   18,    19]

If multiple directive comments are used for a single example, then they arecombined:

>>>print(list(range(20)))# doctest: +ELLIPSIS...# doctest: +NORMALIZE_WHITESPACE[0,    1, ...,   18,    19]

As the previous example shows, you can add... lines to your examplecontaining only directives. This can be useful when an example is too long fora directive to comfortably fit on the same line:

>>>print(list(range(5))+list(range(10,20))+list(range(30,40)))...# doctest: +ELLIPSIS[0, ..., 4, 10, ..., 19, 30, ..., 39]

Note that since all options are disabled by default, and directives apply onlyto the example they appear in, enabling options (via+ in a directive) isusually the only meaningful choice. However, option flags can also be passed tofunctions that run doctests, establishing different defaults. In such cases,disabling an option via- in a directive can be useful.

警告

doctest is serious about requiring exact matches in expected output. Ifeven a single character doesn't match, the test fails. This will probablysurprise you a few times, as you learn exactly what Python does and doesn'tguarantee about output. For example, when printing a set, Python doesn'tguarantee that the element is printed in any particular order, so a test like

>>>foo(){"spam", "eggs"}

is vulnerable! One workaround is to do

>>>foo()=={"spam","eggs"}True

instead. Another is to do

>>>d=sorted(foo())>>>d['eggs', 'spam']

There are others, but you get the idea.

Another bad idea is to print things that embed an object address, like

>>>id(1.0)# certain to fail some of the time7948648>>>classC:pass>>>C()# the default repr() for instances embeds an address<C object at 0x00AC18F0>

TheELLIPSIS directive gives a nice approach for the last example:

>>>C()# doctest: +ELLIPSIS<C object at 0x...>

Floating-point numbers are also subject to small output variations acrossplatforms, because Python defers to the platform C library for float formatting,and C libraries vary widely in quality here.

>>>1./7# risky0.14285714285714285>>>print(1./7)# safer0.142857142857>>>print(round(1./7,6))# much safer0.142857

Numbers of the formI/2.**J are safe across all platforms, and I oftencontrive doctest examples to produce numbers of that form:

>>>3./4# utterly safe0.75

Simple fractions are also easier for people to understand, and that makes forbetter documentation.

基礎 API

The functionstestmod() andtestfile() provide a simple interface todoctest that should be sufficient for most basic uses. For a less formalintroduction to these two functions, see sectionsSimple Usage: Checking Examples in DocstringsandSimple Usage: Checking Examples in a Text File.

doctest.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)

All arguments exceptfilename are optional, and should be specified in keywordform.

Test examples in the file namedfilename. Return(failure_count,test_count).

Optional argumentmodule_relative specifies how the filename should beinterpreted:

  • Ifmodule_relative isTrue (the default), thenfilename specifies anOS-independent module-relative path. By default, this path is relative to thecalling module's directory; but if thepackage argument is specified, then itis relative to that package. To ensure OS-independence,filename should use/ characters to separate path segments, and may not be an absolute path(i.e., it may not begin with/).

  • Ifmodule_relative isFalse, thenfilename specifies an OS-specificpath. The path may be absolute or relative; relative paths are resolved withrespect to the current working directory.

Optional argumentname gives the name of the test; by default, or ifNone,os.path.basename(filename) is used.

Optional argumentpackage is a Python package or the name of a Python packagewhose directory should be used as the base directory for a module-relativefilename. If no package is specified, then the calling module's directory isused as the base directory for module-relative filenames. It is an error tospecifypackage ifmodule_relative isFalse.

Optional argumentglobs gives a dict to be used as the globals when executingexamples. A new shallow copy of this dict is created for the doctest, so itsexamples start with a clean slate. By default, or ifNone, a new empty dictis used.

Optional argumentextraglobs gives a dict merged into the globals used toexecute examples. This works likedict.update(): ifglobs andextraglobs have a common key, the associated value inextraglobs appears inthe combined dict. By default, or ifNone, no extra globals are used. Thisis an advanced feature that allows parameterization of doctests. For example, adoctest can be written for a base class, using a generic name for the class,then reused to test any number of subclasses by passing anextraglobs dictmapping the generic name to the subclass to be tested.

Optional argumentverbose prints lots of stuff if true, and prints onlyfailures if false; by default, or ifNone, it's true if and only if'-v'is insys.argv.

Optional argumentreport prints a summary at the end when true, else printsnothing at the end. In verbose mode, the summary is detailed, else the summaryis very brief (in fact, empty if all tests passed).

Optional argumentoptionflags (default value 0) takes thebitwise OR of option flags.See section可選旗標.

Optional argumentraise_on_error defaults to false. If true, an exception israised upon the first failure or unexpected exception in an example. Thisallows failures to be post-mortem debugged. Default behavior is to continuerunning examples.

Optional argumentparser specifies aDocTestParser (or subclass) thatshould be used to extract tests from the files. It defaults to a normal parser(i.e.,DocTestParser()).

Optional argumentencoding specifies an encoding that should be used toconvert the file to unicode.

doctest.testmod(m=None,name=None,globs=None,verbose=None,report=True,optionflags=0,extraglobs=None,raise_on_error=False,exclude_empty=False)

All arguments are optional, and all except form should be specified inkeyword form.

Test examples in docstrings in functions and classes reachable from modulem(or module__main__ ifm is not supplied or isNone), starting withm.__doc__.

Also test examples reachable from dictm.__test__, if it exists.m.__test__ maps names (strings) to functions, classes andstrings; function and class docstrings are searched for examples; strings aresearched directly, as if they were docstrings.

Only docstrings attached to objects belonging to modulem are searched.

Return(failure_count,test_count).

Optional argumentname gives the name of the module; by default, or ifNone,m.__name__ is used.

Optional argumentexclude_empty defaults to false. If true, objects for whichno doctests are found are excluded from consideration. The default is a backwardcompatibility hack, so that code still usingdoctest.master.summarize inconjunction withtestmod() continues to get output for objects with notests. Theexclude_empty argument to the newerDocTestFinderconstructor defaults to true.

Optional argumentsextraglobs,verbose,report,optionflags,raise_on_error, andglobs are the same as for functiontestfile()above, except thatglobs defaults tom.__dict__.

doctest.run_docstring_examples(f,globs,verbose=False,name='NoName',compileflags=None,optionflags=0)

Test examples associated with objectf; for example,f may be a string,a module, a function, or a class object.

A shallow copy of dictionary argumentglobs is used for the execution context.

Optional argumentname is used in failure messages, and defaults to"NoName".

If optional argumentverbose is true, output is generated even if there are nofailures. By default, output is generated only in case of an example failure.

Optional argumentcompileflags gives the set of flags that should be used bythe Python compiler when running the examples. By default, or ifNone,flags are deduced corresponding to the set of future features found inglobs.

Optional argumentoptionflags works as for functiontestfile() above.

Unittest API

As your collection of doctest'ed modules grows, you'll want a way to run alltheir doctests systematically.doctest provides two functions that canbe used to createunittest test suites from modules and text filescontaining doctests. To integrate withunittest test discovery, includeaload_tests function in your test module:

importunittestimportdoctestimportmy_module_with_doctestsdefload_tests(loader,tests,ignore):tests.addTests(doctest.DocTestSuite(my_module_with_doctests))returntests

There are two main functions for creatingunittest.TestSuite instancesfrom text files and modules with doctests:

doctest.DocFileSuite(*paths,module_relative=True,package=None,setUp=None,tearDown=None,globs=None,optionflags=0,parser=DocTestParser(),encoding=None)

Convert doctest tests from one or more text files to aunittest.TestSuite.

The returnedunittest.TestSuite is to be run by the unittest frameworkand runs the interactive examples in each file. If an example in any filefails, then the synthesized unit test fails, and afailureExceptionexception is raised showing the name of the file containing the test and a(sometimes approximate) line number. If all the examples in a file areskipped, then the synthesized unit test is also marked as skipped.

Pass one or more paths (as strings) to text files to be examined.

Options may be provided as keyword arguments:

Optional argumentmodule_relative specifies how the filenames inpathsshould be interpreted:

  • Ifmodule_relative isTrue (the default), then each filename inpaths specifies an OS-independent module-relative path. By default, thispath is relative to the calling module's directory; but if thepackageargument is specified, then it is relative to that package. To ensureOS-independence, each filename should use/ characters to separate pathsegments, and may not be an absolute path (i.e., it may not begin with/).

  • Ifmodule_relative isFalse, then each filename inpaths specifiesan OS-specific path. The path may be absolute or relative; relative pathsare resolved with respect to the current working directory.

Optional argumentpackage is a Python package or the name of a Pythonpackage whose directory should be used as the base directory formodule-relative filenames inpaths. If no package is specified, then thecalling module's directory is used as the base directory for module-relativefilenames. It is an error to specifypackage ifmodule_relative isFalse.

Optional argumentsetUp specifies a set-up function for the test suite.This is called before running the tests in each file. ThesetUp functionwill be passed aDocTest object. The setUp function can access thetest globals as theglobs attribute of the test passed.

Optional argumenttearDown specifies a tear-down function for the testsuite. This is called after running the tests in each file. ThetearDownfunction will be passed aDocTest object. The setUp function canaccess the test globals as theglobs attribute of the test passed.

Optional argumentglobs is a dictionary containing the initial globalvariables for the tests. A new copy of this dictionary is created for eachtest. By default,globs is a new empty dictionary.

Optional argumentoptionflags specifies the default doctest options for thetests, created by or-ing together individual option flags. See section可選旗標. See functionset_unittest_reportflags() belowfor a better way to set reporting options.

Optional argumentparser specifies aDocTestParser (or subclass)that should be used to extract tests from the files. It defaults to a normalparser (i.e.,DocTestParser()).

Optional argumentencoding specifies an encoding that should be used toconvert the file to unicode.

The global__file__ is added to the globals provided to doctests loadedfrom a text file usingDocFileSuite().

doctest.DocTestSuite(module=None,globs=None,extraglobs=None,test_finder=None,setUp=None,tearDown=None,optionflags=0,checker=None)

Convert doctest tests for a module to aunittest.TestSuite.

The returnedunittest.TestSuite is to be run by the unittest frameworkand runs each doctest in the module. If any of the doctests fail, then thesynthesized unit test fails, and afailureException exception is raisedshowing the name of the file containing the test and a (sometimes approximate)line number. If all the examples in a docstring are skipped, then thesynthesized unit test is also marked as skipped.

Optional argumentmodule provides the module to be tested. It can be a moduleobject or a (possibly dotted) module name. If not specified, the module callingthis function is used.

Optional argumentglobs is a dictionary containing the initial globalvariables for the tests. A new copy of this dictionary is created for eachtest. By default,globs is a new empty dictionary.

Optional argumentextraglobs specifies an extra set of global variables, whichis merged intoglobs. By default, no extra globals are used.

Optional argumenttest_finder is theDocTestFinder object (or adrop-in replacement) that is used to extract doctests from the module.

Optional argumentssetUp,tearDown, andoptionflags are the same as forfunctionDocFileSuite() above.

This function uses the same search technique astestmod().

在 3.5 版的變更:DocTestSuite() returns an emptyunittest.TestSuite ifmodulecontains no docstrings instead of raisingValueError.

exceptiondoctest.failureException

When doctests which have been converted to unit tests byDocFileSuite()orDocTestSuite() fail, this exception is raised showing the name ofthe file containing the test and a (sometimes approximate) line number.

Under the covers,DocTestSuite() creates aunittest.TestSuite outofdoctest.DocTestCase instances, andDocTestCase is asubclass ofunittest.TestCase.DocTestCase isn't documentedhere (it's an internal detail), but studying its code can answer questions aboutthe exact details ofunittest integration.

Similarly,DocFileSuite() creates aunittest.TestSuite out ofdoctest.DocFileCase instances, andDocFileCase is a subclassofDocTestCase.

So both ways of creating aunittest.TestSuite run instances ofDocTestCase. This is important for a subtle reason: when you rundoctest functions yourself, you can control thedoctest options inuse directly, by passing option flags todoctest functions. However, ifyou're writing aunittest framework,unittest ultimately controlswhen and how tests get run. The framework author typically wants to controldoctest reporting options (perhaps, e.g., specified by command lineoptions), but there's no way to pass options throughunittest todoctest test runners.

For this reason,doctest also supports a notion ofdoctestreporting flags specific tounittest support, via this function:

doctest.set_unittest_reportflags(flags)

Set thedoctest reporting flags to use.

Argumentflags takes thebitwise OR of option flags. Seesection可選旗標. Only "reporting flags" can be used.

This is a module-global setting, and affects all future doctests run by moduleunittest: therunTest() method ofDocTestCase looks atthe option flags specified for the test case when theDocTestCaseinstance was constructed. If no reporting flags were specified (which is thetypical and expected case),doctest'sunittest reporting flags arebitwise ORed into the option flags, and the option flagsso augmented are passed to theDocTestRunner instance created torun the doctest. If any reporting flags were specified when theDocTestCase instance was constructed,doctest'sunittest reporting flags are ignored.

The value of theunittest reporting flags in effect before the functionwas called is returned by the function.

Advanced API

The basic API is a simple wrapper that's intended to make doctest easy to use.It is fairly flexible, and should meet most users' needs; however, if yourequire more fine-grained control over testing, or wish to extend doctest'scapabilities, then you should use the advanced API.

The advanced API revolves around two container classes, which are used to storethe interactive examples extracted from doctest cases:

  • Example: A single Pythonstatement, paired with its expectedoutput.

  • DocTest: A collection ofExamples, typically extractedfrom a single docstring or text file.

Additional processing classes are defined to find, parse, and run, and checkdoctest examples:

The relationships among these processing classes are summarized in the followingdiagram:

listof:+------++---------+|module|--DocTestFinder->|DocTest|--DocTestRunner->results+------+|^+---------+|^(printed)|||Example|||v||...|v|DocTestParser|Example|OutputChecker+---------+

DocTest 物件

classdoctest.DocTest(examples,globs,name,filename,lineno,docstring)

A collection of doctest examples that should be run in a single namespace. Theconstructor arguments are used to initialize the attributes of the same names.

DocTest defines the following attributes. They are initialized bythe constructor, and should not be modified directly.

examples

A list ofExample objects encoding the individual interactive Pythonexamples that should be run by this test.

globs

The namespace (aka globals) that the examples should be run in. This is adictionary mapping names to values. Any changes to the namespace made by theexamples (such as binding new variables) will be reflected inglobsafter the test is run.

name

A string name identifying theDocTest. Typically, this is the nameof the object or file that the test was extracted from.

filename

The name of the file that thisDocTest was extracted from; orNone if the filename is unknown, or if theDocTest was notextracted from a file.

lineno

The line number withinfilename where thisDocTest begins, orNone if the line number is unavailable. This line number is zero-basedwith respect to the beginning of the file.

docstring

The string that the test was extracted from, orNone if the string isunavailable, or if the test was not extracted from a string.

Example 物件

classdoctest.Example(source,want,exc_msg=None,lineno=0,indent=0,options=None)

A single interactive example, consisting of a Python statement and its expectedoutput. The constructor arguments are used to initialize the attributes ofthe same names.

Example defines the following attributes. They are initialized bythe constructor, and should not be modified directly.

source

A string containing the example's source code. This source code consists of asingle Python statement, and always ends with a newline; the constructor addsa newline when necessary.

want

The expected output from running the example's source code (either fromstdout, or a traceback in case of exception).want ends with anewline unless no output is expected, in which case it's an empty string. Theconstructor adds a newline when necessary.

exc_msg

The exception message generated by the example, if the example is expected togenerate an exception; orNone if it is not expected to generate anexception. This exception message is compared against the return value oftraceback.format_exception_only().exc_msg ends with a newlineunless it'sNone. The constructor adds a newline if needed.

lineno

The line number within the string containing this example where the examplebegins. This line number is zero-based with respect to the beginning of thecontaining string.

indent

The example's indentation in the containing string, i.e., the number of spacecharacters that precede the example's first prompt.

options

A dictionary mapping from option flags toTrue orFalse, which is usedto override default options for this example. Any option flags not containedin this dictionary are left at their default value (as specified by theDocTestRunner'soptionflags).By default, no options are set.

DocTestFinder 物件

classdoctest.DocTestFinder(verbose=False,parser=DocTestParser(),recurse=True,exclude_empty=True)

A processing class used to extract theDocTests that are relevant toa given object, from its docstring and the docstrings of its contained objects.DocTests can be extracted from modules, classes, functions,methods, staticmethods, classmethods, and properties.

The optional argumentverbose can be used to display the objects searched bythe finder. It defaults toFalse (no output).

The optional argumentparser specifies theDocTestParser object (or adrop-in replacement) that is used to extract doctests from docstrings.

If the optional argumentrecurse is false, thenDocTestFinder.find()will only examine the given object, and not any contained objects.

If the optional argumentexclude_empty is false, thenDocTestFinder.find() will include tests for objects with empty docstrings.

DocTestFinder defines the following method:

find(obj[,name][,module][,globs][,extraglobs])

Return a list of theDocTests that are defined byobj'sdocstring, or by any of its contained objects' docstrings.

The optional argumentname specifies the object's name; this name will beused to construct names for the returnedDocTests. Ifname isnot specified, thenobj.__name__ is used.

The optional parametermodule is the module that contains the given object.If the module is not specified or isNone, then the test finder will attemptto automatically determine the correct module. The object's module is used:

  • As a default namespace, ifglobs is not specified.

  • To prevent the DocTestFinder from extracting DocTests from objects that areimported from other modules. (Contained objects with modules other thanmodule are ignored.)

  • To find the name of the file containing the object.

  • To help find the line number of the object within its file.

Ifmodule isFalse, no attempt to find the module will be made. This isobscure, of use mostly in testing doctest itself: ifmodule isFalse, orisNone but cannot be found automatically, then all objects are consideredto belong to the (non-existent) module, so all contained objects will(recursively) be searched for doctests.

The globals for eachDocTest is formed by combiningglobs andextraglobs (bindings inextraglobs override bindings inglobs). A newshallow copy of the globals dictionary is created for eachDocTest.Ifglobs is not specified, then it defaults to the module's__dict__, ifspecified, or{} otherwise. Ifextraglobs is not specified, then itdefaults to{}.

DocTestParser 物件

classdoctest.DocTestParser

A processing class used to extract interactive examples from a string, and usethem to create aDocTest object.

DocTestParser defines the following methods:

get_doctest(string,globs,name,filename,lineno)

Extract all doctest examples from the given string, and collect them into aDocTest object.

globs,name,filename, andlineno are attributes for the newDocTest object. See the documentation forDocTest for moreinformation.

get_examples(string,name='<string>')

Extract all doctest examples from the given string, and return them as a listofExample objects. Line numbers are 0-based. The optional argumentname is a name identifying this string, and is only used for error messages.

parse(string,name='<string>')

Divide the given string into examples and intervening text, and return them asa list of alternatingExamples and strings. Line numbers for theExamples are 0-based. The optional argumentname is a nameidentifying this string, and is only used for error messages.

TestResults 物件

classdoctest.TestResults(failed,attempted)
failed

Number of failed tests.

attempted

Number of attempted tests.

skipped

Number of skipped tests.

在 3.13 版被加入.

DocTestRunner 物件

classdoctest.DocTestRunner(checker=None,verbose=None,optionflags=0)

A processing class used to execute and verify the interactive examples in aDocTest.

The comparison between expected outputs and actual outputs is done by anOutputChecker. This comparison may be customized with a number ofoption flags; see section可選旗標 for more information. If theoption flags are insufficient, then the comparison may also be customized bypassing a subclass ofOutputChecker to the constructor.

The test runner's display output can be controlled in two ways. First, an outputfunction can be passed torun(); this function will be calledwith strings that should be displayed. It defaults tosys.stdout.write. Ifcapturing the output is not sufficient, then the display output can be alsocustomized by subclassing DocTestRunner, and overriding the methodsreport_start(),report_success(),report_unexpected_exception(), andreport_failure().

The optional keyword argumentchecker specifies theOutputCheckerobject (or drop-in replacement) that should be used to compare the expectedoutputs to the actual outputs of doctest examples.

The optional keyword argumentverbose controls theDocTestRunner'sverbosity. Ifverbose isTrue, then information is printed about eachexample, as it is run. Ifverbose isFalse, then only failures areprinted. Ifverbose is unspecified, orNone, then verbose output is usediff the command-line switch-v is used.

The optional keyword argumentoptionflags can be used to control how the testrunner compares expected output to actual output, and how it displays failures.For more information, see section可選旗標.

The test runner accumulates statistics. The aggregated number of attempted,failed and skipped examples is also available via thetries,failures andskips attributes. Therun() andsummarize() methods return aTestResults instance.

DocTestRunner defines the following methods:

report_start(out,test,example)

Report that the test runner is about to process the given example. This methodis provided to allow subclasses ofDocTestRunner to customize theiroutput; it should not be called directly.

example is the example about to be processed.test is the testcontaining example.out is the output function that was passed toDocTestRunner.run().

report_success(out,test,example,got)

Report that the given example ran successfully. This method is provided toallow subclasses ofDocTestRunner to customize their output; itshould not be called directly.

example is the example about to be processed.got is the actual outputfrom the example.test is the test containingexample.out is theoutput function that was passed toDocTestRunner.run().

report_failure(out,test,example,got)

Report that the given example failed. This method is provided to allowsubclasses ofDocTestRunner to customize their output; it should notbe called directly.

example is the example about to be processed.got is the actual outputfrom the example.test is the test containingexample.out is theoutput function that was passed toDocTestRunner.run().

report_unexpected_exception(out,test,example,exc_info)

Report that the given example raised an unexpected exception. This method isprovided to allow subclasses ofDocTestRunner to customize theiroutput; it should not be called directly.

example is the example about to be processed.exc_info is a tuplecontaining information about the unexpected exception (as returned bysys.exc_info()).test is the test containingexample.out is theoutput function that was passed toDocTestRunner.run().

run(test,compileflags=None,out=None,clear_globs=True)

Run the examples intest (aDocTest object), and display theresults using the writer functionout. Return aTestResultsinstance.

The examples are run in the namespacetest.globs. Ifclear_globs istrue (the default), then this namespace will be cleared after the test runs,to help with garbage collection. If you would like to examine the namespaceafter the test completes, then useclear_globs=False.

compileflags gives the set of flags that should be used by the Pythoncompiler when running the examples. If not specified, then it will default tothe set of future-import flags that apply toglobs.

The output of each example is checked using theDocTestRunner'soutput checker, and the results are formatted by theDocTestRunner.report_*() methods.

summarize(verbose=None)

Print a summary of all the test cases that have been run by this DocTestRunner,and return aTestResults instance.

The optionalverbose argument controls how detailed the summary is. If theverbosity is not specified, then theDocTestRunner's verbosity isused.

DocTestParser 有以下屬性:

tries

Number of attempted examples.

failures

Number of failed examples.

skips

Number of skipped examples.

在 3.13 版被加入.

OutputChecker 物件

classdoctest.OutputChecker

A class used to check the whether the actual output from a doctest examplematches the expected output.OutputChecker defines two methods:check_output(), which compares a given pair of outputs, and returnsTrueif they match; andoutput_difference(), which returns a string describingthe differences between two outputs.

OutputChecker defines the following methods:

check_output(want,got,optionflags)

ReturnTrue iff the actual output from an example (got) matches theexpected output (want). These strings are always considered to match ifthey are identical; but depending on what option flags the test runner isusing, several non-exact match types are also possible. See section可選旗標 for more information about option flags.

output_difference(example,got,optionflags)

Return a string describing the differences between the expected output for agiven example (example) and the actual output (got).optionflags is theset of option flags used to comparewant andgot.

Debugging

Doctest provides several mechanisms for debugging doctest examples:

  • Several functions convert doctests to executable Python programs, which can berun under the Python debugger,pdb.

  • TheDebugRunner class is a subclass ofDocTestRunner thatraises an exception for the first failing example, containing information aboutthat example. This information can be used to perform post-mortem debugging onthe example.

  • Theunittest cases generated byDocTestSuite() support thedebug() method defined byunittest.TestCase.

  • You can add a call topdb.set_trace() in a doctest example, and you'lldrop into the Python debugger when that line is executed. Then you can inspectcurrent values of variables, and so on. For example, supposea.pycontains just this module docstring:

    """>>> def f(x):...     g(x*2)>>> def g(x):...     print(x+3)...     import pdb; pdb.set_trace()>>> f(3)9"""

    Then an interactive Python session may look like this:

    >>>importa,doctest>>>doctest.testmod(a)--Return--> <doctest a[1]>(3)g()->None-> import pdb; pdb.set_trace()(Pdb) list  1     def g(x):  2         print(x+3)  3  ->     import pdb; pdb.set_trace()[EOF](Pdb) p x6(Pdb) step--Return--> <doctest a[0]>(2)f()->None-> g(x*2)(Pdb) list  1     def f(x):  2  ->     g(x*2)[EOF](Pdb) p x3(Pdb) step--Return--> <doctest a[2]>(1)?()->None-> f(3)(Pdb) cont(0, 3)>>>

Functions that convert doctests to Python code, and possibly run the synthesizedcode under the debugger:

doctest.script_from_examples(s)

Convert text with examples to a script.

Arguments is a string containing doctest examples. The string is convertedto a Python script, where doctest examples ins are converted to regular code,and everything else is converted to Python comments. The generated script isreturned as a string. For example,

importdoctestprint(doctest.script_from_examples(r"""    Set x and y to 1 and 2.    >>> x, y = 1, 2    Print their sum:    >>> print(x+y)    3"""))

displays:

# Set x and y to 1 and 2.x,y=1,2## Print their sum:print(x+y)# Expected:## 3

This function is used internally by other functions (see below), but can also beuseful when you want to transform an interactive Python session into a Pythonscript.

doctest.testsource(module,name)

Convert the doctest for an object to a script.

Argumentmodule is a module object, or dotted name of a module, containing theobject whose doctests are of interest. Argumentname is the name (within themodule) of the object with the doctests of interest. The result is a string,containing the object's docstring converted to a Python script, as described forscript_from_examples() above. For example, if modulea.pycontains a top-level functionf(), then

importa,doctestprint(doctest.testsource(a,"a.f"))

prints a script version of functionf()'s docstring, with doctestsconverted to code, and the rest placed in comments.

doctest.debug(module,name,pm=False)

Debug the doctests for an object.

Themodule andname arguments are the same as for functiontestsource() above. The synthesized Python script for the named object'sdocstring is written to a temporary file, and then that file is run under thecontrol of the Python debugger,pdb.

A shallow copy ofmodule.__dict__ is used for both local and globalexecution context.

Optional argumentpm controls whether post-mortem debugging is used. Ifpmhas a true value, the script file is run directly, and the debugger getsinvolved only if the script terminates via raising an unhandled exception. Ifit does, then post-mortem debugging is invoked, viapdb.post_mortem(),passing the traceback object from the unhandled exception. Ifpm is notspecified, or is false, the script is run under the debugger from the start, viapassing an appropriateexec() call topdb.run().

doctest.debug_src(src,pm=False,globs=None)

Debug the doctests in a string.

This is like functiondebug() above, except that a string containingdoctest examples is specified directly, via thesrc argument.

Optional argumentpm has the same meaning as in functiondebug() above.

Optional argumentglobs gives a dictionary to use as both local and globalexecution context. If not specified, orNone, an empty dictionary is used.If specified, a shallow copy of the dictionary is used.

TheDebugRunner class, and the special exceptions it may raise, are ofmost interest to testing framework authors, and will only be sketched here. Seethe source code, and especiallyDebugRunner's docstring (which is adoctest!) for more details:

classdoctest.DebugRunner(checker=None,verbose=None,optionflags=0)

A subclass ofDocTestRunner that raises an exception as soon as afailure is encountered. If an unexpected exception occurs, anUnexpectedException exception is raised, containing the test, theexample, and the original exception. If the output doesn't match, then aDocTestFailure exception is raised, containing the test, the example, andthe actual output.

For information about the constructor parameters and methods, see thedocumentation forDocTestRunner in sectionAdvanced API.

There are two exceptions that may be raised byDebugRunner instances:

exceptiondoctest.DocTestFailure(test,example,got)

An exception raised byDocTestRunner to signal that a doctest example'sactual output did not match its expected output. The constructor arguments areused to initialize the attributes of the same names.

DocTestFailure 定義了以下屬性:

DocTestFailure.test

TheDocTest object that was being run when the example failed.

DocTestFailure.example

TheExample that failed.

DocTestFailure.got

The example's actual output.

exceptiondoctest.UnexpectedException(test,example,exc_info)

An exception raised byDocTestRunner to signal that a doctestexample raised an unexpected exception. The constructor arguments are usedto initialize the attributes of the same names.

UnexpectedException defines the following attributes:

UnexpectedException.test

TheDocTest object that was being run when the example failed.

UnexpectedException.example

TheExample that failed.

UnexpectedException.exc_info

A tuple containing information about the unexpected exception, as returned bysys.exc_info().

Soapbox

As mentioned in the introduction,doctest has grown to have three primaryuses:

  1. Checking examples in docstrings.

  2. Regression testing.

  3. Executable documentation / literate testing.

These uses have different requirements, and it is important to distinguish them.In particular, filling your docstrings with obscure test cases makes for baddocumentation.

When writing a docstring, choose docstring examples with care. There's an art tothis that needs to be learned---it may not be natural at first. Examples shouldadd genuine value to the documentation. A good example can often be worth manywords. If done with care, the examples will be invaluable for your users, andwill pay back the time it takes to collect them many times over as the years goby and things change. I'm still amazed at how often one of mydoctestexamples stops working after a "harmless" change.

Doctest also makes an excellent tool for regression testing, especially if youdon't skimp on explanatory text. By interleaving prose and examples, it becomesmuch easier to keep track of what's actually being tested, and why. When a testfails, good prose can make it much easier to figure out what the problem is, andhow it should be fixed. It's true that you could write extensive comments incode-based testing, but few programmers do. Many have found that using doctestapproaches instead leads to much clearer tests. Perhaps this is simply becausedoctest makes writing prose a little easier than writing code, while writingcomments in code is a little harder. I think it goes deeper than just that:the natural attitude when writing a doctest-based test is that you want toexplain the fine points of your software, and illustrate them with examples.This in turn naturally leads to test files that start with the simplestfeatures, and logically progress to complications and edge cases. A coherentnarrative is the result, instead of a collection of isolated functions that testisolated bits of functionality seemingly at random. It's a different attitude,and produces different results, blurring the distinction between testing andexplaining.

Regression testing is best confined to dedicated objects or files. There areseveral options for organizing tests:

  • Write text files containing test cases as interactive examples, and test thefiles usingtestfile() orDocFileSuite(). This is recommended,although is easiest to do for new projects, designed from the start to usedoctest.

  • Define functions named_regrtest_topic that consist of single docstrings,containing test cases for the named topics. These functions can be included inthe same file as the module, or separated out into a separate test file.

  • Define a__test__ dictionary mapping from regression test topics todocstrings containing test cases.

When you have placed your tests in a module, the module can itself be the testrunner. When a test fails, you can arrange for your test runner to re-run onlythe failing doctest while you debug the problem. Here is a minimal example ofsuch a test runner:

if__name__=='__main__':importdoctestflags=doctest.REPORT_NDIFF|doctest.FAIL_FASTiflen(sys.argv)>1:name=sys.argv[1]ifnameinglobals():obj=globals()[name]else:obj=__test__[name]doctest.run_docstring_examples(obj,globals(),name=name,optionflags=flags)else:fail,total=doctest.testmod(optionflags=flags)print(f"{fail} failures out of{total} tests")

註腳

[1]

Examples containing both expected output and an exception are not supported.Trying to guess where one ends and the other begins is too error-prone, and thatalso makes for a confusing test.