Unittest Framework 简明教程

UnitTest Framework - Doctest

Python 的标准发行版包含“Doctest”模块。此模块的功能使其能够搜索看起来像交互式 Python 会话的文本片断,并执行这些会话以查看它们是否完全按照显示的那样工作。

Python' standard distribution contains 'Doctest' module. This module’s functionality makes it possible to search for pieces of text that look like interactive Python sessions, and executes these sessions to see if they work exactly as shown.

Doctest 在以下场景中非常有用 −

Doctest can be very useful in the following scenarios −

  1. To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.

  2. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.

  3. To write tutorial documentation for a package, liberally illustrated with input-output examples

在 Python 中,‘文档字符串’是一个字符串文字,它作为类,函数或模块中的第一个表达式出现。当执行该套件时,它会被忽略,但会被编译器识别并放入封闭类,函数或模块的 doc 属性中。由于它是通过自省获得的,因此它是文档对象规则的地方。

In Python, a 'docstring' is a string literal which appears as the first expression in a class, function or module. It is ignored when the suite is executed, but it is recognized by the compiler and put into the doc attribute of the enclosing class, function or module. Since it is available via introspection, it is the canonical place for documentation of the object.

在 Python 代码不同部分使用示例用法的通常做法是将其放入文档字符串中。doctest 模块允许验证这些文档字符串在代码之间断断续续的修订中是处于最新状态。

It is a usual practice to put example usage of different parts of Python code inside the docstring. The doctest module allows to verify that these docstrings are up-to-date with the intermittent revisions in code.

在下面的代码中,一个阶乘函数与示例用法穿插定义。为了验证示例用法是否正确,请在 doctest 模块中调用 testmod() 函数。

In the following code, a factorial function is defined interspersed with example usage. In order to verify if the example usage is correct, call the testmod() function in doctest module.

"""
This is the "example" module.

The example module supplies one function, factorial(). For example,

>>> factorial(5)
120
"""

def factorial(x):
   """Return the factorial of n, an exact integer >= 0.
   >>> factorial(-1)
   Traceback (most recent call last):
      ...
   ValueError: x must be >= 0
   """

   if not x >= 0:
      raise ValueError("x must be >= 0")
   f = 1
   for i in range(1,x+1):
      f = f*i
   return f

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

输入并保存上述脚本为 FactDocTest.py,尝试从命令行执行此脚本。

Enter and save the above script as FactDocTest.py and try to execute this script from the command line.

Python FactDocTest.py

除非示例失败,否则不会显示任何输出。现在,将命令行更改为以下内容:

No output will be shown unless the example fails. Now, change the command line to the following −

Python FactDocTest.py –v

控制台现在会显示以下输出:

The console will now show the following output −

C:\Python27>python FactDocTest.py -v
Trying:
   factorial(5)
Expecting:
   120
ok
Trying:
   factorial(-1)
Expecting:
   Traceback (most recent call last):
      ...
   ValueError: x must be >= 0
ok
2 items passed all tests:
   1 tests in __main__
   1 tests in __main__.factorial
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

另一方面,如果 factorial() 函数的代码在文档字符串中没有给出预期结果,则会显示失败结果。例如,在上述脚本中将 f = 1 更改为 f = 2,然后再次运行 doctest。结果如下:

If, on the other hand, the code of factorial() function doesn’t give expected result in docstring, failure result will be displayed. For instance, change f = 2 in place of f = 1 in the above script and run the doctest again. The result will be as follows −

Trying:
   factorial(5)
Expecting:
   120
**********************************************************************
File "docfacttest.py", line 6, in __main__
Failed example:
factorial(5)
Expected:
   120
Got:
   240
Trying:
   factorial(-1)
Expecting:
   Traceback (most recent call last):
      ...
   ValueError: x must be >= 0
ok
1 items passed all tests:
   1 tests in __main__.factorial
**********************************************************************
1 items had failures:
   1 of 1 in __main__
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.

Doctest: Checking Examples in a Text File

doctest 的另一个简单应用是在文本文件中测试交互式示例。这可以使用 testfile() 函数完成。

Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function.

以下文本存储在名为 "example.txt" 的文本文件中。

The following text is stored in a text file named 'example.txt'.

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(5)
   120

文件内容被当作文档字符串处理。为了验证文本文件中的示例,请使用 doctest 模块的 testfile() 函数。

The file content is treated as docstring. In order to verify the examples in the text file, use the testfile() function of doctest module.

def factorial(x):
   if not x >= 0:
      raise ValueError("x must be >= 0")
   f = 1
   for i in range(1,x+1):
      f = f*i
   return f

if __name__ == "__main__":
   import doctest
   doctest.testfile("example.txt")
  1. As with the testmod(), testfile() won’t display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to console, using the same format as testmod().

  2. 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.

  3. 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.

  4. 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.