python doctest模块
2013-08-02 10:56
239 查看
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
相关文章推荐
- python之基础篇(十)——执行环境与doctest模块
- Python doctest自动测试
- 使用DocStrings为python函数添加注释
- 简明python教程学习笔记之十-DocStrings文档字符串
- Python随笔之文档字符串(DocStrings)
- Python 测试(一)—— doctest
- python 把一个文件夹下的docx转化为doc
- 飘逸的python - 代码即文档docstring
- python如何处理解析word文档doc docx , python-docx,python-docx2txt,zipfile
- python 函数、函数式编程、变量作用域、函数__doc__属性
- python 文档测试:doctest
- python中doctest自我测试(测试模块中的函数是否对)
- 在命令行模式下查看Python帮助文档---dir、help、__doc__
- Python中的DocStrings
- Python中print(__doc__)作用的教程
- python中的文档字符串(docString)
- Python doctest
- python基础31[docstring]
- python __doc__ 文档说明
- 31.Python的单元测试工具——doctest