使用doctest模块在Python中进行测试

文件串 在Python中,它们不仅用于描述类或函数,以便更好地理解代码和用法,还用于测试目的。

null

这个 博士测试模块 在docstring中查找看起来像交互式shell命令的模式。

输入和预期输出包含在docstring中,然后doctest模块使用该docstring测试处理后的输出。 在通过docstring进行解析之后,解析后的文本将作为python shell命令执行,并将结果与从docstring获取的预期结果进行比较。

下面是一个简单的例子:

1.从doctest导入testmod以测试函数。 2.定义我们的测试功能。 3.提供一个合适的文档字符串,其中包含特定输入的所需输出。 4.定义逻辑。 5.使用函数名调用testmod函数进行测试,并将verbose True设置为参数。

注: 所有参数都是可选的。函数名显式传递给testmod。如果有多个函数,它很有用。

实施

# import testmod for testing our function
from doctest import testmod
# define a function to test
def factorial(n):
'''
This function calculates recursively and
returns the factorial of a positive number.
Define input and expected output:
>>> factorial(3)
6
>>> factorial(5)
120
'''
if n < = 1 :
return 1
return n * factorial(n - 1 )
# call the testmod function
if __name__ = = '__main__' :
testmod(name = 'factorial' , verbose = True )


输出:

Trying:
    factorial(3)
Expecting:
    6
ok
Trying:
    factorial(5)
Expecting:
    120
ok
1 items had no tests:
    factorial
1 items passed all tests:
   2 tests in factorial.factorial
2 tests in 2 items.
2 passed and 0 failed.
Test passed.

现在,测试失败。如果我们的逻辑是错误的呢?

# import testmod for testing our function
from doctest import testmod
# define a function to test
def factorial(n):
'''
This function calculates recursively and
returns the factorial of a positive number.
Define input and expected output:
>>> factorial(3)
6
>>> factorial(5)
120
'''
if n < = 1 :
return 1
# wrong logic for factorial
return factorial(n - 1 )
# call the testmod function
if __name__ = = '__main__' :
testmod(name = 'factorial' , verbose = True )


输出:

Trying:
    factorial(3)
Expecting:
    6
**********************************************************************
File "woking_with_csv.py", line 33, in factorial.factorial
Failed example:
    factorial(3)
Expected:
    6
Got:
    1
Trying:
    factorial(5)
Expecting:
    120
**********************************************************************
File "woking_with_csv.py", line 35, in factorial.factorial
Failed example:
    factorial(5)
Expected:
    120
Got:
    1
1 items had no tests:
    factorial
**********************************************************************
1 items had failures:
   2 of   2 in factorial.factorial
2 tests in 2 items.
0 passed and 2 failed.
***Test Failed*** 2 failures.

笔记 :如果“verbose”设置为False(默认),则仅在失败时显示输出,而在成功时不显示输出。

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享