利用terminal(如cmd,git bash)对程序进行测试:
输入:
python -m doctest -v Filename.py
(注意,若python环境为python2和python3 则需要将输入更改为:)
python3 -m doctest -v Filename.py
def identity(k):
return k
def cube(k):
return pow(k,3)
def summation(n, term):
total, k = 0, 1
while k <= n:
total, k = total + term(k), k + 1
return total
def sum_naturals(n):
"""sum the first N natural numbers
>>> sum_naturals(5)
15
"""
#上面为测试内容
return summation(n, identity)
def sum_cubes(n):
"""sum the first N cubes of natural numbers
>>> sum_cubes(5)
225
"""
#上面为测试内容
return summation(n, cube)
>>> 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)
Finding tests in NoName
Trying:
sum_naturals(10)
Expecting:
55
ok
Trying:
sum_naturals(100)
Expecting:
5050
ok
参考链接:http://composingprograms.com/pages/15-control.html#testing