unit testing
An automatic procedure used to validate that individual units of code are working properly. Python has doctest built in for this purpose.
doctest是python内置模块,用于进行简单的单元测试
Doctests在函数或脚本体的第一行写入三引号,由简单的解释语、一系列输入和期望输出组成。
doctest模块会自动执行由>>>开头的任何声明,然后输出结果与注释器的期望结果进行比较
Python has a built-in doctest module for easy unit testing. Doctests can be written within a triple quoted string on the first line of the body of a function or script. They consist of sample interpreter sessions with a series of inputs to a Python prompt followed by the expected output from the Python interpreter.
The doctest module automatically runs any statement begining with >>> and compares the following line with the output from the interpreter.
例:
def is_divisible_by_2_or_5(n):
"""
>>> is_divisible_by_2_or_5(8)
True
>>> is_divisible_by_2_or_5(7)
False
>>> is_divisible_by_2_or_5(5)
True
>>> is_divisible_by_2_or_5(9)
False
"""
return n % 2 == 0 or n % 5 == 0
if __name__ == '__main__':
import doctest
doctest.testmod()
运行结果:
c:\>python myfunctions.py -v
Trying:
is_divisible_by_2_or_5(8)
Expecting:
True
ok
Trying:
is_divisible_by_2_or_5(7)
Expecting:
False
ok
Trying:
is_divisible_by_2_or_5(5)
Expecting:
True
ok
Trying:
is_divisible_by_2_or_5(9)
Expecting:
False
ok
1 items had no tests:
__main__
1 items passed all tests:
4 tests in __main__.is_divisible_by_2_or_5
4 tests in 2 items.
4 passed and 0 failed.
Test passed.