Python:doctest
Docstring Tests
Python의 documentation을 읽어 테스트로 활용하는 방법입니다. 예제 보는게 이해가 빠를 겁니다.
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(-1)
Traceback (most recent call last):
...
ValueError: n must be >= 0
Factorials of floats are OK, but the float must be an exact integer:
"""
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
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
문서 주석에서 >>>
부분(7행)을 읽고 실행하여 그 아래내용과 실행한 출력과 비교하는 테스트를 수행합니다. 출력과 문자열 비교를 함으로 띄어쓰기가 하나라도 다르면 테스트 실패 합니다.
재미있는 기능이긴 한데 주로 단위테스트 프레임워크를 사용하므로 패쓰.