Unittest Framework 简明教程

UnitTest Framework - Doctest API

doctest API 围绕下列两个容器类进行,用于从 docstring 中存储交互示例 −

The doctest API revolves around the following two container classes used to store interactive examples from docstrings −

  1. Example − A single Python statement, paired with its expected output.

  2. DocTest − A collection of Examples, typically extracted from a single docstring or a text file.

定义了以下附加处理类,用于查找、解析并运行以及检查 doctest 示例 −

The following additional processing classes are defined to find, parse, and run, and check doctest examples −

  1. DocTestFinder − Finds all docstrings in a given module, and uses a DocTestParser to create a DocTest from every docstring that contains interactive examples.

  2. DocTestParser − Creates a doctest object from a string (such as an object’s docstring).

  3. DocTestRunner − Executes the examples in a doctest, and uses an OutputChecker to verify their output.

  4. OutputChecker − Compares the actual output from a doctest example with the expected output, and decides whether they match.

DocTestFinder Class

它是一个处理类,用于从 docstring 及其包含对象 docstring 中提取与给定对象相关的 doctest。当前可以从以下对象类型中提取 doctest — 模块、函数、类、方法、静态方法、类方法和属性。

It is a processing class used to extract the doctests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following object types — modules, functions, classes, methods, staticmethods, classmethods, and properties.

此类定义 find() 方法。它返回由对象的 docstring,或其包含对象的任何 docstring 定义的 DocTest 列表。

This class defines the find() method. It returns a list of the DocTests that are defined by the object‘s docstring, or by any of its contained objects’ docstrings.

DocTestParser Class

这是一个处理类,用于从字符串中提取交互示例,并使用它们来创建 DocTest 对象。该类定义了以下方法 -

It is a processing class used to extract interactive examples from a string, and use them to create a DocTest object. This class defines the following methods −

  1. get_doctest() − Extract all doctest examples from the given string, and collect them into a DocTest object.

  2. get_examples(string[, name]) − Extract all doctest examples from the given string, and return them as a list of Example objects. Line numbers are 0-based. The optional argument name is a name identifying this string, and is only used for error messages.

  3. parse(string[, name]) − Divide the given string into examples and intervening text, and return them as a list of alternating Examples and strings. Line numbers for the Examples are 0-based. The optional argument name is a name identifying this string, and is only used for error messages.

DocTestRunner Class

这是一个处理类,用于执行和验证 DocTest 中的交互示例。其中定义了以下方法 -

This is a processing class used to execute and verify the interactive examples in a DocTest. The following methods are defined in it −

report_start()

报告测试运行器即将处理给定示例。此方法是为了允许 DocTestRunner 的子类自定义其输出;不应该直接调用它

Report that the test runner is about to process the given example. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly

report_success()

报告给定的示例运行成功。此方法是为了允许 DocTestRunner 的子类自定义其输出;不应该直接调用它

Report that the given example ran successfully. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

report_failure()

报告给定的示例失败。此方法是为了允许 DocTestRunner 的子类自定义其输出;不应该直接调用它

Report that the given example failed. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

report_unexpected_exception()

报告给定的示例引发了一个意外的异常。此方法是为了允许 DocTestRunner 的子类自定义其输出;不应该直接调用它

Report that the given example raised an unexpected exception. This method is provided to allow subclasses of DocTestRunner to customize their output; it should not be called directly.

run(test)

运行测试中的示例(一个 DocTest 对象),并使用 writer 函数 out 显示结果

Run the examples in test (a DocTest object), and display the results using the writer function out.

summarize([verbose])

打印此 DocTestRunner 运行的所有测试用例的摘要,并返回一个命名的元组 TestResults(failed, attempted)。可选的 verbose 参数控制摘要的详细程度。如果未指定详细程度,则使用 DocTestRunner 的详细程度。

Print a summary of all the test cases that have been run by this DocTestRunner, and return a named tuple TestResults(failed, attempted). The optional verbose argument controls how detailed the summary is. If the verbosity is not specified, then the DocTestRunner‘s verbosity is used.

OutputChecker Class

此类用于检查 doctest 示例的实际输出是否与预期输出匹配。

This class is used to check whether the actual output from a doctest example matches the expected output.

此类中定义了以下方法 -

The following methods are defined in this class −

check_output()

