doctestTest interactive Python examples测试交互式Python示例

Source code: Lib/doctest.py


The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. doctest模块搜索看起来像交互式Python会话的文本片段,然后执行这些会话以验证它们是否完全如图所示工作。There are several common ways to use doctest:使用doctest有几种常见方法:

  • To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.检查模块的文档字符串是否是最新的,方法是验证所有交互示例是否仍按文档所示工作。

  • To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.通过验证测试文件或测试对象中的交互示例是否按预期工作来执行回归测试。

  • To write tutorial documentation for a package, liberally illustrated with input-output examples. 为软件包编写教程文档,并用输入输出示例进行详细说明。Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.根据强调的是示例还是解释性文本,这具有“识字测试”或“可执行文档”的味道。

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
"""

def factorial(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
"""

import math
if not n >= 0:
raise ValueError("n must be >= 0")
if math.floor(n) != n:
raise ValueError("n must be exact integer")
if n+1 == n: # catch a value like 1e300
raise OverflowError("n too large")
result = 1
factor = 2
while factor <= n:
result *= factor
factor += 1
return result


if __name__ == "__main__":
import doctest
doctest.testmod()

If you run example.py directly from the command line, doctest works its magic:如果您直接从命令行运行example.pydoctest就会发挥作用:

$ python example.py
$

There’s no output! 没有输出!That’s normal, and it means all the examples worked. 这很正常,这意味着所有的例子都奏效了。Pass -v to the script, and doctest prints a detailed log of what it’s trying, and prints a summary at the end:-v传递给脚本,doctest将打印它正在尝试的内容的详细日志,并在最后打印摘要:

