1.使用assert
聲明方法
# define a function to test
def fib(x):
if x==0:
return 0
elif x==1:
return 1
else:
return fib(x-1)+fib(x-2)
# define a test function
def fib_test():
assert fib(2) == 1, 'The 2nd Fibonacci number should be 1'
assert fib(3) == 1, 'The 3rd Fibonacci number should be 1'
assert fib(50) == 7778742049, 'Error at the 50th Fibonacci number'
# execute test
fib_test(2)
fib_test()
函數(shù)會先執(zhí)行fib()
函數(shù),然后與assert
命令的指標(biāo)進(jìn)行對比,如果不符就會報錯。
2.使用run_docstring_examples
函數(shù)
def sum_naturals(n):
"""Return the sum of the first n natural numbers.
>>> sum_naturals(10)
55
>>> sum_naturals(100)
5050
"""
total, k = 0, 1
while k <= n:
total, k = total + k, k + 1
return total
from doctest import run_docstring_examples
run_docstring_examples(sum_naturals,globals(),True)
函數(shù)sum_naturals()
在聲明時使用三個引號提供了一份簡單的說明。在編譯器中執(zhí)行help()
函數(shù)皆可獲得這段說明(按Q退出)。同時,這份說明也指出了特定之下的輸出值。利用run_docstring_examples
函數(shù)可以自動完成檢驗,并輸出檢驗結(jié)果。例如,
Trying:
sum_naturals(10)
Expecting:
55
ok
Trying:
sum_naturals(100)
Expecting:
5050
ok