python代码测试的两种思路

本文介绍了Python代码测试的两种方法:使用Assertions和Doctests。在PyCharm环境中,Assertions测试通过时无提示,失败则显示AssertionError。Doctests测试包括testmod和run_docstring_examples函数,成功时显示测试通过数量,命令行测试成功则无提示。
摘要由CSDN通过智能技术生成

说明:第一种思路(使用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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值