doctest 简介

2022-08-03 16:29 更新

doctest模块搜索看起来像交互式Python会话的文本片段,然后执行这些会话以验证它们完全按照所示方式工作。有几种常用的方法可以使用doctest:

  • 通过验证所有交互式示例仍按记录工作来检查模块的文档是否是最新的。
  • 通过验证测试文件或测试对象中的交互式示例如预期工作来执行回归测试。
  • 为包编写教程文档,用输入输出示例大量地说明。根据实例或说明文本是否被强调,这具有“识字测试”或“可执行文档”的味道。

这是一个完整但很小的示例模块:

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

    If the result is small enough to fit in an int, return an int.
    Else return a long.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> [factorial(long(n)) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000L
    >>> factorial(30L)
    265252859812191058636308480000000L
    >>> 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)
    265252859812191058636308480000000L

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

如果您直接从命令行运行example.py,那么doctest可以发挥它的魔力:

$ python example.py

没有输出!这很正常,而且这意味着所有的例子都有效。传递-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
Trying:
    [factorial(long(n)) for n in range(6)]
Expecting:
    [1, 1, 2, 6, 24, 120]
ok

以此类推,最终结局如下:

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.

这就是你需要知道的开始有效使用doctest!跳入。以下部分提供完整的详细信息。请注意,标准Python测试套件和库中有很多文档测试的例子。在标准测试文件中可以找到特别有用的示例Lib/test/test_doctest.py


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号