标准库:doctest
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.
>>>
>>> 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 -v
输出:
Trying:
factorial(5)
Expecting:
120
ok
Trying:
Expecting:
ok
Trying:
factorial(30)
Expecting:
265252859812191058636308480000000
ok
Trying:
factorial(-1)
Expecting:
Traceback (most recent call last):
...
ValueError: n must be >= 0
ok
Trying:
factorial(30.1)
Expecting:
Traceback (most recent call last):
...
ValueError: n must be exact integer
ok
Trying:
factorial(30.0)
Expecting:
265252859812191058636308480000000
ok
Trying:
factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
2 items passed all tests:
1 tests in __main__
6 tests in __main__.factorial
7 tests in 2 items.
7 passed and 0 failed.
Test passed.
原文出处:https://docs.python.org/zh-cn/3/library/doctest.html
页:
[1]