doctest 模块寻找像Python交互式代码的文本,然后执行这些代码来确保它们的确就像展示的那样正确运行,类似于单元测试
doctest测试用例放在两个地方:
1、函数或者方法下的注释里面
2、模块的开头
它可以用来测试代码,以测试该函数、类、类方法的功能是否正确。
在函数、类或方法的说明性文档中,以>>>作为开始的内容表示一行测试代码,并且接下来的一行则明确该测试代码的输出结果。
代码参考如下:
1 # content of test_doctest.py 2 def something(): 3 """ a doctest in a docstring 4 >>> something() 5 42 6 """ 7 return 42 8 9 def num(n): 10 """ 11 function:斐波那契数列 12 >>> num(5) 13 [0, 1, 1, 2, 3] 14 """ 15 titles = [] 16 a = 0 17 b = 1 18 for i in range(n): 19 titles.append(a) 20 a, b = b, a+b 21 22 return titles 23 24 25 if __name__ == '__main__': 26 import doctest 27 doctest.testmod(verbose=True)
结果:
1 C:UsersAdministratorPycharmProjectsuntitled2venvScriptspython.exe C:/Users/Administrator/PycharmProjects/untitled2/forpytest/test_doctest.py 2 Trying: 3 num(5) 4 Expecting: 5 [0, 1, 1, 2, 3] 6 ok 7 Trying: 8 something() 9 Expecting: 10 42 11 ok 12 1 items had no tests: 13 __main__ 14 2 items passed all tests: 15 1 tests in __main__.num 16 1 tests in __main__.something 17 2 tests in 3 items. 18 2 passed and 0 failed. 19 Test passed. 20 21 Process finished with exit code 0
在执行 doctest.testmod() 函数时,它会执行该模块中各成员说明性文档包含的测试代码,并将执行结果和指定的结果做比对,如果一致,则什么也不输出;反之,则输出以下提示信息:
-
显示在哪个源文件的哪一行。
-
Failed example,显示是哪个测试用例出错了。
-
Expected,显示程序期望的输出结果。也就是在“>>>命令”的下一行给出的运行结果,它就是期望结果。
-
Got,显示程序实际运行产生的输出结果。只有当实际运行产生的输出结果与期望结果一致时,才表明该测试用例通过。
参考: