1.doctest实现对python函数的测试,用一段官方教程源码介绍:
This is the "example" module.
def factorial(n): # 阶乘函数
"""Return the factorial of n, an exact integer >= 0.
# 设定测试内容 >>>是测试内容,下一行设定输出
"""Return the factorial of n, an exact integer >= 0.
>>> [factorial(n) for n in range(6)]
[1, 1, 2, 6, 24, 120]
>>> factorial(5)
120
>>> 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()
2.直接运行源码,不报错就没有输出。
python example.py
3.打印测试过程
$ 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(1e100)
Expecting:
Traceback (most recent call last):
OverflowError: n too large