测试的基本手段即使,保证和测试足够多的 case 。
交互式解释器的会话可以以文档字符串(docstring,在该文档字符串内部测试一些基本案例)的形式写入文档。如下:
def square(x):
'''
squares a number and returns the result.
>>> square(2)
4
>>> square(3)
9
'''
return x**2
文档字符串也可以包含一些文本(squares a number and returns the result.
)。然而这与测试又有什么关系?假如 square 定义在 my_math 模块(也就是叫做 my_math.py 的文件)。我们可在该文件的末尾添加如下的代码:
if __name__ == '__main__':
import doctest, my_math
doctest.testmod(my_math)
在命令行界面,为该脚本(script)设定 -v (verbose,详述)选项开关:
$ python my_math.py -v
将会得到如下的输出:
Trying:
square(2)
Expecting:
4
ok
Trying:
square(3)
Expecting:
9
ok
1 items had no tests:
demo
1 items passed all tests:
2 tests in demo.square
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
如果在 square 函数的内部,我们定义了错误的实现,比如将return x**2
写作 return x**x
,再次运行,将得到如下的结果:
Failed example:
square(3)
Expected:
9
Got:
27
1 items had no tests:
demo
**********************************************************************
1 items had failures:
1 of 2 in demo.square
2 tests in 2 items.
1 passed and 1 failed.
***Test Failed*** 1 failures.