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

pythonserver side programmingprogramming更新于 2025/6/25 11:24:17

我们知道 docstring 提供了有关 Python 中的函数和类的额外信息。我们还可以使用 doctest 模块使用它来测试函数。doctest 模块执行以 >>> 开头的代码并将其与预期输出进行比较。

按照以下步骤使用 doctest 编写函数。

  • 导入 doctest 模块。

  • 使用 docstring 编写函数。在文档字符串中,编写以下两行代码,用于测试同一个函数。

    • >>>function_name(*args).

    • 预期输出。

  • 编写函数代码。

  • 现在,调用 doctest.testmod(name=function_name, verbose=True) 函数进行测试。如果将 verbose 设置为 False,并且所有测试都通过,则看不到测试结果。最好将其设置为 True。

示例

让我们用 doctest 编写一个简单的函数。

# 导入模块
import doctest
# 函数
def numbers_sum(*args) -> int:
   """
   This function returns the sum of all the argumets
   Shell commands for testing
   incoking the function followed by expected output:
   >>> numbers_sum(1, 2, 3, 4, 5)
   15
   >>> numbers_sum(6, 7, 8)
   21
   """
   return sum(args)
# invoking the testmod function
doctest.testmod(name='numbers_sum', verbose=True)

如果您运行上述代码,您将获得以下结果。

Trying:
numbers_sum(1, 2, 3, 4, 5)
Expecting:
15
ok
Trying:
numbers_sum(6, 7, 8)
Expecting:
21
ok
1 items had no tests:
numbers_sum
1 items passed all tests:
2 tests in numbers_sum.numbers_sum
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
TestResults(failed=0, attempted=2)

如果您看到输出,则每个测试后都会出现 ok 字样。这意味着预期输出和实际输出匹配。您可以在输出末尾检查测试结果。

示例

让我们看看测试失败时会发生什么。使用错误的输出运行相同的示例。

# 导入模块
import doctest
# 函数
def numbers_sum(*args) -> int:
   """
   This function returns the sum of all the argumets
   Shell commands for testing
   incoking the function followed by expected output:
   >>> numbers_sum(1, 2, 3, 4, 5)
   10
   >>> numbers_sum(6, 7, 8) 23
   """ return sum(args)
# 调用 testmod 函数
doctest.testmod(name='numbers_sum', verbose=True)

输出

如果执行上述程序,您将得到以下结果。

Trying:
   numbers_sum(1, 2, 3, 4, 5)
Expecting:
   10
**********************************************************************
File "__main__", line 10, in numbers_sum.numbers_sum
Failed example:
   numbers_sum(1, 2, 3, 4, 5)
Expected:
   10
Got:
   15
Trying:
   numbers_sum(6, 7, 8)
Expecting:
   23
**********************************************************************
File "__main__", line 12, in numbers_sum.numbers_sum
Failed example:
   numbers_sum(6, 7, 8)
Expected:
   23
Got:
   21
1 items had no tests:
   numbers_sum
**********************************************************************
1 items had failures:
   2 of 2 in numbers_sum.numbers_sum
2 tests in 2 items.
0 passed and 2 failed.
***Test Failed*** 2 failures.
TestResults(failed=2, attempted=2)

如果您看到测试结果,则有 2 个失败。您还可以在输出中检查预期和实际输出。

结论

如果您对本教程有任何疑问,请在评论部分中提及。


相关文章


有用资源