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

python自动化单元测试工具----doctest

2017-02-14 10:02 676 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: