doctest是python自带的一个模块,你可以把它叫做“文档测试”(doctest)模块。
我在认识这个模块时,总是不会写,发现格式总是找不对,现在做一下总结。
官方文件描述是:
In simplest use, end each module M to be tested with:
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
Then running the module as a script will cause the examples in the
docstrings to get executed and verified:
python M.py
This won't display anything unless an example fails, in which case the
failing example(s) and the cause(s) of the failure(s) are printed to stdout
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
line of output is "Test failed.".
大体意思就是引入这个模块就能对我们编写的程序进行测试。
简单的测试:
def collect_vowels(s):
""" (str) -> str
Return the vowels (a, e, i, o, and u) from s.
>>> collect_vowels('Happy Anniversary!')
'aAiea'
>>> collect_vowels('xyz')
''
"""
vowels = ''
for char in s:
if char in 'aeiouAEIOU':
vowels = vowels + char
return vowels
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
运行结果:
PS C:\Users\15222\lpthw> python ex471.py
Trying:
collect_vowels('Happy Anniversary!')
Expecting:
'aAiea'
ok
Trying:
collect_vowels('xyz')
Expecting:
''
ok
1 items had no tests:
__main__
1 items passed all tests:
2 tests in __main__.collect_vowels
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
PS C:\Users\15222\lpthw>
由于加上了语句`verbose=True``强制将详细信息显示出来,否则就是什么都不输出;去掉那个语句后的运行结果是:
PS C:\Users\15222\lpthw> python ex471.py
PS C:\Users\15222\lpthw>
这是测试的函数中输入的字符串中的元音输出,正确的话,就通过测试。