$ python example.py -v
Trying:
factorial(5)
Expecting:
120
ok
Trying:
[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 large
ok
2 items passed all tests:
1 tests in __main__
8 tests in __main__.factorial
9 tests in 2 items.
9 passed and 0 failed.
Test passed.
$

That’s all you need to know to start making productive use of doctest!这就是开始高效使用doctest所需的全部知识! Jump in. 跳进去。The following sections provide full details. 以下各节提供了详细信息。Note that there are many examples of doctests in the standard Python test suite and libraries. 注意,标准Python测试套件和库中有许多doctest的示例。Especially useful examples can be found in the standard test file Lib/test/test_doctest.py.在标准测试文件Lib/test/test_doctest.py中可以找到特别有用的示例。

Simple Usage: Checking Examples in Docstrings简单用法:检查Docstring中的示例

The simplest way to start using doctest (but not necessarily the way you’ll continue to do it) is to end each module M with:开始使用doctest的最简单方法(但不一定是继续使用的方法)是以以下方式结束每个模块M

if __name__ == "__main__":
import doctest
doctest.testmod()

doctest then examines docstrings in module M.然后检查模块M中的文档字符串。

Running the module as a script causes the examples in the docstrings to get executed and verified:将模块作为脚本运行会导致文档字符串中的示例得到执行和验证:

python M.py

This won’t display anything unless an example fails, in which case the failing example(s) and the cause(s) of the failure(s) are printed to stdout, and the final line of output is ***Test Failed*** N failures., where N is the number of examples that failed.除非示例失败,否则不会显示任何内容,在这种情况下,失败的示例和失败的原因将打印到stdout,输出的最后一行是***Test Failed*** N failures.,其中N是失败的示例数。

Run it with the -v switch instead:改为使用-v开关运行:

python M.py -v

and a detailed report of all examples tried is printed to standard output, along with assorted summaries at the end.并将所有尝试的示例的详细报告打印到标准输出中,最后附上各种摘要。

You can force verbose mode by passing verbose=True to testmod(), or prohibit it by passing verbose=False. 您可以通过将verbose=True传递给testmod()来强制verbose模式,或者通过传递verbose=False来禁止它。In either of those cases, sys.argv is not examined by testmod() (so passing -v or not has no effect).在这两种情况下,testmod()都不会检查sys.argv(因此,传递-v或不传递-v都没有效果)。

There is also a command line shortcut for running testmod(). 还有一个用于运行testmod()的命令行快捷方式。You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the module name(s) on the command line:您可以指示Python解释器直接从标准库运行doctest模块,并在命令行上传递模块名称:

python -m doctest -v example.py

This will import example.py as a standalone module and run testmod() on it. 这将导入example.py作为一个独立模块,并在其上运行testmod()Note that this may not work correctly if the file is part of a package and imports other submodules from that package.请注意,如果文件是包的一部分并从该包中导入其他子模块,则这可能无法正常工作。

For more information on testmod(), see section Basic API.有关testmod()的更多信息,请参阅基本API部分

Simple Usage: Checking Examples in a Text File简单用法:检查文本文件中的示例

Another simple application of doctest is testing interactive examples in a text file. doctest的另一个简单应用程序是测试文本文件中的交互示例。This can be done with the testfile() function:这可以通过testfile()函数完成:

import doctest
doctest.testfile("example.txt")

That short script executes and verifies any interactive Python examples contained in the file example.txt. 该短脚本执行并验证文件example.txt中包含的任何交互式Python示例。The file content is treated as if it were a single giant docstring; the file doesn’t need to contain a Python program! 文件内容被视为一个巨大的文档字符串;文件不需要包含Python程序! For example, perhaps example.txt contains this:例如,examplet.ext可能包含以下内容:

The ``example`` module
======================
Using ``factorial``
-------------------

This is an example text file in reStructuredText format. First import
``factorial`` from the ``example`` module:

>>> from example import factorial

Now use it:

>>> factorial(6)
120

Running doctest.testfile("example.txt") then finds the error in this documentation:运行doctest.testfile("example.txt"),然后在以下文档中找到错误:

File "./example.txt", line 14, in example.txt
Failed example:
factorial(6)
Expected:
120
Got:
720

As with testmod(), testfile() won’t display anything unless an example fails. testmod()一样,除非示例失败,否则testfile()不会显示任何内容。If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to stdout, using the same format as testmod().如果某个示例确实失败,则使用与testmod()相同的格式将失败的示例和失败原因打印到stdout。

By default, testfile() looks for files in the calling module’s directory. 默认情况下,testfile()在调用模块的目录中查找文件。See section Basic API for a description of the optional arguments that can be used to tell it to look for files in other locations.有关可选参数的描述,请参阅Basic API部分,这些参数可用于告诉它在其他位置查找文件。

Like testmod(), testfile()’s verbosity can be set with the -v command-line switch or with the optional keyword argument verbose.testmod()一样,可以使用-v命令行开关或可选关键字参数verbose设置testfile()的详细信息。

There is also a command line shortcut for running testfile(). 还有一个用于运行testfile()的命令行快捷方式。You can instruct the Python interpreter to run the doctest module directly from the standard library and pass the file name(s) on the command line:您可以指示Python解释器直接从标准库运行doctest模块,并在命令行上传递文件名:

python -m doctest -v example.txt

Because the file name does not end with .py, doctest infers that it must be run with testfile(), not testmod().由于文件名不以.py结尾,testfile()推断它必须使用testfile()而不是testmod()运行。

For more information on testfile(), see section Basic API.有关testfile()的更多信息,请参阅基本API部分

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 it handles exceptions, and how option flags can be used to control its behavior. 本节详细检查doctest的工作原理:它查看哪些docstring,如何查找交互示例,使用什么执行上下文,如何处理异常,以及如何使用选项标志来控制其行为。This is the information that you need to know to write doctest examples; for information about actually running doctest on these examples, see the following sections.这是编写doctest示例所需了解的信息;有关在这些示例上实际运行doctest的信息,请参阅以下部分。

Which Docstrings Are Examined?检查了哪些Docstring?

The module docstring, and all function, class and method docstrings are searched. 搜索模块docstring以及所有函数、类和方法docstring。Objects imported into the module are not searched.不会搜索导入模块的对象。

In addition, if M.__test__ exists and “is true”, it must be a dict, and each entry maps a (string) name to a function object, class object, or string. 此外,如果M.__test__存在并且“为真”,则它必须是一个dict,并且每个条目都将一个(字符串)名称映射到函数对象、类对象或字符串。Function and class object docstrings found from M.__test__ are searched, and strings are treated as if they were docstrings. 搜索从M.__test__中找到的函数和类对象docstring,并将字符串视为docstring。In output, a key K in M.__test__ appears with name在输出中,M.__test__中的键K显示为名称

<name of M>.__test__.K

Any classes found are recursively searched similarly, to test docstrings in their contained methods and nested classes.找到的任何类都会进行类似的递归搜索,以测试其包含的方法和嵌套类中的文档字符串。

CPython implementation detail:CPython实施细节: Prior to version 3.4, extension modules written in C were not fully searched by doctest.在3.4版之前,doctest没有完全搜索用C编写的扩展模块。

How are Docstring Examples Recognized?如何识别Docstring示例?

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.在大多数情况下,交互式控制台会话的复制和粘贴工作正常,但doctest并不试图对任何特定的Python shell进行精确模拟。

>>> # comments are ignored
>>> x = 12
>>> x
12
>>> if x == 13:
... print("yes")
... else:
... print("no")
... print("NO")
... print("NO!!!")
...
no
NO
NO!!!
>>>

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 is taken to signal the end of expected output. 预期输出不能包含全空白行,因为这样的行被用来表示预期输出的结束。If expected output does contain a blank line, put <BLANKLINE> in your doctest example each place a blank line is expected.如果预期输出包含空行,请在doctest示例中放置<BLANKLINE>,每个地方都需要空行。

  • All hard tab characters are expanded to spaces, using 8-column tab stops. 使用8列制表位将所有硬制表位字符扩展为空格。Tabs in output generated by the tested code are not modified. 测试代码生成的输出中的选项卡不会被修改。Because any hard tabs in the sample output are expanded, this means that if the code output includes hard tabs, the only way the doctest can pass is if the NORMALIZE_WHITESPACE option or directive is in effect. 由于示例输出中的任何硬选项卡都已展开,这意味着如果代码输出包含硬选项卡,则指令可以通过的唯一方式是NORMALIZE_WHITESPACE选项或指令是否有效。Alternatively, the test can be rewritten to capture the output and compare it to an expected value as part of the test. 或者,作为测试的一部分,可以重写测试以捕获输出并将其与预期值进行比较。This handling of tabs in the source was arrived at through trial and error, and has proven to be the least error prone way of handling them. 在源代码中对标签的这种处理是经过反复尝试而得到的,并且被证明是最不容易出错的处理方法。It is possible to use a different algorithm for handling tabs by writing a custom DocTestParser class.通过编写自定义DocTestParser类,可以使用不同的算法来处理选项卡。

  • Output to stdout is captured, but not output to stderr (exception tracebacks are captured via a different means).捕获到stdout的输出,但不捕获到stderr的输出(通过不同的方法捕获异常回溯)。

  • If you continue a line via backslashing in an interactive session, or for any other reason use a backslash, you should use a raw docstring, which will preserve your backslashes exactly as you type them:如果在交互式会话中通过反斜杠继续一行,或出于任何其他原因使用反斜杠,则应使用原始文档字符串,该字符串将在键入反斜杠时保留反斜杠:

    >>> def f(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. 例如,上面的\n将被解释为换行符。Alternatively, you can double each backslash in the doctest version (and not use a raw string):或者,您可以在doctest版本中将每个反斜杠加倍(而不使用原始字符串):

    >>> def f(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 output as appeared in the initial '>>> ' line that started the example.并且从预期输出中删除了许多前导空白字符,如开始示例的初始'>>> '行中所示。

What’s the Execution Context?执行环境是什么?

By default, each time doctest finds a docstring to test, it uses a shallow copy of M’s globals, so that running tests doesn’t change the module’s real globals, and so that one test in M can’t leave behind crumbs that accidentally allow another test to work. 默认情况下,每次doctest找到要测试的docstring时,它都会使用M的全局变量的浅拷贝,这样运行测试就不会更改模块的真实全局变量,这样M中的一个测试就不会留下意外允许另一个测试工作的碎屑。This means examples can freely use any names defined at top-level in M, and names defined earlier in the docstring being run. Examples cannot see names defined in other docstrings.这意味着示例可以自由使用M中顶层定义的任何名称,以及在运行的文档字符串中前面定义的名称。示例无法看到其他文档字符串中定义的名称。

You can force use of your own dict as the execution context by passing globs=your_dict to testmod() or testfile() instead.通过将globs=your_dict传递给testmod()testfile(),可以强制使用自己的dict作为执行上下文。

What About Exceptions?例外情况如何?

No problem, provided that the traceback is the only output produced by the example: just paste in the traceback. 没有问题,前提是回溯是该示例生成的唯一输出:只需粘贴回溯即可。1 Since tracebacks contain details that are likely to change rapidly (for example, exact file paths and line numbers), this is one case where doctest works hard to be flexible in what it accepts.由于回溯包含可能快速更改的详细信息(例如,确切的文件路径和行号),这是doctest努力灵活接受的一种情况。

Simple example:简单示例:

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

That doctest succeeds if ValueError is raised, with the list.remove(x): x not in list detail as shown.如果引发ValueError,并且带有list.remove(x): x not in list的细节,则doctest成功。

The expected output for an exception must start with a traceback header, which may be either of the following two lines, indented the same as the first line of the example:异常的预期输出必须以回溯标头开头,该标头可以是以下两行之一,缩进与示例的第一行相同:

Traceback (most recent call last):
Traceback (innermost last):

The traceback header is followed by an optional traceback stack, whose contents are ignored by doctest. 回溯头后面是可选的回溯堆栈,doctest将忽略其内容。The traceback stack is typically omitted, or copied verbatim 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 a traceback, but can extend across multiple lines if the exception has a multi-line detail:这通常是回溯的最后一行,但如果异常具有多行详细信息,则可以跨多行扩展:

>>> raise ValueError('multi\n    line\ndetail')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: multi
line
detail

The last three lines (starting with ValueError) are compared against the exception’s type and detail, and the rest are ignored.最后三行(以ValueError开头)将与异常的类型和详细信息进行比较,其余的将被忽略。

Best practice is to omit the traceback stack, unless it adds significant documentation value to the example. 最佳实践是省略回溯堆栈,除非它为示例添加了重要的文档价值。So the last example is probably better as:因此,最后一个示例可能更好:

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

Note that tracebacks are treated very specially. 请注意,对回溯的处理非常特殊。In particular, in the rewritten example, the use of ... is independent of doctest’s ELLIPSIS option. 特别是,在重写的示例中,使用...独立于doctest的ELLIPSIS选项。The ellipsis in that example could be left out, or could just as well be three (or three hundred) commas or digits, or an indented transcript of a Monty Python skit.该示例中的省略号可以省略,也可以是三个(或三百个)逗号或数字,或者是Monty Python短剧的缩进文本。

Some details you should read once, but won’t need to remember:一些细节你应该读一次,但不需要记住:

  • Doctest can’t guess whether your expected output came from an exception traceback or from ordinary printing. Doctest无法猜测您的预期输出是来自异常回溯还是来自普通打印。So, e.g., an example that expects ValueError: 42 is prime will pass whether ValueError is actually raised or if the example merely prints that traceback text. 因此,例如,一个期望ValueError: 42 is prime的示例将传递ValueError是否实际引发,或者该示例是否仅打印回溯文本。In practice, ordinary output rarely begins with a traceback header line, so this doesn’t create real problems.实际上,普通输出很少以回溯标题行开头,因此这不会产生真正的问题。

  • Each line of the traceback stack (if present) must be indented further than the first line of the example, or start with a non-alphanumeric character. 回溯堆栈的每一行(如果存在)必须缩进得比示例的第一行更远,或者以非字母数字字符开头。The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail. 回溯头后面缩进相同且以字母数字开头的第一行被视为异常详细信息的开头。Of course this does the right thing for genuine tracebacks.当然,这对于真正的回溯来说是正确的。

  • When the IGNORE_EXCEPTION_DETAIL doctest option is specified, everything following the leftmost colon and any module information in the exception name is ignored.当指定IGNORE_EXCEPTION_DETAIL doctest选项时,将忽略最左侧冒号后面的所有内容以及异常名称中的任何模块信息。

  • The interactive shell omits the traceback header line for some SyntaxErrors. 交互式shell省略了某些SyntaxError的回溯头行。But doctest uses the traceback header line to distinguish exceptions from non-exceptions. 但是doctest使用回溯头行来区分异常和非异常。So in the rare case where you need to test a SyntaxError that omits the traceback header, you will need to manually add the traceback header line to your test example.因此,在需要测试省略回溯头的SyntaxError的罕见情况下,需要手动将回溯头行添加到测试示例中。

  • For some SyntaxErrors, Python displays the character position of the syntax error, using a ^ marker:对于某些SyntaxError,Python使用^标记显示语法错误的字符位置:

    >>> 1 1
    File "<stdin>", line 1
    1 1
    ^
    SyntaxError: invalid syntax

    Since the lines showing the position of the error come before the exception type and detail, they are not checked by doctest. 由于显示错误位置的行位于异常类型和详细信息之前,因此doctest不会检查它们。For example, the following test would pass, even though it puts the ^ marker in the wrong location:例如,以下测试将通过,即使它将^标记放在错误的位置:

    >>> 1 1
    File "<stdin>", line 1
    1 1
    ^
    SyntaxError: invalid syntax

Option Flags选项标志

A number of option flags control various aspects of doctest’s behavior. 许多选项标志控制doctest行为的各个方面。Symbolic names for the flags are supplied as module constants, which can be bitwise ORed together and passed to various functions. 标志的符号名称作为模块常量提供,可以按位或运算在一起并传递给各种函数。The names can also be used in doctest directives, and may be passed to the doctest command line interface via the -o option.这些名称也可以在doctest指令中使用,并且可以通过-o选项传递给doctest命令行接口。

New in version 3.4.版本3.4中新增。The -o command line option.-o命令行选项。

The first group of options define test semantics, controlling aspects of how doctest decides whether actual output matches an example’s expected output:第一组选项定义测试语义,控制doctest如何决定实际输出是否与示例的预期输出相匹配:

doctest.DONT_ACCEPT_TRUE_FOR_1

By default, if an expected output block contains just 1, an actual output block containing just 1 or just True is considered to be a match, and similarly for 0 versus False. 默认情况下,如果期望的输出块仅包含1,则仅包含1True的实际输出块被视为匹配,同样地,对于0False也是如此。When DONT_ACCEPT_TRUE_FOR_1 is specified, neither substitution is allowed. 如果指定了DONT_ACCEPT_TRUE_FOR_1,则不允许进行替换。The default behavior caters to that Python changed the return type of many functions from integer to boolean; doctests expecting “little integer” output still work in these cases. 默认行为迎合了Python将许多函数的返回类型从整数改为布尔;在这些情况下,期望“小整数”输出的doctest仍然有效。This option 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 the string <BLANKLINE>, then that line will match a blank line in the actual output. 默认情况下,如果预期输出块包含仅包含字符串<BLANKLINE>的行,则该行将与实际输出中的空白行匹配。Because a genuinely blank line delimits the expected output, this is the only way to communicate that a blank line is expected. 因为真正的空行限定了预期的输出,所以这是传达期望空行的唯一方式。When DONT_ACCEPT_BLANKLINE is specified, this substitution is not allowed.如果指定了DONT_ACCEPT_BLANKLINE,则不允许进行此替换。

doctest.NORMALIZE_WHITESPACE

When specified, all sequences of whitespace (blanks and newlines) are treated as equal. 如果指定,则所有空白序列(空白和换行)都视为相等。Any sequence of whitespace within the expected output will match any sequence of whitespace within the actual output. 预期输出中的任何空白序列将与实际输出中的任意空白序列匹配。By default, whitespace must match exactly. 默认情况下,空白必须完全匹配。NORMALIZE_WHITESPACE is especially useful when a line of expected output is very long, and you want to wrap it across multiple lines in your source.NORMALIZE_WHITESPACE在一行预期输出非常长,并且您希望在源代码中跨多行换行时特别有用。

doctest.ELLIPSIS

When specified, an ellipsis marker (...) in the expected output can match any substring in the actual output. 指定时,预期输出中的省略号标记(...)可以匹配实际输出中的任何子字符串。This includes substrings that span line boundaries, 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, an example that expects an exception passes if an exception of the expected type is raised, even if the exception detail does not match. 指定时,如果引发预期类型的异常,即使异常详细信息不匹配,也会传递预期异常的示例。For example, an example expecting ValueError: 42 will pass if the actual exception raised is ValueError: 3*14, but will fail, e.g., if TypeError is raised.例如,如果引发的实际异常为ValueError:3*14,则预期ValueError:42的示例将通过,但如果引发TypeError,则会失败。

It will also ignore the module name used in Python 3 doctest reports. 它还将忽略Python 3 doctest报告中使用的模块名称。Hence both of these variations will work with the flag specified, regardless of whether the test is run under Python 2.7 or Python 3.2 (or later versions):因此,无论测试是在Python 2.7还是Python 3.2(或更高版本)下运行,这两种变体都将使用指定的标志:

>>> raise CustomError('message')
Traceback (most recent call last):
CustomError: message
>>> raise CustomError('message')
Traceback (most recent call last):
my_module.CustomError: message

Note that ELLIPSIS can also be used to ignore the details of the exception message, but such a test may still fail based on whether or not the module details are printed as part of the exception name. 请注意,ELLIPSIS也可用于忽略异常消息的详细信息,但根据模块详细信息是否作为异常名称的一部分打印,此类测试仍可能失败。Using IGNORE_EXCEPTION_DETAIL and the details from Python 2.3 is also the only clear way to write a doctest that doesn’t care about the exception detail yet continues to pass under Python 2.3 or earlier (those releases do not support doctest directives and ignore them as irrelevant comments). 使用IGNORE_EXCEPTION_DETAIL和Python 2.3中的详细信息也是编写不关心异常详细信息但在Python 2.3或更早版本下继续传递的doctest的唯一明确方法(这些版本不支持doctest指令,并将其作为无关注释忽略)。For example:例如:

>>> (1, 2)[3] = 'moo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object doesn't support item assignment

passes under Python 2.3 and later Python versions with the flag specified, even though the detail changed in Python 2.4 to say “does not” instead of “doesn’t”.在Python 2.3和更高版本的Python下传递,并指定标志,即使Python 2.4中的细节更改为“不”而不是“不”。

Changed in version 3.2:版本3.2中更改: IGNORE_EXCEPTION_DETAIL now also ignores any information relating to the module containing the exception under test.现在也忽略与包含测试异常的模块相关的任何信息。

doctest.SKIP

When specified, do not run the example at all. 如果指定,则完全不要运行该示例。This can be useful in contexts where doctest examples serve as both documentation and test cases, and an example should be included for documentation purposes, but should not be checked. 这在doctest示例同时用作文档和测试用例的情况下非常有用,并且应包含一个示例用于文档目的,但不应进行检查。E.g., the example’s output might be random; or the example might depend on resources which would be unavailable to the test driver.例如,示例的输出可能是随机的;或者该示例可能取决于测试驱动程序不可用的资源。

The SKIP flag can also be used for temporarily “commenting out” examples.SKIP标志也可用于临时“注释”示例。

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 are displayed using a unified diff.如果指定,则使用一致性的差异显示涉及多行预期输出和实际输出的故障。

doctest.REPORT_CDIFF

When specified, failures that involve multi-line expected and actual outputs will be displayed using a context diff.如果指定,将使用上下文差异显示涉及多行预期输出和实际输出的故障。

doctest.REPORT_NDIFF

When specified, differences are computed by difflib.Differ, using the same algorithm as the popular ndiff.py utility. 指定时,差异由difflib.Differ计算,使用与流行的ndiff.py实用程序相同的算法。This is the only method that marks differences within lines as well as across lines. 这是唯一一种标记行内和行间差异的方法。For example, if a line of expected output contains digit 1 where actual output contains letter l, a line is inserted with a caret marking the mismatching column positions.例如,如果一行预期输出包含数字1,而实际输出包含字母l,则插入一行插入符号,标记不匹配的列位置。

doctest.REPORT_ONLY_FIRST_FAILURE

When specified, display the first failing example in each doctest, but suppress output for all remaining examples. 指定后,在每个doctest中显示第一个失败的示例,但抑制所有剩余示例的输出。This will prevent doctest from reporting correct examples that break because of earlier failures; but it might also hide incorrect examples that fail independently of the first failure. 这将阻止doctest报告由于早期失败而中断的正确示例;但它也可能隐藏独立于第一次失败而失败的错误示例。When REPORT_ONLY_FIRST_FAILURE is specified, the remaining examples are still run, and still count towards the total number of failures reported; only the output is suppressed.当指定REPORT_ONLY_FIRST_FAILURE时,其余示例仍在运行,并且仍计入报告的故障总数;仅抑制输出。

doctest.FAIL_FAST

When specified, exit after the first failing example and don’t attempt to run the remaining examples. 指定时,在第一个失败的示例后退出,不要尝试运行其余的示例。Thus, the number of failures reported will be at most 1. 因此,报告的故障数最多为1。This flag may be useful during debugging, since examples after the first failure won’t even produce debugging output.此标志在调试期间可能很有用,因为第一次失败后的示例甚至不会产生调试输出。

The doctest command line accepts the option -f as a shorthand for -o FAIL_FAST.doctest命令行接受选项-f作为-o FAIL_FAST的缩写。

New in version 3.4.版本3.4中新增。

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’t useful unless you intend to extend doctest internals via subclassing:还有一种方法可以注册新的选项标志名,但这并不有用,除非您打算通过子类化扩展doctest 内部:

doctest.register_optionflag(name)

Create a new option flag with a given name, and return the new flag’s integer value. 使用给定的名称创建一个新的选项标志,并返回新标志的整数值。register_optionflag() can be used when subclassing OutputChecker or DocTestRunner to create new options that are supported by your subclasses. 可以在子类OutputCheckerDocTestRunner时使用register_optionflag(),以创建子类支持的新选项。register_optionflag() should always be called using the following idiom:应始终使用以下习语进行调用:

MY_FLAG = register_optionflag('MY_FLAG')

Directives指令

Doctest directives may be used to modify the option flags for an individual example. Doctest指令可用于修改单个示例的选项标志Doctest directives are special Python comments following an example’s source code:Doctest指令是示例源代码后面的特殊Python注释:


directive ::= "#" "doctest:" directive_options
directive_options ::= directive_option ("," directive_option)\*
directive_option ::= on_or_off directive_option_name
on_or_off ::= "+" \| "-"
directive_option_name ::= "DONT_ACCEPT_BLANKLINE" \| "NORMALIZE_WHITESPACE" \| ...

Whitespace is not allowed between the + or - and the directive option name. +-与指令选项名称之间不允许有空格。The directive option name can be any of the option flag names explained above.指令选项名称可以是上面解释的任何选项标志名称。

An example’s doctest directives modify doctest’s behavior for that single example. 示例的doctest指令修改了该示例的docest行为。Use + to enable the named behavior, or - to disable it.使用+启用命名行为,或使用-禁用命名行为。

For example, this test passes:例如,此测试通过:

>>> print(list(range(20)))
[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 have two blanks before the single-digit list elements, and because the actual output is on a single line. 如果没有该指令,它将失败,这既因为实际输出在单个数字列表元素之前没有两个空格,也因为实际输出位于单行上。This test also passes, and also requires a directive to do so:此测试也通过,并且还需要一个指令来完成:

>>> print(list(range(20)))
[0, 1, ..., 18, 19]

Multiple directives can be used on a single physical line, separated by commas:可以在单个物理行上使用多个指令,用逗号分隔:

>>> print(list(range(20)))
[0, 1, ..., 18, 19]

If multiple directive comments are used for a single example, then they are combined:如果单个示例使用多个指令注释,则将它们组合在一起:

>>> print(list(range(20)))
...
[0, 1, ..., 18, 19]

As the previous example shows, you can add ... lines to your example containing only directives. 如前一个示例所示,您可以添加。。。示例中的行仅包含指令。This can be useful when an example is too long for a directive to comfortably fit on the same line:当一个示例太长,指令不能很好地放在同一行时,这可能很有用:

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

Note that since all options are disabled by default, and directives apply only to the example they appear in, enabling options (via + in a directive) is usually the only meaningful choice. 注意,由于默认情况下禁用所有选项,并且指令仅适用于它们出现的示例,因此启用选项(通过指令中的+)通常是唯一有意义的选择。However, option flags can also be passed to functions that run doctests, establishing different defaults. 然而,选项标志也可以传递给运行doctest的函数,从而建立不同的默认值。In such cases, disabling an option via - in a directive can be useful.在这种情况下,利用-在指令中禁用选项是有用的。

Warnings

doctest is serious about requiring exact matches in expected output. 在期望的输出中需要精确匹配。If even a single character doesn’t match, the test fails. 如果连一个字符都不匹配,测试就会失败。This will probably surprise you a few times, as you learn exactly what Python does and doesn’t guarantee about output. 这可能会让你惊讶几次,因为你确切地了解了Python的功能和不保证输出。For example, when printing a set, Python doesn’t guarantee that the element is printed in any particular order, so a test like例如,当打印一个集合时,Python不能保证元素以任何特定的顺序打印,因此类似于

>>> foo()
{"Hermione", "Harry"}

is vulnerable! One workaround is to do是脆弱的!解决方法之一是

>>> foo() == {"Hermione", "Harry"}
True

instead. Another is to do相反另一个是做

>>> d = sorted(foo())
>>> d
['Harry', 'Hermione']

Note

Before Python 3.6, when printing a dict, Python did not guarantee that the key-value pairs was printed in any particular order.在Python3.6之前,当打印dict时,Python不保证按任何特定顺序打印键值对。

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 time
7948648
>>> class C: pass
>>> C() # the default repr() for instances embeds an address
<__main__.C instance at 0x00AC18F0>

The ELLIPSIS directive gives a nice approach for the last example:ELLIPSIS指令为最后一个示例提供了一种很好的方法:

>>> C()
<__main__.C instance at 0x...>

Floating-point numbers are also subject to small output variations across platforms, because Python defers to the platform C library for float formatting, and C libraries vary widely in quality here.浮点数在不同的平台上也会有很小的输出变化,因为Python遵循平台C库进行浮点数格式化,而C库在这里的质量差异很大。

>>> 1./7  # risky
0.14285714285714285
>>> print(1./7) # safer
0.142857142857
>>> print(round(1./7, 6)) # much safer
0.142857

Numbers of the form I/2.**J are safe across all platforms, and I often contrive doctest examples to produce numbers of that form:I/2.**J形式的数字在所有平台上都是安全的,我经常设计doctest示例来生成这种形式的数字:

>>> 3./4  # utterly safe
0.75

Simple fractions are also easier for people to understand, and that makes for better documentation.简单的分数对人们来说也更容易理解,这有助于更好的文档。

Basic API

The functions testmod() and testfile() provide a simple interface to doctest that should be sufficient for most basic uses. 函数testmod()testfile()为doctest提供了一个简单的接口,应该足以满足大多数基本用途。For a less formal introduction to these two functions, see sections Simple Usage: Checking Examples in Docstrings and Simple Usage: Checking Examples in a Text File.有关这两个函数的不太正式的介绍,请参阅部分简单用法:检查Docstring中的示例简单用法:在文本文件中检查示例

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 except filename are optional, and should be specified in keyword form.除了filename之外的所有参数都是可选的,应该以关键字形式指定。

Test examples in the file named filename. 名为filename的文件中的测试示例。Return (failure_count, test_count).返回(failure_count, test_count)

Optional argument module_relative specifies how the filename should be interpreted:可选参数module_relative指定应如何解释文件名:

  • If module_relative is True (the default), then filename specifies an OS-independent module-relative path. 如果module_relativeTrue(默认值),则filename指定与操作系统无关的模块相对路径。By default, this path is relative to the calling module’s directory; but if the package argument is specified, then it is relative to that package. 默认情况下,此路径相对于调用模块的目录;但如果指定了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 /).为了确保操作系统的独立性,filename应该使用/字符来分隔路径段,并且不能是绝对路径(即不能以/开头)。

  • If module_relative is False, then filename specifies an OS-specific path. 如果module_relativeFalse,则filename指定特定于操作系统的路径。The path may be absolute or relative; relative paths are resolved with respect to the current working directory.路径可以是绝对的或相对的;相对于当前工作目录解析相对路径。

Optional argument name gives the name of the test; by default, or if None, os.path.basename(filename) is used.可选参数name给出测试的名称;默认情况下,或者如果None,则使用os.path.basename(filename)

Optional argument package is a Python package or the name of a Python package whose directory should be used as the base directory for a module-relative filename. 可选参数package是Python包或Python包的名称,其目录应用作模块相关文件名的基本目录。If no package is specified, then the calling module’s directory is used as the base directory for module-relative filenames. 如果未指定包,则调用模块的目录将用作模块相关文件名的基本目录。It is an error to specify package if module_relative is False.如果module_relativeFalse,则指定package是错误的。

Optional argument globs gives a dict to be used as the globals when executing examples. 可选参数globs在执行示例时提供一个用作全局变量的dict。A new shallow copy of this dict is created for the doctest, so its examples start with a clean slate. 为doctest创建了这个dict的一个新的浅层副本,因此它的示例从一个干净的石板开始。By default, or if None, a new empty dict is used.默认情况下,或者如果None,则使用新的空字典。

Optional argument extraglobs gives a dict merged into the globals used to execute examples. 可选参数extraglobs提供了一个合并到用于执行示例的全局变量中的dict。This works like dict.update(): if globs and extraglobs have a common key, the associated value in extraglobs appears in the combined dict. 这与dict.update()类似:如果globsextraglobs有一个公共键,extraglb中的关联值将出现在组合的dict中。By default, or if None, no extra globals are used. 默认情况下,或者如果为None,则不使用额外的全局变量。This is an advanced feature that allows parameterization of doctests. 这是一个允许doctest参数化的高级功能。For example, a doctest can be written for a base class, using a generic name for the class, then reused to test any number of subclasses by passing an extraglobs dict mapping the generic name to the subclass to be tested.例如,可以使用类的通用名称为基类编写doctest,然后通过传递将通用名称映射到要测试的子类的extraglobs dict来重用它来测试任意数量的子类。

Optional argument verbose prints lots of stuff if true, and prints only failures if false; by default, or if None, it’s true if and only if '-v' is in sys.argv.可选参数verbose如果为true,则打印大量内容,如果为false,则只打印失败;默认情况下,或如果为None,则当且仅当'-v'sys.argv中时为true

Optional argument report prints a summary at the end when true, else prints nothing at the end. 可选参数report在结尾处打印摘要(如果为true),否则在结尾处不打印任何内容。In verbose mode, the summary is detailed, else the summary is very brief (in fact, empty if all tests passed).在详细模式下,摘要是详细的,否则摘要非常简短(事实上,如果所有测试都通过,则为空)。

Optional argument optionflags (default value 0) takes the bitwise OR of option flags. 可选参数optionflags(默认值为0)采用选项标志的按位或See section Option Flags.请参阅选项标志一节。

Optional argument raise_on_error defaults to false. 可选参数raise_on_error默认为falseIf true, an exception is raised upon the first failure or unexpected exception in an example. 如果为true,则在示例中出现第一次失败或意外异常时引发异常。This allows failures to be post-mortem debugged. 这允许对故障进行事后调试。Default behavior is to continue running examples.默认行为是继续运行示例。

Optional argument parser specifies a DocTestParser (or subclass) that should be used to extract tests from the files. 可选参数parser指定一个DocTestParser(或子类),它应该用于从文件中提取测试。It defaults to a normal parser (i.e., DocTestParser()).它默认为普通解析器(即DocTestParser())。

Optional argument encoding specifies an encoding that should be used to convert the file to unicode.可选参数encoding指定用于将文件转换为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 for m should be specified in keyword form.所有参数都是可选的,除m以外的所有参数都应以关键字形式指定。

Test examples in docstrings in functions and classes reachable from module m (or module __main__ if m is not supplied or is None), starting with m.__doc__.从模块m(或模块__main__,如果未提供mmNone)可访问的函数和类中的docstring中的测试示例,从m.__doc__开始。

Also test examples reachable from dict m.__test__, if it exists and is not None. 另外,如果dict m.__test__存在且不是None,则还可以从m.__test__中获取测试示例。m.__test__ maps names (strings) to functions, classes and strings; function and class docstrings are searched for examples; strings are searched directly, as if they were docstrings.将名称(字符串)映射到函数、类和字符串;搜索函数和类文档字符串以获取示例;字符串被直接搜索,就像它们是文档字符串一样。

Only docstrings attached to objects belonging to module m are searched.仅搜索附加到属于模块m的对象的文档字符串。

Return (failure_count, test_count).返回(failure_count, test_count)

Optional argument name gives the name of the module; by default, or if None, m.__name__ is used.可选参数name提供模块的名称;默认情况下,或如果None,则使用m.__name__

Optional argument exclude_empty defaults to false. 可选参数exclude_empty默认为falseIf true, objects for which no doctests are found are excluded from consideration. 如果为true,则不考虑未找到doctest的对象。The default is a backward compatibility hack, so that code still using doctest.master.summarize() in conjunction with testmod() continues to get output for objects with no tests. 默认情况下是向后兼容黑客,因此仍然使用doctest.master.summarize()testmod()的代码可以继续获得没有测试的对象的输出。The exclude_empty argument to the newer DocTestFinder constructor defaults to true.更新的DocTestFinder构造函数的exclude_empty参数默认为true

Optional arguments extraglobs, verbose, report, optionflags, raise_on_error, and globs are the same as for function testfile() above, except that globs defaults to m.__dict__.可选参数extraglobsverbosereportoptionflagsraise_o_errorglobs与上述函数testfile()相同,但globs默认为m.__dict__

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

Test examples associated with object f; for example, f may be a string, a module, a function, or a class object.与对象f相关的测试示例;例如,f可以是字符串、模块、函数或类对象。

A shallow copy of dictionary argument globs is used for the execution context.字典参数globs的浅副本用于执行上下文。

Optional argument name is used in failure messages, and defaults to "NoName".在失败消息中使用可选参数name,默认为"NoName"

If optional argument verbose is true, output is generated even if there are no failures. 如果可选参数verbosetrue,则即使没有失败,也会生成输出。By default, output is generated only in case of an example failure.默认情况下,仅在示例失败时生成输出。

Optional argument compileflags gives the set of flags that should be used by the Python compiler when running the examples. 可选参数compileflags提供Python编译器在运行示例时应使用的一组标志。By default, or if None, flags are deduced corresponding to the set of future features found in globs.默认情况下,或者如果为None,则根据globs中发现的一组未来特性推断标志。

Optional argument optionflags works as for function testfile() above.可选参数optionflags的工作原理与上述函数testfile()相同。

Unittest API

As your collection of doctest’ed modules grows, you’ll want a way to run all their doctests systematically. 随着doctested模块集合的增长,您将需要一种系统地运行所有doctest的方法。doctest provides two functions that can be used to create unittest test suites from modules and text files containing doctests. 提供了两个函数,可用于从包含doctest的模块和文本文件创建unittest测试套件。To integrate with unittest test discovery, include a load_tests() function in your test module:要与unittest测试发现集成,请在测试模块中包含load_tests()函数:

import unittest
import doctest
import my_module_with_doctests
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
return tests

There are two main functions for creating unittest.TestSuite instances from text files and modules with doctests:从文本文件和带有doctest的模块创建unittest.TestSuite实例有两个主要功能:

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 a unittest.TestSuite.将doctest测试从一个或多个文本文件转换为unittest.TestSuite

The returned unittest.TestSuite is to be run by the unittest framework and runs the interactive examples in each file. 返回的unittest.TestSuite将由unittest框架运行,并在每个文件中运行交互示例。If an example in any file fails, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number.如果任何文件中的示例失败,则合成单元测试失败,并引发failureException异常,显示包含测试的文件名和(有时是近似的)行号。

Pass one or more paths (as strings) to text files to be examined.将一个或多个路径(作为字符串)传递给要检查的文本文件。

Options may be provided as keyword arguments:选项可以作为关键字参数提供:

Optional argument module_relative specifies how the filenames in paths should be interpreted:可选参数module_relative指定如何解释paths中的文件名:

  • If module_relative is True (the default), then each filename in paths specifies an OS-independent module-relative path. 如果module_relativeTrue(默认值),则paths中的每个文件名都指定一个独立于操作系统的模块相对路径。By default, this path is relative to the calling module’s directory; but if the package argument is specified, then it is relative to that package. 默认情况下,此路径相对于调用模块的目录;但如果指定了package参数,则它是相对于该包的。To ensure OS-independence, each filename should use / characters to separate path segments, and may not be an absolute path (i.e., it may not begin with /).为了确保操作系统的独立性,每个文件名都应该使用/字符来分隔路径段,并且不能是绝对路径(即不能以/开头)。

  • If module_relative is False, then each filename in paths specifies an OS-specific path. 如果module_relativeFalse,则paths中的每个文件名都指定一个特定于操作系统的路径。The path may be absolute or relative; relative paths are resolved with respect to the current working directory.路径可以是绝对的或相对的;相对于当前工作目录解析相对路径。

Optional argument package is a Python package or the name of a Python package whose directory should be used as the base directory for module-relative filenames in paths. 可选参数 package是Python包或Python包的名称,其目录应用作paths中模块相关文件名的基本目录。If no package is specified, then the calling module’s directory is used as the base directory for module-relative filenames. 如果未指定包,则调用模块的目录将用作模块相关文件名的基本目录。It is an error to specify package if module_relative is False.如果module_relativeFalse,则指定package是错误的。

Optional argument setUp specifies a set-up function for the test suite. 可选参数setUp指定测试套件的设置函数。This is called before running the tests in each file. 这在运行每个文件中的测试之前调用。The setUp function will be passed a DocTest object. setUp函数将传递DocTest对象。The setUp function can access the test globals as the globs attribute of the test passed.setUp函数可以在通过测试的globs属性时访问测试全局变量。

Optional argument tearDown specifies a tear-down function for the test suite. 可选参数tearDown为测试套件指定一个可拆卸函数。This is called after running the tests in each file. 这是在每个文件中运行测试后调用的。The tearDown function will be passed a DocTest object. tearDown函数将传递DocTest对象。The setUp function can access the test globals as the globs attribute of the test passed.setUp函数可以在通过测试的globs属性时访问测试全局变量。

Optional argument globs is a dictionary containing the initial global variables for the tests. 可选参数globs是一个包含测试初始全局变量的字典。A new copy of this dictionary is created for each test. 将为每个测试创建此词典的新副本。By default, globs is a new empty dictionary.默认情况下,globs是一个新的空字典。

Optional argument optionflags specifies the default doctest options for the tests, created by or-ing together individual option flags. 可选参数optionflags指定测试的默认doctest选项,这些选项由单个选项标志创建或组合在一起。See section Option Flags. 请参阅选项标志一节。See function set_unittest_reportflags() below for a better way to set reporting options.有关设置报告选项的更好方法,请参阅下面的函数set_unittest_reportflags()

Optional argument parser specifies a DocTestParser (or subclass) that should be used to extract tests from the files. 可选参数parser指定一个DocTestParser(或子类),它应该用于从文件中提取测试。It defaults to a normal parser (i.e., DocTestParser()).它默认为普通解析器(即DocTestParser())。

Optional argument encoding specifies an encoding that should be used to convert the file to unicode.可选参数encoding指定用于将文件转换为unicode的编码。

The global __file__ is added to the globals provided to doctests loaded from a text file using DocFileSuite().使用DocFileSuite()将全局__file__添加到提供给从文本文件加载的doctest的全局值中。

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

Convert doctest tests for a module to a unittest.TestSuite.将模块的doctest测试转换为unittest.TestSuite

The returned unittest.TestSuite is to be run by the unittest framework and runs each doctest in the module. 返回的unittest.TestSuite将由unittest框架运行,并运行模块中的每个doctest。If any of the doctests fail, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number.如果任何doctest失败,则合成单元测试失败,并引发failureException异常,显示包含测试的文件名和(有时是近似的)行号。

Optional argument module provides the module to be tested. 可选参数module提供要测试的模块。It can be a module object or a (possibly dotted) module name. 它可以是模块对象或(可能是虚线)模块名称。If not specified, the module calling this function is used.如果未指定,则使用调用此函数的模块。

Optional argument globs is a dictionary containing the initial global variables for the tests. 可选参数globs是一个包含测试初始全局变量的字典。A new copy of this dictionary is created for each test. 将为每个测试创建此词典的新副本。By default, globs is a new empty dictionary.默认情况下,globs是一个新的空字典。

Optional argument extraglobs specifies an extra set of global variables, which is merged into globs. 可选参数extraglobs指定一组额外的全局变量,这些变量被合并到globs中。By default, no extra globals are used.默认情况下,不使用额外的全局变量。

Optional argument test_finder is the DocTestFinder object (or a drop-in replacement) that is used to extract doctests from the module.可选参数test_finder是用于从模块中提取doctest的DocTestFinder对象(或替换项)。

Optional arguments setUp, tearDown, and optionflags are the same as for function DocFileSuite() above.可选参数setUptearDownoptionflags与上述函数DocFileSuite()相同。

This function uses the same search technique as testmod().此函数使用与testmod()相同的搜索技术。

Changed in version 3.5:版本3.5中更改: DocTestSuite() returns an empty unittest.TestSuite if module contains no docstrings instead of raising ValueError.如果module不包含文档字符串,而不是引发ValueError

Under the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase. 在封面下,DocTestSuite()根据doctest.DocTestCase实例创建了一个unittest.TestSuiteDocTestCaseunittest.TestCase的子类。DocTestCase isn’t documented here (it’s an internal detail), but studying its code can answer questions about the exact details of unittest integration.这里没有记录(这是一个内部细节),但是研究它的代码可以回答关于unittest集成的确切细节的问题。

Similarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase.类似地,DocFileSuite()doctest.DocFileCase实例创建了一个unittest.TestSuiteDocFileCaseDocTestCase的子类。

So both ways of creating a unittest.TestSuite run instances of DocTestCase. 因此,创建unittest.TestSuite的两种方法都运行DocTestCase的实例。This is important for a subtle reason: when you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions. 这一点很重要,原因很微妙:当您自己运行doctest函数时,可以通过向doctest函数传递选项标志来直接控制使用中的doctest选项。However, if you’re writing a unittest framework, unittest ultimately controls when and how tests get run. 然而,如果您正在编写一个unittest框架,那么unittest将最终控制测试的运行时间和方式。The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners.框架作者通常希望控制doctest报告选项(例如,由命令行选项指定),但无法将选项通过unittest传递给doctest测试运行者。

For this reason, doctest also supports a notion of doctest reporting flags specific to unittest support, via this function:因此,doctest还通过以下函数支持特定于unittest支持的doctest报告标志的概念:

doctest.set_unittest_reportflags(flags)

Set the doctest reporting flags to use.设置要使用的doctest报告标志。

Argument flags takes the bitwise OR of option flags. 参数flags采用选项标志的按位或See section Option Flags. 请参阅选项标志一节。Only “reporting flags” can be used.只能使用“报告标志”。

This is a module-global setting, and affects all future doctests run by module unittest: the runTest() method of DocTestCase looks at the option flags specified for the test case when the DocTestCase instance was constructed. 这是一个模块全局设置,并影响由模块unittest运行的所有未来doctest:DocTestCaserunTest()方法在构建DocTestCase实例时查看为测试用例指定的选项标志。If no reporting flags were specified (which is the typical and expected case), doctest’s unittest reporting flags are bitwise ORed into the option flags, and the option flags so augmented are passed to the DocTestRunner instance created to run the doctest. 如果未指定报告标志(这是典型的和预期的情况),则doctestunittest报告标志将按位或运算到选项标志中,并将增强的选项标志传递给为运行doctest而创建的DocTestRunner实例。If any reporting flags were specified when the DocTestCase instance was constructed, doctest’s unittest reporting flags are ignored.如果在构建DocTestCase实例时指定了任何报告标志,则会忽略doctestunittest报告标志。

The value of the unittest reporting flags in effect before the function was called is returned by the function.函数返回函数调用前有效的unittest报告标志的值。

Advanced API高级API

The basic API is a simple wrapper that’s intended to make doctest easy to use. 基本API是一个简单的包装器,旨在使doctest易于使用。It is fairly flexible, and should meet most users’ needs; however, if you require more fine-grained control over testing, or wish to extend doctest’s capabilities, then you should use the advanced API.它相当灵活,应该满足大多数用户的需求;但是,如果您需要对测试进行更细粒度的控制,或者希望扩展doctest的功能,那么应该使用高级API。

The advanced API revolves around two container classes, which are used to store the interactive examples extracted from doctest cases:高级API围绕两个容器类,用于存储从doctest用例中提取的交互示例:

  • Example: A single Python statement, paired with its expected output.:单个Python语句,与预期输出配对。

  • DocTest: A collection of Examples, typically extracted from a single docstring or text file.Example的集合,通常从单个文档字符串或文本文件中提取。

Additional processing classes are defined to find, parse, and run, and check doctest examples:定义了其他处理类来查找、分析、运行和检查doctest示例:

  • DocTestFinder: Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples.:查找给定模块中的所有文档字符串,并使用DocTestParser从包含交互示例的每个文档字符串创建DocTest

  • DocTestParser: Creates a DocTest object from a string (such as an object’s docstring).:从字符串(例如对象的docstring)创建DocTest对象。

  • DocTestRunner: Executes the examples in a DocTest, and uses an OutputChecker to verify their output.:执行DocTest中的示例,并使用OutputChecker验证其输出。

  • OutputChecker: Compares the actual output from a doctest example with the expected output, and decides whether they match.:将doctest示例的实际输出与预期输出进行比较,并确定它们是否匹配。

The relationships among these processing classes are summarized in the following diagram:下图总结了这些处理类之间的关系:

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

DocTest ObjectsDocTest对象

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

A collection of doctest examples that should be run in a single namespace. 应在单个命名空间中运行的doctest示例集合。The constructor arguments are used to initialize the attributes of the same names.构造函数参数用于初始化同名属性。

DocTest defines the following attributes. 定义以下属性。They are initialized by the constructor, and should not be modified directly.它们由构造函数初始化,不应直接修改。

examples

A list of Example objects encoding the individual interactive Python examples that should be run by this test.编码本测试应运行的各个交互式Python示例的Example对象列表。

globs

The namespace (aka globals) that the examples should be run in. 应该在其中运行示例的名称空间(又名globals)。This is a dictionary mapping names to values. 这是一个将名称映射到值的字典。Any changes to the namespace made by the examples (such as binding new variables) will be reflected in globs after the test is run.运行测试后,示例对命名空间所做的任何更改(例如绑定新变量)都将反映在globs中。

name

A string name identifying the DocTest. 标识DocTest的字符串名称。Typically, this is the name of the object or file that the test was extracted from.通常,这是从中提取测试的对象或文件的名称。

filename

The name of the file that this DocTest was extracted from; or None if the filename is unknown, or if the DocTest was not extracted from a file.提取此DocTest的文件的名称;如果文件名未知,或者DocTest未从文件中提取,则为None

lineno

The line number within filename where this DocTest begins, or None if the line number is unavailable. filename中此DocTest开始的行号,如果行号不可用,则为NoneThis line number is zero-based with respect to the beginning of the file.相对于文件开头,该行号从零开始。

docstring

The string that the test was extracted from, or None if the string is unavailable, or if the test was not extracted from a string.从中提取测试的字符串,如果该字符串不可用或未从字符串中提取测试,则选择None

Example Objects示例对象

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

A single interactive example, consisting of a Python statement and its expected output. 一个交互式示例,由Python语句及其预期输出组成。The constructor arguments are used to initialize the attributes of the same names.构造函数参数用于初始化同名属性。

Example defines the following attributes. 定义以下属性。They are initialized by the constructor, and should not be modified directly.它们由构造函数初始化,不应直接修改。

source

A string containing the example’s source code. 包含示例源代码的字符串。This source code consists of a single Python statement, and always ends with a newline; the constructor adds a newline when necessary.此源代码由一条Python语句组成,并始终以换行符结尾;构造函数在必要时添加新行。

want

The expected output from running the example’s source code (either from stdout, or a traceback in case of exception). 运行示例源代码的预期输出(来自stdout,或在异常情况下的回溯)。want ends with a newline unless no output is expected, in which case it’s an empty string. want以换行结尾,除非不需要输出,在这种情况下,它是一个空字符串。The constructor adds a newline when necessary.构造函数在必要时添加换行符。

exc_msg

The exception message generated by the example, if the example is expected to generate an exception; or None if it is not expected to generate an exception. 如果该示例预期生成异常,则该示例生成的异常消息;如果不希望生成异常,则为NoneThis exception message is compared against the return value of traceback.format_exception_only(). 将此异常消息与traceback.format_exception_only()的返回值进行比较。exc_msg ends with a newline unless it’s None. exc_msg以换行结尾,除非它是NoneThe constructor adds a newline if needed.如果需要,构造函数将添加新行。

lineno

The line number within the string containing this example where the example begins. 包含此示例的字符串中的行号(示例开始处)。This line number is zero-based with respect to the beginning of the containing string.相对于包含字符串的开头,该行号从零开始。

indent

The example’s indentation in the containing string, i.e., the number of space characters that precede the example’s first prompt.示例在包含字符串中的缩进,即示例第一个提示前的空格字符数。

options

A dictionary mapping from option flags to True or False, which is used to override default options for this example. 从选项标志到TrueFalse的字典映射,用于覆盖本示例的默认选项。Any option flags not contained in this dictionary are left at their default value (as specified by the DocTestRunner’s optionflags). 此字典中未包含的任何选项标志都保留其默认值(由DocTestRunneroptionflags指定)。By default, no options are set.默认情况下,不设置任何选项。

DocTestFinder objectsDocTestFinder对象

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

A processing class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. 一个处理类,用于从给定对象的文档字符串及其包含对象的文档串中提取与给定对象相关的DocTestDocTests can be extracted from modules, classes, functions, methods, staticmethods, classmethods, and properties.可以从模块、类、函数、方法、静态方法、类方法和财产中提取DocTest

The optional argument verbose can be used to display the objects searched by the finder. 可选参数verbose可用于显示查找器搜索的对象。It defaults to False (no output).它默认为False(无输出)。

The optional argument parser specifies the DocTestParser object (or a drop-in replacement) that is used to extract doctests from docstrings.可选参数parser指定DocTestParser对象(或替换项),该对象用于从docstring中提取doctest。

If the optional argument recurse is false, then DocTestFinder.find() will only examine the given object, and not any contained objects.如果可选参数recursefalse,则DocTestFinder.find()将只检查给定对象,而不检查任何包含的对象。

If the optional argument exclude_empty is false, then DocTestFinder.find() will include tests for objects with empty docstrings.如果可选参数exclude_emptyfalse,则DocTestFinder.find()将包括对具有空文档字符串的对象的测试。

DocTestFinder defines the following method:定义了以下方法:

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

Return a list of the DocTests that are defined by obj’s docstring, or by any of its contained objects’ docstrings.返回由obj的docstring或其包含的任何对象的docstring定义的DocTest列表。

The optional argument name specifies the object’s name; this name will be used to construct names for the returned DocTests. 可选参数名称指定对象的名称;此名称将用于构造返回DocTest的名称。If name is not specified, then obj.__name__ is used.如果未指定name,则使用obj.__name__

The optional parameter module is the module that contains the given object. 可选参数module是包含给定对象的模块。If the module is not specified or is None, then the test finder will attempt to automatically determine the correct module. 如果未指定模块或模块为None,则测试查找器将尝试自动确定正确的模块。The object’s module is used:使用对象的模块:

  • As a default namespace, if globs is not specified.如果未指定globs,则作为默认命名空间。

  • To prevent the DocTestFinder from extracting DocTests from objects that are imported from other modules. 防止DocTestFinder从从其他模块导入的对象中提取DocTests。(Contained objects with modules other than module are ignored.)(包含模块而不是module的对象将被忽略。)

  • To find the name of the file containing the object.查找包含对象的文件的名称。

  • To help find the line number of the object within its file.帮助查找文件中对象的行号。

If module is False, no attempt to find the module will be made. 如果moduleFalse,则不会尝试查找模块。This is obscure, of use mostly in testing doctest itself: if module is False, or is None but cannot be found automatically, then all objects are considered to belong to the (non-existent) module, so all contained objects will (recursively) be searched for doctests.这很模糊,主要用于测试doctest本身:如果module为False或None,但无法自动找到,则所有对象都被认为属于(不存在的)模块,因此将(递归地)搜索所有包含的对象以查找doctest。

The globals for each DocTest is formed by combining globs and extraglobs (bindings in extraglobs override bindings in globs). 每个DocTest的全局变量是通过组合globsextraglobsextraglobs中的绑定覆盖globs中的绑定)形成的。A new shallow copy of the globals dictionary is created for each DocTest. 为每个DocTest创建一个新的全局字典浅副本。If globs is not specified, then it defaults to the module’s __dict__, if specified, or {} otherwise. 如果未指定globs,则默认为模块的__dict__(如果指定),否则为{}If extraglobs is not specified, then it defaults to {}.如果未指定extraglobs,则默认为{}

DocTestParser objects

classdoctest.DocTestParser

A processing class used to extract interactive examples from a string, and use them to create a DocTest object.一个处理类,用于从字符串中提取交互式示例,并使用它们创建DocTest对象。

DocTestParser defines the following methods:定义了以下方法:

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

Extract all doctest examples from the given string, and collect them into a DocTest object.从给定字符串中提取所有doctest示例,并将它们收集到DocTest对象中。

globs, name, filename, and lineno are attributes for the new DocTest object. globsnamefilenamelineno是新DocTest对象的属性。See the documentation for DocTest for more information.有关更多信息,请参阅DocTest文档。

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

Extract all doctest examples from the given string, and return them as a list of Example objects. 从给定字符串中提取所有doctest示例,并将它们作为Example对象列表返回。Line numbers are 0-based. 行号从0开始。The optional argument name is a name identifying this string, and is only used for error messages.可选参数名称是标识此字符串的name,仅用于错误消息。

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

Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. 将给定字符串分成示例和中间文本,并将它们作为Example和字符串的交替列表返回。Line numbers for the Examples are 0-based. Example的行号从0开始。The optional argument name is a name identifying this string, and is only used for error messages.可选参数name是标识此字符串的名称,仅用于错误消息。

DocTestRunner objects

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

A processing class used to execute and verify the interactive examples in a DocTest.用于在DocTest中执行和验证交互示例的处理类。

The comparison between expected outputs and actual outputs is done by an OutputChecker. 预期输出和实际输出之间的比较由OutputChecker完成。This comparison may be customized with a number of option flags; see section Option Flags for more information. 该比较可以使用多个选项标志来定制;有关详细信息,请参阅选项标志一节。If the option flags are insufficient, then the comparison may also be customized by passing a subclass of OutputChecker to the constructor.如果选项标志不足,则还可以通过将OutputChecker的子类传递给构造函数来定制比较。

The test runner’s display output can be controlled in two ways. 可以通过两种方式控制测试运行器的显示输出。First, an output function can be passed to TestRunner.run(); this function will be called with strings that should be displayed. 首先,可以将输出函数传递给TestRunner.run();将使用应显示的字符串调用此函数。It defaults to sys.stdout.write. 它默认为sys.stdout.writeIf capturing the output is not sufficient, then the display output can be also customized by subclassing DocTestRunner, and overriding the methods report_start(), report_success(), report_unexpected_exception(), and report_failure().如果捕获输出还不够,那么还可以通过将DocTestRunner子类化,并重写方法report_start()report_success()report_unexpected_exception()report_failure()来定制显示输出。

The optional keyword argument checker specifies the OutputChecker object (or drop-in replacement) that should be used to compare the expected outputs to the actual outputs of doctest examples.可选关键字参数checker指定OutputChecker对象(或替换项),该对象应用于将预期输出与doctest示例的实际输出进行比较。

The optional keyword argument verbose controls the DocTestRunner’s verbosity. 可选关键字参数verbose控制DocTestRunner的详细信息。If verbose is True, then information is printed about each example, as it is run. 如果verboseTrue,则会在运行每个示例时打印有关该示例的信息。If verbose is False, then only failures are printed. 如果verboseFalse,则只打印失败。If verbose is unspecified, or None, then verbose output is used iff the command-line switch -v is used.如果未指定verboseNone,则在使用命令行开关-v时使用verbose输出。

The optional keyword argument optionflags can be used to control how the test runner compares expected output to actual output, and how it displays failures. 可选的关键字参数optionflags可用于控制测试运行程序如何将预期输出与实际输出进行比较,以及如何显示失败。For more information, see section Option Flags.有关详细信息,请参阅选项标志一节。

DocTestParser defines the following methods:定义了以下方法:

report_start(out, test, example)

Report that the test runner is about to process the given example. 报告测试运行者即将处理给定的示例。This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.提供此方法是为了允许DocTestRunner的子类自定义其输出;不应直接调用它。

example is the example about to be processed. 是即将处理的示例。test is the test containing example. 是包含测试的exampleout is the output function that was passed to DocTestRunner.run().是传递给DocTestRunner.run()的输出函数。

report_success(out, test, example, got)

Report that the given example ran successfully. 报告给定示例已成功运行。This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.提供此方法是为了允许DocTestRunner的子类自定义其输出;不应直接调用它。

example is the example about to be processed. 是即将处理的示例。got is the actual output from the example. 是示例的实际输出。test is the test containing example. 是包含测试的exampleout is the output function that was passed to DocTestRunner.run().是传递给DocTestRunner.run()的输出函数。

report_failure(out, test, example, got)

Report that the given example failed. 报告给定示例失败。This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.提供此方法是为了允许DocTestRunner的子类自定义其输出;不应直接调用它。

example is the example about to be processed. example是即将处理的示例。got is the actual output from the example. 是示例的实际输出。test is the test containing example. 是包含测试的exampleout is the output function that was passed to DocTestRunner.run().是传递给DocTestRunner.run()的输出函数。

report_unexpected_exception(out, test, example, exc_info)

Report that the given example raised an unexpected exception. 报告给定示例引发意外异常。This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.提供此方法是为了允许DocTestRunner的子类自定义其输出;不应直接调用它。

example is the example about to be processed. 是即将处理的示例。exc_info is a tuple containing information about the unexpected exception (as returned by sys.exc_info()). 是一个包含意外异常信息的元组(由sys.exc_info()返回)。test is the test containing example. 是包含测试的exampleout is the output function that was passed to DocTestRunner.run().是传递给DocTestRunner.run()的输出函数。

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

Run the examples in test (a DocTest object), and display the results using the writer function out.运行test中的示例(DocTest对象),并使用writer函数out显示结果。

The examples are run in the namespace test.globs. 示例在命名空间test.globs中运行。If clear_globs is true (the default), then this namespace will be cleared after the test runs, to help with garbage collection. 如果clear_globstrue(默认值),则在测试运行后将清除此命名空间,以帮助垃圾收集。If you would like to examine the namespace after the test completes, then use clear_globs=False.如果您想在测试完成后检查名称空间,请使用clear_globs=False

compileflags gives the set of flags that should be used by the Python compiler when running the examples. 给出了Python编译器在运行示例时应使用的一组标志。If not specified, then it will default to the set of future-import flags that apply to globs.如果未指定,则默认为应用于globs的一组未来导入标志。

The output of each example is checked using the DocTestRunner’s output checker, and the results are formatted by the DocTestRunner.report_*() methods.使用DocTestRunner的输出检查器检查每个示例的输出,结果由DocTestRunner.report_*()方法格式化。

summarize(verbose=None)

Print a summary of all the test cases that have been run by this DocTestRunner, and return a named tuple TestResults(failed, attempted).打印此DocTestRunner已运行的所有测试用例的摘要,并返回命名的元组TestResults(failed, attempted)

The optional verbose argument controls how detailed the summary is. 可选的verbose参数控制摘要的详细程度。If the verbosity is not specified, then the DocTestRunner’s verbosity is used.如果未指定详细信息,则使用DocTestRunner的详细信息。

OutputChecker objects

classdoctest.OutputChecker

A class used to check the whether the actual output from a doctest example matches the expected output. 用于检查doctest示例的实际输出是否与预期输出匹配的类。OutputChecker defines two methods: check_output(), which compares a given pair of outputs, and returns True if they match; and output_difference(), which returns a string describing the differences between two outputs.定义了两个方法:check_output(),它比较给定的一对输出,如果匹配则返回True;以及output_difference(),它返回描述两个输出之间差异的字符串。

OutputChecker defines the following methods:定义了以下方法:

check_output(want, got, optionflags)

Return True iff the actual output from an example (got) matches the expected output (want). 如果示例(got)的实际输出与预期输出(want)匹配,则返回TrueThese strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. 如果这些字符串相同,则始终认为它们匹配;但是,根据测试运行者使用的选项标志,也可能有几种不完全匹配的类型。See section Option Flags for more information about option flags.有关选项标志的更多信息,请参阅选项标志一节。

output_difference(example, got, optionflags)

Return a string describing the differences between the expected output for a given example (example) and the actual output (got). 返回一个字符串,描述给定示例(example)的预期输出与实际输出(got)之间的差异。optionflags is the set of option flags used to compare want and got.optionflags是用于比较wantgot的选项标志集。

Debugging调试

Doctest provides several mechanisms for debugging doctest examples:Doctest提供了几种调试Doctest示例的机制:

  • Several functions convert doctests to executable Python programs, which can be run under the Python debugger, pdb.几个函数将doctest转换为可执行的Python程序,这些程序可以在Python调试器pdb下运行。

  • The DebugRunner class is a subclass of DocTestRunner that raises an exception for the first failing example, containing information about that example. DebugRunner类是DocTestRunner的一个子类,它为第一个失败的示例引发异常,包含有关该示例的信息。This information can be used to perform post-mortem debugging on the example.此信息可用于对示例执行事后调试。

  • The unittest cases generated by DocTestSuite() support the debug() method defined by unittest.TestCase.DocTestSuite()生成的unittest用例支持unittest.TestCase定义的debug()方法。

  • You can add a call to pdb.set_trace() in a doctest example, and you’ll drop into the Python debugger when that line is executed. 您可以在doctest示例中添加对pdb.set_trace()的调用,当执行该行时,您将进入Python调试器。Then you can inspect current values of variables, and so on. 然后可以检查变量的当前值,依此类推。For example, suppose a.py contains just this module docstring:例如,假设a.py仅包含以下模块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:然后,交互式Python会话可能如下所示:

    >>> import a, 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 x
    6
    (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 x
    3
    (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 synthesized code under the debugger:将doctest转换为Python代码,并可能在调试器下运行合成代码的函数:

doctest.script_from_examples(s)

Convert text with examples to a script.将带有示例的文本转换为脚本。

Argument s is a string containing doctest examples. 参数s是包含doctest示例的字符串。The string is converted to a Python script, where doctest examples in s are converted to regular code, and everything else is converted to Python comments. 字符串被转换为Python脚本,其中s中的doctest示例被转换为常规代码,其他所有内容都被转换为Python注释。The generated script is returned as a string. 生成的脚本作为字符串返回。For example,例如

import doctest
print(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 be useful when you want to transform an interactive Python session into a Python script.此函数由其他函数在内部使用(请参见下文),但当您希望将交互式Python会话转换为Python脚本时,它也很有用。

doctest.testsource(module, name)

Convert the doctest for an object to a script.将对象的doctest转换为脚本。

Argument module is a module object, or dotted name of a module, containing the object whose doctests are of interest. 参数module是一个模块对象,或模块的虚线名称,包含其doctest感兴趣的对象。Argument name is the name (within the module) of the object with the doctests of interest. 参数name是具有感兴趣的doctest的对象的名称(在模块内)。The result is a string, containing the object’s docstring converted to a Python script, as described for script_from_examples() above. 结果是一个字符串,包含转换为Python脚本的对象的文档字符串,如上面script_from_examples()所述。For example, if module a.py contains a top-level function f(), then例如,如果模块a.py包含顶级函数f(),则

import a, doctest
print(doctest.testsource(a, "a.f"))

prints a script version of function f()’s docstring, with doctests converted to code, and the rest placed in comments.打印函数f()的docstring的脚本版本,doctest转换为代码,其余的放在注释中。

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

Debug the doctests for an object.调试对象的doctest。

The module and name arguments are the same as for function testsource() above. modulename参数与上述函数testsource()相同。The synthesized Python script for the named object’s docstring is written to a temporary file, and then that file is run under the control of the Python debugger, pdb.命名对象的docstring的合成Python脚本被写入一个临时文件,然后该文件在Python调试器pdb的控制下运行。

A shallow copy of module.__dict__ is used for both local and global execution context.module.__dict__的浅显副本用于本地和全局执行上下文。

Optional argument pm controls whether post-mortem debugging is used. 可选参数pm控制是否使用事后调试。If pm has a true value, the script file is run directly, and the debugger gets involved only if the script terminates via raising an unhandled exception. 如果pm的值为true,则脚本文件将直接运行,只有当脚本通过引发未处理的异常而终止时,调试器才会参与。If it does, then post-mortem debugging is invoked, via pdb.post_mortem(), passing the traceback object from the unhandled exception. 如果是,则通过 pdb.post_mortem()调用事后调试,从未处理的异常传递回溯对象。If pm is not specified, or is false, the script is run under the debugger from the start, via passing an appropriate exec() call to pdb.run().如果未指定pmpmfalse,则脚本从一开始就在调试器下运行,通过向pdb.run()传递适当的exec()调用。

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

Debug the doctests in a string.在字符串中调试doctest。

This is like function debug() above, except that a string containing doctest examples is specified directly, via the src argument.这与上面的函数debug()类似,只是通过src参数直接指定了包含doctest示例的字符串。

Optional argument pm has the same meaning as in function debug() above.可选参数pm的含义与上述函数debug()中的含义相同。

Optional argument globs gives a dictionary to use as both local and global execution context. 可选参数globs提供了一个既可以用作本地执行上下文也可以用作全局执行上下文的字典。If not specified, or None, an empty dictionary is used. 如果未指定或None,则使用空字典。If specified, a shallow copy of the dictionary is used.如果指定,则使用词典的浅副本。

The DebugRunner class, and the special exceptions it may raise, are of most interest to testing framework authors, and will only be sketched here. DebugRunner类以及它可能引发的特殊异常是测试框架作者最感兴趣的,这里只略述。See the source code, and especially DebugRunner’s docstring (which is a doctest!) for more details:有关详细信息,请参阅源代码,尤其是DebugRunner的docstring(这是一个doctest!):

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

A subclass of DocTestRunner that raises an exception as soon as a failure is encountered. DocTestRunner的一个子类,一旦遇到故障就会引发异常。If an unexpected exception occurs, an UnexpectedException exception is raised, containing the test, the example, and the original exception. 如果发生意外异常,将引发UnexpectedException异常,其中包含测试、示例和原始异常。If the output doesn’t match, then a DocTestFailure exception is raised, containing the test, the example, and the actual output.如果输出不匹配,则会引发DocTestFailure异常,其中包含测试、示例和实际输出。

For information about the constructor parameters and methods, see the documentation for DocTestRunner in section Advanced API.有关构造函数参数和方法的信息,请参阅高级API部分中DocTestRunner的文档。

There are two exceptions that may be raised by DebugRunner instances:DebugRunner实例可能引发两个异常:

exceptiondoctest.DocTestFailure(test, example, got)

An exception raised by DocTestRunner to signal that a doctest example’s actual output did not match its expected output. DocTestRunner引发的异常,表示doctest示例的实际输出与其预期输出不匹配。The constructor arguments are used to initialize the attributes of the same names.构造函数参数用于初始化同名属性。

DocTestFailure defines the following attributes:定义以下属性:

DocTestFailure.test

The DocTest object that was being run when the example failed.示例失败时正在运行的DocTest对象。

DocTestFailure.example

The Example that failed.失败的Example

DocTestFailure.got

The example’s actual output.示例的实际输出。

exceptiondoctest.UnexpectedException(test, example, exc_info)

An exception raised by DocTestRunner to signal that a doctest example raised an unexpected exception. DocTestRunner引发的异常,表示doctest示例引发了意外异常。The constructor arguments are used to initialize the attributes of the same names.构造函数参数用于初始化同名属性。

UnexpectedException defines the following attributes:定义以下属性:

UnexpectedException.test

The DocTest object that was being run when the example failed.示例失败时正在运行的DocTest对象。

UnexpectedException.example

The Example that failed.失败的Example

UnexpectedException.exc_info

A tuple containing information about the unexpected exception, as returned by sys.exc_info().包含意外异常信息的元组,由sys.exc_info()返回。

Soapbox肥皂箱

As mentioned in the introduction, doctest has grown to have three primary uses:如引言中所述,doctest已发展成为三个主要用途:

  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 bad documentation.特别是,用晦涩的测试用例填充文档字符串会导致糟糕的文档。

When writing a docstring, choose docstring examples with care. 编写文档字符串时,请小心选择文档字符串示例。There’s an art to this that needs to be learned—it may not be natural at first. 这是一门需要学习的艺术,一开始可能并不自然。Examples should add genuine value to the documentation. 示例应该为文档增加真正的价值。A good example can often be worth many words. 一个好的例子往往值得多言。If done with care, the examples will be invaluable for your users, and will pay back the time it takes to collect them many times over as the years go by and things change. 如果认真完成,这些示例对您的用户来说将是非常宝贵的,并且随着时间的推移和情况的变化,这些示例将可以多次收集。I’m still amazed at how often one of my doctest examples stops working after a “harmless” change.我仍然惊讶于我的一个doctest示例在一次“无害”的更改后停止工作的频率。

Doctest also makes an excellent tool for regression testing, especially if you don’t skimp on explanatory text. Doctest也为回归测试提供了一个极好的工具,特别是如果你不吝啬解释性文本的话。By interleaving prose and examples, it becomes much easier to keep track of what’s actually being tested, and why. 通过将散文和示例交织在一起,可以更容易地跟踪实际测试的内容以及原因。When a test fails, good prose can make it much easier to figure out what the problem is, and how it should be fixed. 当测试失败时,好的散文可以让你更容易弄清楚问题是什么,以及应该如何解决。It’s true that you could write extensive comments in code-based testing, but few programmers do. 的确,您可以在基于代码的测试中编写大量注释,但很少有程序员这样做。Many have found that using doctest approaches instead leads to much clearer tests. 许多人发现,使用doctest方法反而会导致更清晰的测试。Perhaps this is simply because doctest makes writing prose a little easier than writing code, while writing comments in code is a little harder. 也许这仅仅是因为doctest使撰写散文比编写代码容易一点,而在代码中编写注释则困难一点。I think it goes deeper than just that: the natural attitude when writing a doctest-based test is that you want to explain the fine points of your software, and illustrate them with examples. 我认为这不仅仅是一个问题:编写基于doctest的测试时的自然态度是,你想解释你的软件的优点,并用例子来说明它们。This in turn naturally leads to test files that start with the simplest features, and logically progress to complications and edge cases. 这反过来自然会导致测试文件从最简单的特性开始,并从逻辑上进展到复杂和边缘情况。A coherent narrative is the result, instead of a collection of isolated functions that test isolated bits of functionality seemingly at random. 一个连贯的叙述是结果,而不是一组孤立的函数,这些函数似乎随机测试孤立的功能。It’s a different attitude, and produces different results, blurring the distinction between testing and explaining.这是一种不同的态度,产生不同的结果,模糊了测试和解释之间的区别。

Regression testing is best confined to dedicated objects or files. 回归测试最好仅限于专用对象或文件。There are several options for organizing tests:组织测试有几个选项:

  • Write text files containing test cases as interactive examples, and test the files using testfile() or DocFileSuite(). 编写包含测试用例的文本文件作为交互示例,并使用testfile()DocFileSuite()测试这些文件。This is recommended, although is easiest to do for new projects, designed from the start to use doctest.这是建议的,尽管对于从一开始就使用doctest设计的新项目来说,这是最容易做到的。

  • Define functions named _regrtest_topic that consist of single docstrings, containing test cases for the named topics. 定义名为_regrtest_topic的函数,该函数由单个文档字符串组成,包含命名主题的测试用例。These functions can be included in the same file as the module, or separated out into a separate test file.这些功能可以包含在与模块相同的文件中,也可以分离到单独的测试文件中。

  • Define a __test__ dictionary mapping from regression test topics to docstrings containing test cases.定义从回归测试主题到包含测试用例的文档字符串的__test__字典映射。

When you have placed your tests in a module, the module can itself be the test runner. 当您将测试放置在模块中时,模块本身可以是测试运行器。When a test fails, you can arrange for your test runner to re-run only the failing doctest while you debug the problem. 当测试失败时,您可以安排测试运行者在调试问题时仅重新运行失败的doctest。Here is a minimal example of such a test runner:下面是这样一个测试运行器的最小示例:

if __name__ == '__main__':
import doctest
flags = doctest.REPORT_NDIFF|doctest.FAIL_FAST
if len(sys.argv) > 1:
name = sys.argv[1]
if name in globals():
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("{} failures out of {} tests".format(fail, total))

Footnotes

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 that also makes for a confusing test.试图猜测其中一个结束,另一个开始的位置太容易出错,这也会导致测试混乱。