说明:第一种思路(使用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 the first 5 natural numbers should be 15
(2)如果测试成功,则无提示
二、使用Doctests进行测试
1. 通过function: testmod
代码:
from doctest import testmod
def sum_naturals(n):
"""re

本文介绍了Python代码测试的两种方法:使用Assertions和Doctests。在PyCharm环境中,Assertions测试通过时无提示,失败则显示AssertionError。Doctests测试包括testmod和run_docstring_examples函数,成功时显示测试通过数量,命令行测试成功则无提示。
最低0.47元/天 解锁文章
1341

被折叠的 条评论
为什么被折叠?



