说明:第一种思路(使用Assertions进行测试)和第二种思路(使用Doctests进行测试)中的前2种方式,其测试结果都是通过 IDE:pycharm2020.3.4 x64输出的;第二种思路中的第3种方式是通过命令行进行测试,其测试结果是从git bash中截取的。本次测试使用的电脑为windows10系统
一、使用Assertions进行测试
代码:
def sum_naturals(n):
"""return the sum of the first n natural numbers"""
total, k = 0, 1
while k <= n:
total, k = total+k, k+1
return total
def sum_naturals_test():
assert sum_naturals(5) == 15, "sum of the first 5 natural numbers should be 15"
assert sum_naturals(10) == 55, "sum of the first 10 natural numbers should be 55"
assert sum_naturals(100) == 5050, "sum of the first 100 natural numbers should be 5050"
sum_naturals_test()
(1)如果测试过程中出现错误,如测试“sum_naturals(5) == 15”时出现错误,则会提示:AssertionError: sum of th