Python文档测试---doctest

Python中的文档测试doctest非常之简单,就是对注释部分测试,按Python的自带IDE的语法进行,即交互模式

下面看一个简单的栗子,test.py

#coding:UTF-8
import doctest
def ceshi(x):
    """#这是文档测试的内容
    >>> ceshi(2)
    1
    >>> ceshi(3)
    0
    """#End
    if x%2==0:
        return 1
    else:
        return 0

if __name__ == "__main__":
doctest.testmod(verbose=True)
#doctest.testmod是测试模块,verbose默认是False,意思是出错才用提示;True,对错都有执行结果

 下面是运行结果:

 1 Trying:
 2     ceshi(2)
 3 Expecting:
 4     1
 5 ok
 6 Trying:
 7     ceshi(3)
 8 Expecting:
 9     0
10 ok
11 1 items had no tests:
12     __main__
13 1 items passed all tests:
14    2 tests in __main__.ceshi
15 2 tests in 2 items.
16 2 passed and 0 failed.
17 Test passed.

我们可以从第16行代码看到,2个测试都通过了

文档测试算是比较简单的,要注意的地方就是格式上问题

>>>def ... 
#显然是错的

>>> def ...
#用过IDE的应该都知道,要空一格

好了,本章到此结束

End

原文地址:https://www.cnblogs.com/yin-tao/p/7084937.html