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

我们知道docstring提供了有关Python中函数和类的更多信息。我们也可以使用doctest模块将其用于功能测试。的文档测试模块执行与>>>开始,并确定它的预期的输出的代码。

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

  • 导入doctest模块。

  • 用docstring编写函数。在文档字符串中,编写以下两行以测试同一功能。

    • >>> function_name(* args)。

    • 预期的输出。

  • 编写功能代码。

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

示例

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

# importing the module
import doctest
# function
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。这意味着预期输出和实际输出是匹配的。您可以在输出末尾检查测试结果。

示例

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

# importing the module
import doctest
# function
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)
# invoking the testmod function
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失败。您还可以在输出中检查预期实际输出。

结论

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