使用doctestDocTestSuite()执行测试案例
doctest 是 Python 自带的一种轻量级测试工具,以文档的形式书写测试用例,可以直接运行文档中的指令,并检查输出结果是否与期望一致。通过编写 doctest,可以同时完成代码的说明文档和测试用例,提高代码的可读性和可维护性。
doctest 模块提供了一个函数 doctest.DocTestSuite(),用于收集并执行 doctest 中的测试用例。下面我们将结合示例来演示如何使用 doctest.DocTestSuite()。
假设我们有一个名为 "math_functions.py" 的模块,其中定义了几个数学函数,我们想要通过 doctest 来测试这些函数的正确性。首先,我们需要在该模块中编写 doctest 的测试用例。
# math_functions.py
def add(x, y):
"""
Return the sum of x and y.
>>> add(2, 3)
5
>>> add(10, -5)
5
"""
return x + y
def multiply(x, y):
"""
Return the product of x and y.
>>> multiply(2, 3)
6
>>> multiply(-4, 5)
-20
"""
return x * y
上述代码中,定义了两个函数 add() 和 multiply(),并且为每个函数编写了 doctest 测试用例。每个测试用例都以 ">>>" 开始,后面跟着要执行的函数调用语句和期望的输出结果。
接下来,我们可以在另一个脚本中使用 doctest.DocTestSuite() 来收集并执行这些测试用例。以下是一个示例代码:
# test_math_functions.py
import doctest
import math_functions
if __name__ == "__main__":
suite = doctest.DocTestSuite(math_functions)
runner = doctest.DocTestRunner()
runner.run(suite)
在上述代码中,首先导入了 doctest 和 math_functions 模块。然后,通过 doctest.DocTestSuite() 函数收集 math_functions 模块中的测试用例,并将其返回一个 TestSuite 对象。接着,创建一个 DocTestRunner 对象 runner,并使用 runner.run(suite) 运行测试案例。
最后,我们可以通过运行 "python test_math_functions.py" 来执行测试,输出结果如下:
**********************************************************************
File "math_functions.py", line 7, in math_functions.add
Failed example:
add(2, 3)
Expected:
5
Got:
6
**********************************************************************
File "math_functions.py", line 9, in math_functions.add
Failed example:
add(10, -5)
Expected:
5
Got:
5
**********************************************************************
1 items had failures:
2 of 2 in math_functions.add
***Test Failed*** 2 failures.
从输出结果可以看出,其中一个测试用例没有通过。根据输出结果中的提示信息,我们可以看到具体的失败位置和失败的原因,并及时修复代码。
总结来说,使用 doctest.DocTestSuite() 来执行测试案例的步骤如下:
1. 在被测试的模块中编写 doctest 测试用例,并确保每个测试用例以 ">>>" 开始。
2. 在测试脚本中导入 doctest 和被测试的模块。
3. 使用 doctest.DocTestSuite() 函数收集测试用例,并将其返回一个 TestSuite 对象。
4. 创建一个 DocTestRunner 对象,并使用 runner.run(suite) 运行测试案例。
这样,通过编写 doctest 测试用例并使用 doctest.DocTestSuite() 执行测试案例,可以提高代码的可读性和可维护性,并确保被测试的模块的正确性。
