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

📅  最后修改于: 2022-05-13 01:55:39.846000             🧑  作者: Mango

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

Python中的文档Python不仅用于描述类或函数,以更好地理解代码和使用,还用于测试目的。

Doctest 模块在文档字符串中查找类似于交互式 shell 命令的模式。

输入和预期输出包含在文档字符串中,然后 doctest 模块使用此文档字符串来测试处理后的输出。
解析完文档字符串后,解析后的文本将作为Python shell 命令执行,并将结果与从文档字符串中获取的预期结果进行比较。

这是一个简单的例子:

执行

# 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(默认),输出将仅在失败的情况下显示,而不是在成功的情况下显示。