您的位置:首页 > 编程语言 > Python开发

【脚本语言系列】关于Python测试工具docstrings, 你需要知道的事

2017-04-19 17:01 633 查看

如何使用docstrings

编写一个简单的程序来计算阶乘,但该程序没有覆盖所有可能的边界条件。也就是说,某些测试项目是通不过的。

编写docstring

"""
Test for the factorial of 3 that should pass.
>>> factorial(3)
6

Test for the factorial of 0 that should fail.
>>> factorial(0)
1
"""




编写NumPy代码

def factorial(n):
return numpy.arange(1, n+1).cumprod()[-1]




执行测试

完整代码

import numpy
import doctest

def factorial(n):
"""
Test for the factorial of 3 that should pass.
>>> factorial(3)
6

Test for the factorial of 0 that should fail.
>>> factorial(0)
1
"""
return numpy.arange(1, n+1).cumprod()[-1]

doctest.testmod()




详细输出



简略输出



由于出现数组为空的情况,得到了一个索引超出边界(index out of bounds)的错误

什么是docstrings

docstring是嵌入在Python代码中的字符串, 其内容看上去有点像交互式的会话。

这些字符串可用来检查某些假设, 或仅仅把他们看作是一些范例代码。

我们需要doctest模块运行这些测试。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