Python doctest - zhongjiajie/zhongjiajie.github.com GitHub Wiki

doctest

作用

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. There are several common ways to use doctest:

  • 在python代码中寻找类似交互解释器里执行的命令,执行它们并且和这些命令的期望值进行比较。
  • 用来验证docstring中的注释和代码实际的作用是一致的
  • 可以作为回归测试来验证代码能够正确执行
  • 可以用来编写模块的文档演示这些模块是如何处理输入得到输出的

例子

定义一个python文件

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

然后运行该文件

python example.py     # 如果test没有错误情况下默认不输出内容 如果错误会在最后一行输出错误的行数
python example.py -v  # 选择用 `-v` 参数强行让代码输出内容

详情

简单做法

例子类似,直接写在文件的__main__()

设置详细输出

运行python filename.py -v,或者在简单做法中设置testmod(verbose=True)

命令行-m输出

python -m doctest -v filename.py

编写doctest要点

  • 直接下载docstring里面
  • >>>作为用例的开始,下一个>>>或者空行作为用例的结束
  • ...代表输出的省略,如果输出的内容过长,可以通过#doctest: +ELLIPSIS结合...完成测试用例的通过

单独的doctest文件

除了将doctest写在源码里面,还可以将他写在单独的测试文本里面,可以放在一个test_<filename>.txt文件里面

这个例子展示如何将doctest用例放到一个独立的文件中
'>>>' 开头的行就是doctest测试用例
不带 '>>>' 的行就是测试用例的输出
如果实际运行的结果与期望的结果不一致,就标记为测试失败

>>> from example import factorial
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(1e100)
Traceback (most recent call last):
    ...
OverflowError: n too large

运行的时候在系统中运行python -m doctest -v test_<filename>.txt


⚠️ **GitHub.com Fallback** ⚠️