doctest查找和执行交互式Python会话,检验其符合预期,常用场景如下:
- 检验模块的文档字符串是最新的。
- 衰退测试。
- 书写教程。
Doctest比unittest简单,没有API。不过doctest没有fixture,不适合复杂的场景
Getting Started¶
需要注意的是,“>>>”后面必须跟个空格,否则会报错
def my_function(a, b):
"""
>>> my_function(2, 3)
6
>>> my_function('a', 3)
'aaa'
"""
return a * b
To run the tests, use doctest as the main program via the-m option to the interpreter. Usually no output is produced while the tests are running,
-v表示显示详细执行过程。测试用例以空行或者下个解释器提示符表示结束。
$ python -m doctest -v doctest_simple.py
Trying:
my_function(2, 3)
Expecting:
6
ok
Trying:
my_function('a', 3)
Expecting:
'aaa'
ok
1 items had no tests:
doctest_simple
1 items passed all tests:
2 tests in doctest_simple.my_function
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
Examples cannot usually stand on their own as explanations of a function, so doctest also lets you keep the surrounding text you would normally include in the documentation. It looks for lines beginning with the interpreter prompt,>>>, to find the beginning of a test case. The case is ended by a blank line, or by the next interpreter prompt. Intervening text is ignored, and can have any format as long as it does not look like a test case.
def my_function(a, b):
"""Returns a * b.
Works with numbers:
>>> my_function(2, 3)
6
and strings:
>>> my_function('a', 3)
'aaa'
"""
return a * b
The surrounding text in the updated docstring makes it more useful to a human reader, and is ignored bydoctest, and the results are the same.
$ python -m doctest -v doctest_simple_with_docs.py
Trying:
my_function(2, 3)
Expecting:
6
ok
Trying:
my_function('a', 3)
Expecting:
'aaa'
ok
1 items had no tests:
doctest_simple_with_docs
1 items passed all tests:
2 tests in doctest_simple_with_docs.my_function
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
另外的例子
#!/usr/bin/env python3.2
def is_between(v, lower, higher):
'''demo of doctest
>>> is_between(5,1,9)
True
>>> is_between(3,3,9)
False
'''
return lower<v<higher
if __name__=='__main__':
import doctest
doctest.testmod(verbose=True)
需要注意的是,“>>>”后面必须跟个空格,否则会报错
ValueError: line 2 of the docstring for __main__.is_between lacks blank after >>>: ' >>>is_between(5,1,9) '
python thefile.py -v
显示doctest详细信息
转自:http://blog.sina.com.cn/s/blog_630c58cb0100u20d.html