文档测试doctest及常见问题
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
author = 'Noiccy'
'''description:文档测试'''
def fact(n):
'''
Calculate 1*2*...*n
>>> fact(1)
1
>>> fact(10)
3628800
>>> fact(-1)
Traceback (most recent call last):
...
ValueError
'''
if n < 1:
raise ValueError()
if n == 1:
return 1
return n*fact(n-1)
if __name__ == '__main__':
import doctest
doctest.testmod()
运行后,没有输出内容才是正确的!
可能遇到的问题:
一、AttributeError: module 'doctest' has no attribute 'testmod'
报错原因:保存的文件名是doctest.py,导致doctest模块被重写。修改文件名,并删除文件目录下的__pycache__文件夹后,重新运行即可
二、ValueError: line 3 of the docstring for __main__.fact lacks blank after >>>: '>>>fact(1)'
报错原因:>>>后面有个空格
三、File "E:\LearnPython\doctest1.py", line 14, in __main__.fact
Failed example:
fact(-1)
Exception raised:
Traceback (most recent call last):
File "C:\Program Files\Python36\lib\doctest.py", line 1330, in __run
compileflags, 1), test.globs)
File "<doctest __main__.fact[2]>", line 1, in <module>
fact(-1)
File "E:\LearnPython\doctest1.py", line 20, in fact
raise ValueError()
ValueError
报错原因:Traceback后面有个空格
下一篇: 服务器被黑给我上了一课