title: Python doctest测试

tags: Python

doctest测试

python 提供了REPL(read-eval-print loop,读取、求值、输出的循环)

官方地址:https://docs.python.org/3/library/doctest.html

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

执行Python3 test.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(30)
Expecting:
265252859812191058636308480000000
**********************************************************************
File "test.py", line 15, in __main__.factorial
Failed example:
factorial(30)
Expected:
265252859812191058636308480000000
Got:
265252859812191058636308480000000L
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
**********************************************************************
File "test.py", line 27, in __main__.factorial
Failed example:
factorial(30.0)
Expected:
265252859812191058636308480000000
Got:
265252859812191058636308480000000L
Trying:
factorial(1e100)
Expecting:
Traceback (most recent call last):
...
OverflowError: n too large
ok
1 items passed all tests:
1 tests in __main__
**********************************************************************
1 items had failures:
2 of 6 in __main__.factorial
7 tests in 2 items.
5 passed and 2 failed.
***Test Failed*** 2 failures.
05-08 15:26