如果示例(got)的实际输出与预期输出(want)匹配,则返回 True 。如果这些字符串相同,则它们始终被认为匹配;但是,根据测试运行器使用的选项标记是什么,也可能使用多种非精确匹配类型。有关选项标记的详细信息,请参阅选项标记和指令部分。

Return True if the actual output from an example (got) matches with the expected output (want). These strings are always considered to match if they are identical; but depending on what option flags the test runner is using, several non-exact match types are also possible. See section Option Flags and Directives for more information about option flags.

output_difference()

返回一个字符串,描述给定示例(example)的预期输出与实际输出(got)之间的差异。

Return a string describing the differences between the expected output for a given example (example) and the actual output (got).

DocTest Integration with Unittest

doctest 模块提供了两个函数,可用于从包含 doctest 的模块和文本文件中创建 unittest 测试套件。若要与 unittest 测试发现集成,请在您的测试模块中包含一个 load_tests() 函数 -

The doctest module provides two functions that can be used to create unittest test suites from modules and text files containing doctests. To integrate with unittest test discovery, include a load_tests() function in your test module −

import unittest
import doctest
import doctestexample

def load_tests(loader, tests, ignore):
   tests.addTests(doctest.DocTestSuite(doctestexample))
   return tests

将形成一个 unittest 和 doctest 的测试的组合 TestSuite,现在可以通过 unittest 模块的 main() 方法或 run() 方法来执行它。

A combined TestSuite of tests from unittest as well as doctest will be formed and it can now be executed by unittest module’s main() method or run() method.

以下是用于从文本文件和包含 doctest 的模块创建 unittest.TestSuite 实例的两个主要函数 -

The following are the two main functions for creating unittest.TestSuite instances from text files and modules with the doctests −

doctest.DocFileSuite()

它用于将一个或多个文本文件中的 doctest 测试转换为 unittest.TestSuite 。返回的 unittest.TestSuite 由 unittest 框架运行,并在每个文件中运行交互式示例。如果文件中任何示例失败,则合成的单元测试也将失败,并且会引发一个 failureException 异常,该异常显示包含测试的文件的名称和(有时是近似值)行号。

It is used to convert doctest tests from one or more text files to a unittest.TestSuite. The returned unittest.TestSuite is to be run by the unittest framework and runs the interactive examples in each file. If any of the examples in a file fails, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number.

doctest.DocTestSuite()

它用于将模块的 doctest 测试转换为 unittest.TestSuite

It is used to convert doctest tests for a module to a unittest.TestSuite.

返回的 unittest.TestSuite 由 unittest 框架运行,并且运行模块中的每个 doctest。如果任何 doctest 失败,则合成的单元测试失败,并且引发 failureException 异常,显示包含测试的文件名称和(有时近似)行号

The returned unittest.TestSuite is to be run by the unittest framework and runs each doctest in the module. If any of the doctests fail, then the synthesized unit test fails, and a failureException exception is raised showing the name of the file containing the test and a (sometimes approximate) line number

DocTestSuite() 在底层创建一个 unittest.TestSuite ,该对象由 doctest.DocTestCase 实例和 DocTestCase(unittest.TestCase 的子类)组成。

Under the covers, DocTestSuite() creates a unittest.TestSuite out of doctest.DocTestCase instances, and DocTestCase is a subclass of unittest.TestCase.

类似地,DocFileSuite() 使用 doctest.DocFileCase 实例创建一个 unittest.TestSuite,而 DocFileCase 是 DocTestCase 的子类。

Similarly, DocFileSuite() creates a unittest.TestSuite out of doctest.DocFileCase instances, and DocFileCase is a subclass of DocTestCase.

因此,两种创建 unittest.TestSuite 的方式都运行 DocTestCase 的实例。通过将选项标志传递给 doctest 函数,当您自己运行 doctest 函数时,您可以直接控制所使用的 doctest 选项。

So both ways of creating a unittest.TestSuite run instances of DocTestCase. When you run doctest functions yourself, you can control the doctest options in use directly, by passing option flags to doctest functions.

但是,如果您正在编写一个 unittest 框架,unittest 最终会控制何时以及如何运行测试。框架作者通常想要控制 doctest 报告选项(例如,由命令行选项指定),但无法通过 unittest 将选项传递给 doctest 测试运行程序。

However, if you’re writing a unittest framework, unittest ultimately controls when and how the tests get run. The framework author typically wants to control doctest reporting options (perhaps, e.g., specified by command line options), but there’s no way to pass options through unittest to doctest test runners.