unittestUnit testing framework单元测试框架

Source code: Lib/unittest/__init__.py


(If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.)(如果您已经熟悉测试的基本概念,则可能需要跳到断言方法列表。)

The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. unittest单元测试框架最初受到JUnit的启发,与其他语言中的主要单元测试框架有着相似的风格。It supports test automation, sharing of setup and shutdown code for tests, aggregation of tests into collections, and independence of the tests from the reporting framework.它支持测试自动化,共享测试的设置和关闭代码,将测试聚合到集合中,以及测试与报告框架的独立性。

To achieve this, unittest supports some important concepts in an object-oriented way:为了实现这一点,unittest以面向对象的方式支持一些重要概念:

test fixture测试夹具

A test fixture represents the preparation needed to perform one or more tests, and any associated cleanup actions. 测试夹具表示执行一个或多个测试所需的准备工作,以及任何相关的清理操作。This may involve, for example, creating temporary or proxy databases, directories, or starting a server process.例如,这可能涉及创建临时或代理数据库、目录,或启动服务器进程。

test case测试用例

A test case is the individual unit of testing. 测试用例是单独的测试单元。It checks for a specific response to a particular set of inputs. 它检查对一组特定输入的特定响应。unittest provides a base class, TestCase, which may be used to create new test cases.提供了一个基类TestCase,该基类可用于创建新的测试用例。

test suite测试套件

A test suite is a collection of test cases, test suites, or both. It is used to aggregate tests that should be executed together.测试套件是测试用例、测试套件或两者的集合。它用于聚合应该一起执行的测试。

test runner试车员

A test runner is a component which orchestrates the execution of tests and provides the outcome to the user. 测试运行程序是一个组件,它协调测试的执行并向用户提供结果。The runner may use a graphical interface, a textual interface, or return a special value to indicate the results of executing the tests.跑步者可以使用图形界面、文本界面或返回特殊值来指示执行测试的结果。

See also

Module doctest

Another test-support module with a very different flavor.另一个测试支持模块具有非常不同的风格。

Simple Smalltalk Testing: With Patterns简单的Smalltalk测试:使用模式

Kent Beck’s original paper on testing frameworks using the pattern shared by unittest.Kent-Beck关于使用unittest共享的模式测试框架的原始论文。

pytest

Third-party unittest framework with a lighter-weight syntax for writing tests. 第三方单元测试框架,具有用于编写测试的轻量级语法。For example, assert func(10) == 42.例如,assert func(10) == 42

The Python Testing Tools TaxonomyPython测试工具分类

An extensive list of Python testing tools including functional testing frameworks and mock object libraries.Python测试工具的广泛列表,包括功能测试框架和模拟对象库。

Testing in Python Mailing ListPython邮件列表中的测试

A special-interest-group for discussion of testing, and testing tools, in Python.一个专门讨论Python中的测试和测试工具的兴趣小组。

The script Tools/unittestgui/unittestgui.py in the Python source distribution is a GUI tool for test discovery and execution. Python源代码发行版中的脚本Tools/unittestgui/unittestgui.py是用于测试发现和执行的GUI工具。This is intended largely for ease of use for those new to unit testing. 这在很大程度上是为了让那些新加入单元测试的人易于使用。For production environments it is recommended that tests be driven by a continuous integration system such as Buildbot, Jenkins or Travis-CI, or AppVeyor.对于生产环境,建议由连续集成系统驱动测试,如BuildbotJenkinsTravis-CIAppVeyor

Basic example基本示例

The unittest module provides a rich set of tools for constructing and running tests. This section demonstrates that a small subset of the tools suffice to meet the needs of most users.unittest模块为构建和运行测试提供了一组丰富的工具。本节演示了一小部分工具足以满足大多数用户的需求。

Here is a short script to test three string methods:下面是一个测试三种字符串方法的简短脚本:

import unittest
class TestStringMethods(unittest.TestCase):

def test_upper(self):
self.assertEqual('foo'.upper(), 'FOO')

def test_isupper(self):
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())

def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)

if __name__ == '__main__':
unittest.main()

A testcase is created by subclassing unittest.TestCase. 测试用例是通过对unittest.TestCase进行子类化来创建的。The three individual tests are defined with methods whose names start with the letters test. This naming convention informs the test runner about which methods represent tests.这三个单独的测试是用名称以字母test开头的方法定义的。此命名约定通知测试运行程序哪些方法表示测试。

The crux of each test is a call to assertEqual() to check for an expected result; assertTrue() or assertFalse() to verify a condition; or assertRaises() to verify that a specific exception gets raised. 每个测试的关键是调用assertEqual()来检查预期结果;assertTrue()assertFalse()来验证条件;或assertRaises()来验证是否引发了特定的异常。These methods are used instead of the assert statement so the test runner can accumulate all test results and produce a report.使用这些方法代替assert语句,以便测试运行程序可以累积所有测试结果并生成报告。

The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. setUp()tearDown()方法允许您定义将在每个测试方法之前和之后执行的指令。They are covered in more detail in the section Organizing test code.组织测试代码一节中对它们进行了更详细的介绍。

The final block shows a simple way to run the tests. unittest.main() provides a command-line interface to the test script. 最后一个块显示了运行测试的简单方法。unittest.main()为测试脚本提供了一个命令行接口。When run from the command line, the above script produces an output that looks like this:从命令行运行时,上面的脚本会生成如下输出:

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK

Passing the -v option to your test script will instruct unittest.main() to enable a higher level of verbosity, and produce the following output:将-v选项传递到测试脚本将指示unittest.main()启用更高级别的详细度,并产生以下输出:

test_isupper (__main__.TestStringMethods) ... ok
test_split (__main__.TestStringMethods) ... ok
test_upper (__main__.TestStringMethods) ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.001s

OK

The above examples show the most commonly used unittest features which are sufficient to meet many everyday testing needs. 以上示例显示了最常用的unittest功能,这些功能足以满足许多日常测试需求。The remainder of the documentation explores the full feature set from first principles.本文档的其余部分从第一原则探讨了完整的功能集。

Command-Line Interface命令行接口

The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:可以从命令行使用unittest模块来运行模块、类甚至单个测试方法的测试:

python -m unittest test_module1 test_module2
python -m unittest test_module.TestClass
python -m unittest test_module.TestClass.test_method

You can pass in a list with any combination of module names, and fully qualified class or method names.您可以传入一个列表,该列表包含模块名称和完全限定类或方法名称的任意组合。

Test modules can be specified by file path as well:测试模块也可以通过文件路径指定:

python -m unittest tests/test_something.py

This allows you to use the shell filename completion to specify the test module. The file specified must still be importable as a module. 这允许您使用shell文件名完成来指定测试模块。指定的文件必须仍然可以作为模块导入。The path is converted to a module name by removing the ‘.py’ and converting path separators into ‘.’. 通过删除“py”并将路径分隔符转换为“.”,路径将转换为模块名称。If you want to execute a test file that isn’t importable as a module you should execute the file directly instead.如果您想执行一个不可作为模块导入的测试文件,则应直接执行该文件。

You can run tests with more detail (higher verbosity) by passing in the -v flag:您可以通过传递-v标志来运行更详细(更详细)的测试:

python -m unittest -v test_module

When executed without arguments Test Discovery is started:当在没有参数的情况下执行时,将启动测试发现

python -m unittest

For a list of all the command-line options:有关所有命令行选项的列表:

python -m unittest -h

Changed in version 3.2:版本3.2中更改: In earlier versions it was only possible to run individual test methods and not modules or classes.在早期版本中,只能运行单独的测试方法,而不能运行模块或类。

Command-line options命令行选项

unittest supports these command-line options:支持以下命令行选项:

-b,--buffer

The standard output and standard error streams are buffered during the test run. Output during a passing test is discarded. Output is echoed normally on test fail or error and is added to the failure messages.在测试运行期间缓冲标准输出和标准错误流。通过测试期间的输出将被丢弃。输出在测试失败或错误时正常地回显,并添加到失败消息中。

-c,--catch

Control-C during the test run waits for the current test to end and then reports all the results so far. 在测试运行期间,等待当前测试结束,然后报告到目前为止的所有结果。A second Control-C raises the normal KeyboardInterrupt exception.

See Signal Handling for the functions that provide this functionality.有关提供此功能的功能,请参阅信号处理

-f,--failfast

Stop the test run on the first error or failure.出现第一个错误或失败时停止测试运行。

-k

Only run test methods and classes that match the pattern or substring. This option may be used multiple times, in which case all test cases that match any of the given patterns are included.只运行与模式或子字符串匹配的测试方法和类。此选项可以多次使用,在这种情况下,将包括与任何给定模式匹配的所有测试用例。

Patterns that contain a wildcard character (*) are matched against the test name using fnmatch.fnmatchcase(); otherwise simple case-sensitive substring matching is used.使用fnmatch.fnmatchcase()将包含通配符(*)的模式与测试名称进行匹配;否则使用简单的区分大小写的子字符串匹配。

Patterns are matched against the fully qualified test method name as imported by the test loader.模式与测试加载程序导入的完全限定的测试方法名称相匹配。

For example, -k foo matches foo_tests.SomeTest.test_something, bar_tests.SomeTest.test_foo, but not bar_tests.FooTest.test_something.例如,-k foo匹配foo_tests.SomeTest.test_somethingbar_tests.SomeTest.test_foo,但不匹配bar_tests.FooTest.test_something

--locals

Show local variables in tracebacks.在回溯中显示局部变量。

New in version 3.2.版本3.2中新增。The command-line options -b, -c and -f were added.添加了命令行选项-b-c-f

New in version 3.5.版本3.5中新增。The command-line option --locals.命令行选项--locals

New in version 3.7.版本3.7中新增。The command-line option -k.命令行选项-k

The command line can also be used for test discovery, for running all of the tests in a project or just a subset.命令行还可以用于测试发现,用于运行项目中的所有测试或仅运行一个子集。

Test Discovery测试发现

New in version 3.2.版本3.2中新增。

Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages (including namespace packages) importable from the top-level directory of the project (this means that their filenames must be valid identifiers).Unittest支持简单的测试发现。为了与测试发现兼容,所有测试文件都必须是可从项目的顶级目录导入的模块(包括命名空间包)(这意味着它们的文件名必须是有效的标识符)。

Test discovery is implemented in TestLoader.discover(), but can also be used from the command line. The basic command-line usage is:测试发现在TestLoader.discover()中实现,但也可以从命令行使用。基本的命令行用法是:

cd project_directory
python -m unittest discover

Note

As a shortcut, python -m unittest is the equivalent of python -m unittest discover. 作为一种快捷方式,python -m unittest相当于python -m unittest discoverIf you want to pass arguments to test discovery the discover sub-command must be used explicitly.如果要传递参数以测试发现,则必须显式使用discover子命令。

The discover sub-command has the following options:discover子命令具有以下选项:

-v,--verbose

Verbose output详细输出

-s,--start-directory directory

Directory to start discovery (. default)启动发现的目录(默认值为.

-p,--pattern pattern

Pattern to match test files (test*.py default)匹配测试文件的模式(默认值为test*.py

-t,--top-level-directory directory

Top level directory of project (defaults to start directory)项目的顶层目录(默认为启动目录)

The -s, -p, and -t options can be passed in as positional arguments in that order. -s-p-t选项可以按此顺序作为位置参数传入。The following two command lines are equivalent:以下两个命令行是等效的:

python -m unittest discover -s project_directory -p "*_test.py"
python -m unittest discover project_directory "*_test.py"

As well as being a path it is possible to pass a package name, for example myproject.subpackage.test, as the start directory. 除了作为路径之外,还可以传递包名称,例如myproject.subpackage.test,作为启动目录。The package name you supply will then be imported and its location on the filesystem will be used as the start directory.然后将导入您提供的包名称,并将其在文件系统中的位置用作启动目录。

Caution小心

Test discovery loads tests by importing them. Once test discovery has found all the test files from the start directory you specify it turns the paths into package names to import. 测试发现通过导入测试来加载测试。一旦测试发现从您指定的开始目录中找到所有测试文件,它就会将路径转换为要导入的包名称。For example foo/bar/baz.py will be imported as foo.bar.baz.例如,foo/bar/baz.py将作为foo.bar.baz导入。

If you have a package installed globally and attempt test discovery on a different copy of the package then the import could happen from the wrong place. 如果全局安装了一个包,并尝试在该包的另一个副本上进行测试发现,则导入可能发生在错误的位置。If this happens test discovery will warn you and exit.如果发生这种情况,测试发现将警告您并退出。

If you supply the start directory as a package name rather than a path to a directory then discover assumes that whichever location it imports from is the location you intended, so you will not get the warning.如果您将启动目录提供为包名称,而不是目录的路径,则discover会假定它从哪个位置导入都是您想要的位置,因此不会收到警告。

Test modules and packages can customize test loading and discovery by through the load_tests protocol.测试模块和包可以通过load_tests协议自定义测试加载和发现。

Changed in version 3.4:版本3.4中更改: Test discovery supports namespace packages for the start directory. 测试发现支持启动目录的命名空间包Note that you need to specify the top level directory too (e.g. python -m unittest discover -s root/namespace -t root).请注意,您还需要指定顶级目录(例如python -m unittest discover -s root/namespace -t root)。

Organizing test code组织测试代码

The basic building blocks of unit testing are test cases单元测试的基本构建块是测试用例single scenarios that must be set up and checked for correctness. 必须设置并检查其正确性的单个场景。In unittest, test cases are represented by unittest.TestCase instances. unittest中,测试用例由unittest.TestCase实例表示。To make your own test cases you must write subclasses of TestCase or use FunctionTestCase.要制作自己的测试用例,您必须编写TestCase的子类或使用FunctionTestCase

The testing code of a TestCase instance should be entirely self contained, such that it can be run either in isolation or in arbitrary combination with any number of other test cases.TestCase实例的测试代码应该完全是自包含的,这样它就可以单独运行,也可以与任何数量的其他测试用例任意组合运行。

The simplest TestCase subclass will simply implement a test method (i.e. a method whose name starts with test) in order to perform specific testing code:最简单的TestCase子类将简单地实现一个测试方法(即名称以test开头的方法),以执行特定的测试代码:

import unittest
class DefaultWidgetSizeTestCase(unittest.TestCase):
def test_default_widget_size(self):
widget = Widget('The widget')
self.assertEqual(widget.size(), (50, 50))

Note that in order to test something, we use one of the assert*() methods provided by the TestCase base class. 请注意,为了测试某些内容,我们使用TestCase基类提供的assert*()方法之一。If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. 如果测试失败,将引发一个异常并显示一条解释性消息,unittest将把测试用例标识为失败Any other exceptions will be treated as errors.任何其他异常情况都将被视为错误

Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp(), which the testing framework will automatically call for every single test we run:测试可能很多,而且它们的设置可能是重复的。幸运的是,我们可以通过实现一个名为setUp()的方法来考虑设置代码,测试框架将为我们运行的每一个测试自动调用该方法:

import unittest
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget('The widget')

def test_default_widget_size(self):
self.assertEqual(self.widget.size(), (50,50),
'incorrect default size')

def test_widget_resize(self):
self.widget.resize(100,150)
self.assertEqual(self.widget.size(), (100,150),
'wrong size after resize')

Note

The order in which the various tests will be run is determined by sorting the test method names with respect to the built-in ordering for strings.各种测试的运行顺序是通过根据字符串的内置顺序对测试方法名称进行排序来确定的。

If the setUp() method raises an exception while the test is running, the framework will consider the test to have suffered an error, and the test method will not be executed.如果setUp()方法在测试运行时引发异常,则框架将认为测试发生了错误,并且不会执行该测试方法。

Similarly, we can provide a tearDown() method that tidies up after the test method has been run:类似地,我们可以提供一个tearDown()方法,在测试方法运行后进行清理:

import unittest
class WidgetTestCase(unittest.TestCase):
def setUp(self):
self.widget = Widget('The widget')

def tearDown(self):
self.widget.dispose()

If setUp() succeeded, tearDown() will be run whether the test method succeeded or not.如果setUp()成功,那么无论测试方法是否成功,tearDown()都将运行。

Such a working environment for the testing code is called a test fixture. 这种用于测试代码的工作环境称为测试夹具A new TestCase instance is created as a unique test fixture used to execute each individual test method. 一个新的TestCase实例被创建为一个唯一的测试夹具,用于执行每个单独的测试方法。Thus setUp(), tearDown(), and __init__() will be called once per test.因此,每次测试将调用setUp()tearDown()__init__()一次。

It is recommended that you use TestCase implementations to group tests together according to the features they test. 建议您使用TestCase实现根据测试的特性将测试分组在一起。unittest provides a mechanism for this: the test suite, represented by unittest’s TestSuite class. 提供了一种机制:测试套件,由unittestTestSuite类表示。In most cases, calling unittest.main() will do the right thing and collect all the module’s test cases for you and execute them.在大多数情况下,调用unittest.main()将做正确的事情,为您收集所有模块的测试用例并执行它们。

However, should you want to customize the building of your test suite, you can do it yourself:但是,如果您想自定义测试套件的构建,您可以自己完成:

def suite():
suite = unittest.TestSuite()
suite.addTest(WidgetTestCase('test_default_widget_size'))
suite.addTest(WidgetTestCase('test_widget_resize'))
return suite
if __name__ == '__main__':
runner = unittest.TextTestRunner()
runner.run(suite())

You can place the definitions of test cases and test suites in the same modules as the code they are to test (such as widget.py), but there are several advantages to placing the test code in a separate module, such as test_widget.py:您可以将测试用例和测试套件的定义与要测试的代码(如widget.py)放在相同的模块中,但将测试代码放在单独的模块中有几个优点,如test_widget.py

  • The test module can be run standalone from the command line.测试模块可以从命令行独立运行。

  • The test code can more easily be separated from shipped code.测试代码可以更容易地从附带的代码中分离出来。

  • There is less temptation to change test code to fit the code it tests without a good reason.在没有充分理由的情况下,更改测试代码以适应所测试的代码的诱惑较小。

  • Test code should be modified much less frequently than the code it tests.测试代码的修改频率应该比它测试的代码低得多。

  • Tested code can be refactored more easily.经过测试的代码可以更容易地重构。

  • Tests for modules written in C must be in separate modules anyway, so why not be consistent?无论如何,用C编写的模块的测试必须在单独的模块中,所以为什么不保持一致呢?

  • If the testing strategy changes, there is no need to change the source code.如果测试策略发生变化,则无需更改源代码。

Re-using old test code重新使用旧的测试代码

Some users will find that they have existing test code that they would like to run from unittest, without converting every old test function to a TestCase subclass.一些用户会发现,他们有想要从unittest运行的现有测试代码,而不需要将每个旧的测试函数转换为TestCase子类。

For this reason, unittest provides a FunctionTestCase class. This subclass of TestCase can be used to wrap an existing test function. 因此,unittest提供了一个FunctionTestCase类。TestCase的这个子类可以用来包装现有的测试函数。Set-up and tear-down functions can also be provided.还可以提供设置和拆卸功能。

Given the following test function:给定以下测试功能:

def testSomething():
something = makeSomething()
assert something.name is not None
# ...

one can create an equivalent test case instance as follows, with optional set-up and tear-down methods:可以使用可选的设置和拆除方法,创建如下等效的测试用例实例:

testcase = unittest.FunctionTestCase(testSomething,
setUp=makeSomethingDB,
tearDown=deleteSomethingDB)

Note

Even though FunctionTestCase can be used to quickly convert an existing test base over to a unittest-based system, this approach is not recommended. 尽管FunctionTestCase可以用于将现有的测试库快速转换为基于unittest的系统,但不建议使用这种方法。Taking the time to set up proper TestCase subclasses will make future test refactorings infinitely easier.花点时间建立适当的TestCase子类将使未来的测试重构更加容易。

In some cases, the existing tests may have been written using the doctest module. 在某些情况下,现有的测试可能是使用doctest模块编写的。If so, doctest provides a DocTestSuite class that can automatically build unittest.TestSuite instances from the existing doctest-based tests.如果是这样,doctest提供了一个DocTestSuite类,该类可以从现有的基于doctest的测试中自动构建unittest.TestSuite实例。

Skipping tests and expected failures跳过测试和预期的失败

New in version 3.1.版本3.1中新增。

Unittest supports skipping individual test methods and even whole classes of tests. Unittest支持跳过单个测试方法,甚至跳过整个测试类。In addition, it supports marking a test as an “expected failure,” a test that is broken and will fail, but shouldn’t be counted as a failure on a TestResult.此外,它支持将测试标记为“预期失败”,即一个已损坏并将失败的测试,但不应在TestResult上算作失败。

Skipping a test is simply a matter of using the skip() decorator or one of its conditional variants, calling TestCase.skipTest() within a setUp() or test method, or raising SkipTest directly.跳过测试只是使用skip()装饰器或其条件变体之一,在setUp()或测试方法中调用TestCase.skipTest(),或直接引发SkipTest。

Basic skipping looks like this:基本跳过如下所示:

class MyTestCase(unittest.TestCase):
@unittest.skip("demonstrating skipping")
def test_nothing(self):
self.fail("shouldn't happen")

@unittest.skipIf(mylib.__version__ < (1, 3),
"not supported in this library version")
def test_format(self):
# Tests that work for only a certain version of the library.
pass

@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
def test_windows_support(self):
# windows specific testing code
pass

def test_maybe_skipped(self):
if not external_resource_available():
self.skipTest("external resource not available")
# test code that depends on the external resource
pass

This is the output of running the example above in verbose mode:这是在详细模式下运行上述示例的输出:

test_format (__main__.MyTestCase) ... skipped 'not supported in this library version'
test_nothing (__main__.MyTestCase) ... skipped 'demonstrating skipping'
test_maybe_skipped (__main__.MyTestCase) ... skipped 'external resource not available'
test_windows_support (__main__.MyTestCase) ... skipped 'requires Windows'
----------------------------------------------------------------------
Ran 4 tests in 0.005s

OK (skipped=4)

Classes can be skipped just like methods:类可以像方法一样跳过:

@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
def test_not_run(self):
pass

TestCase.setUp() can also skip the test. 也可以跳过测试。This is useful when a resource that needs to be set up is not available.当需要设置的资源不可用时,这很有用。

Expected failures use the expectedFailure() decorator.预期的失败使用expectedFailure()装饰器。

class ExpectedFailureTestCase(unittest.TestCase):
@unittest.expectedFailure
def test_fail(self):
self.assertEqual(1, 0, "broken")

It’s easy to roll your own skipping decorators by making a decorator that calls skip() on the test when it wants it to be skipped. 通过制作一个装饰器,当它希望跳过测试时,在测试上调用skip(),可以很容易地滚动自己的跳过装饰器。This decorator skips the test unless the passed object has a certain attribute:除非传递的对象具有某个属性,否则此装饰器将跳过测试:

def skipUnlessHasattr(obj, attr):
if hasattr(obj, attr):
return lambda func: func
return unittest.skip("{!r} doesn't have {!r}".format(obj, attr))

The following decorators and exception implement test skipping and expected failures:以下装饰器和异常实现了测试跳过和预期的失败:

@unittest.skip(reason)

Unconditionally skip the decorated test. 无条件跳过装饰测试。reason should describe why the test is being skipped.应描述跳过测试的原因。

@unittest.skipIf(condition, reason)

Skip the decorated test if condition is true.如果条件true,则跳过修饰测试。

@unittest.skipUnless(condition, reason)

Skip the decorated test unless condition is true.

@unittest.expectedFailure

Mark the test as an expected failure or error. 将测试标记为预期的失败或错误。If the test fails or errors in the test function itself (rather than in one of the test fixture methods) then it will be considered a success. 如果测试失败或测试功能本身出现错误(而不是测试夹具方法之一),则视为成功。If the test passes, it will be considered a failure.如果测试通过,则视为失败。

exceptionunittest.SkipTest(reason)

This exception is raised to skip a test.引发此异常是为了跳过测试。

Usually you can use TestCase.skipTest() or one of the skipping decorators instead of raising this directly.通常,您可以使用TestCase.skipTest()或其中一个跳过装饰器,而不是直接引发它。

Skipped tests will not have setUp() or tearDown() run around them. Skipped classes will not have setUpClass() or tearDownClass() run. 跳过的测试将不会在它们周围运行setUp()tearDown()。跳过的类将不会运行setUpClass()tearDownClass()Skipped modules will not have setUpModule() or tearDownModule() run.跳过的模块将不会运行setUpModule()tearDownModule()

Distinguishing test iterations using subtests使用子测试区分测试迭代

New in version 3.4.版本3.4中新增。

When there are very small differences among your tests, for instance some parameters, unittest allows you to distinguish them inside the body of a test method using the subTest() context manager.当测试之间存在非常小的差异时,例如某些参数,unittest允许您使用subTest()上下文管理器在测试方法的主体中区分它们。

For example, the following test:例如,以下测试:

class NumbersTest(unittest.TestCase):
def test_even(self):
"""
Test that numbers between 0 and 5 are all even.
"""
for i in range(0, 6):
with self.subTest(i=i):
self.assertEqual(i % 2, 0)

will produce the following output:将产生以下输出:

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=1)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py", line 32, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0
======================================================================
FAIL: test_even (__main__.NumbersTest) (i=3)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py", line 32, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_even (__main__.NumbersTest) (i=5)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py", line 32, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

Without using a subtest, execution would stop after the first failure, and the error would be less easy to diagnose because the value of i wouldn’t be displayed:如果不使用子测试,执行将在第一次失败后停止,并且错误将不太容易诊断,因为不会显示i的值:

======================================================================
FAIL: test_even (__main__.NumbersTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "subtests.py", line 32, in test_even
self.assertEqual(i % 2, 0)
AssertionError: 1 != 0

Classes and functions类和函数

This section describes in depth the API of unittest.本节详细介绍了unittest的API。

Test cases测试用例

classunittest.TestCase(methodName='runTest')

Instances of the TestCase class represent the logical test units in the unittest universe. TestCase类的实例表示unittest领域中的逻辑测试单元。This class is intended to be used as a base class, with specific tests being implemented by concrete subclasses. 该类旨在用作基类,具体的测试由具体的子类实现。This class implements the interface needed by the test runner to allow it to drive the tests, and methods that the test code can use to check for and report various kinds of failure.这个类实现了测试运行程序所需的接口,使其能够驱动测试,以及测试代码可以用来检查和报告各种故障的方法。

Each instance of TestCase will run a single base method: the method named methodName. TestCase的每个实例都将运行一个基方法:名为methodName的方法。In most uses of TestCase, you will neither change the methodName nor reimplement the default runTest() method.在大多数TestCase的使用中,既不会更改methodName,也不会重新实现默认的runTest()方法。

Changed in version 3.2:版本3.2中更改: TestCase can be instantiated successfully without providing a methodName. 可以在不提供methodName的情况下成功实例化TestCaseThis makes it easier to experiment with TestCase from the interactive interpreter.这使得从交互式解释器中对TestCase进行实验变得更容易。

TestCase instances provide three groups of methods: one group used to run the test, another used by the test implementation to check conditions and report failures, and some inquiry methods allowing information about the test itself to be gathered.实例提供了三组方法:一组用于运行测试,另一组用于测试实现检查条件和报告失败,以及一些允许收集有关测试本身信息的查询方法。

Methods in the first group (running the test) are:第一组(运行测试)中的方法为:

setUp()

Method called to prepare the test fixture. 方法来准备测试夹具。This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. 这是在调用测试方法之前立即调用的;除了AssertionErrorSkipTest之外,此方法引发的任何异常都将被视为错误,而不是测试失败。The default implementation does nothing.默认实现不执行任何操作。

tearDown()

Method called immediately after the test method has been called and the result recorded. 在调用测试方法并记录结果后立即调用的方法。This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. 即使测试方法引发异常,也会调用此方法,因此子类中的实现可能需要特别小心检查内部状态。Any exception, other than AssertionError or SkipTest, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). AssertionErrorSkipTest外,此方法引发的任何异常都将被视为额外错误,而不是测试失败(从而增加报告的错误总数)。This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. 无论测试方法的结果如何,只有在setUp()成功的情况下才会调用此方法。The default implementation does nothing.默认实现不执行任何操作。

setUpClass()

A class method called before tests in an individual class are run. 在运行单个类中的测试之前调用的类方法。setUpClass is called with the class as the only argument and must be decorated as a classmethod():调用setUpClass时,类是唯一的参数,并且必须装饰为classmethod()

@classmethod
def setUpClass(cls):
...

See Class and Module Fixtures for more details.有关更多详细信息,请参阅类和模块固定装置

New in version 3.2.版本3.2中新增。

tearDownClass()

A class method called after tests in an individual class have run. 在单个类中的测试运行后调用的类方法。tearDownClass is called with the class as the only argument and must be decorated as a classmethod():tearDownClass是以类作为唯一参数调用的,并且必须装饰为classmethod()

@classmethod
def tearDownClass(cls):
...

See Class and Module Fixtures for more details.有关更多详细信息,请参阅类和模块固定装置

New in version 3.2.版本3.2中新增。

run(result=None)

Run the test, collecting the result into the TestResult object passed as result. 运行测试,将result收集到作为结果传递的TestResult对象中。If result is omitted or None, a temporary result object is created (by calling the defaultTestResult() method) and used.如果省略了resultresultNone,则会创建并使用一个临时结果对象(通过调用defaultTestResult()方法)。The result object is returned to run()’s caller.结果对象返回给run()的调用程序。

The same effect may be had by simply calling the TestCase instance.通过简单地调用TestCase实例也可以获得相同的效果。

Changed in version 3.3:版本3.3中更改: Previous versions of run did not return the result. Neither did calling an instance.以前版本的run未返回结果。也没有调用实例。

skipTest(reason)

Calling this during a test method or setUp() skips the current test. 在测试方法或setUp()期间调用此函数将跳过当前测试。See Skipping tests and expected failures for more information.有关详细信息,请参阅跳过测试和预期失败

New in version 3.1.版本3.1中新增。

subTest(msg=None, **params)

Return a context manager which executes the enclosed code block as a subtest. 返回一个上下文管理器,该管理器将执行所包含的代码块作为子测试。msg and params are optional, arbitrary values which are displayed whenever a subtest fails, allowing you to identify them clearly.msgparams是可选的、任意的值,每当子测试失败时就会显示这些值,使您能够清楚地识别它们。

A test case can contain any number of subtest declarations, and they can be arbitrarily nested.一个测试用例可以包含任意数量的子测试声明,并且它们可以任意嵌套。

See Distinguishing test iterations using subtests for more information.有关详细信息,请参阅使用子测试区分测试迭代

New in version 3.4.版本3.4中新增。

debug()

Run the test without collecting the result. This allows exceptions raised by the test to be propagated to the caller, and can be used to support running tests under a debugger.在不收集结果的情况下运行测试。这允许将测试引发的异常传播到调用方,并可用于支持在调试器下运行测试。

The TestCase class provides several assert methods to check for and report failures. TestCase类提供了几个断言方法来检查和报告失败。The following table lists the most commonly used methods (see the tables below for more assert methods):下表列出了最常用的方法(有关更多断言方法,请参阅下表):

Method方法

Checks that检查

New in中的新内容

assertEqual(a, b)

a == b

assertNotEqual(a, b)

a != b

assertTrue(x)

bool(x) is True

assertFalse(x)

bool(x) is False

assertIs(a, b)

a is b

3.1

assertIsNot(a, b)

a is not b

3.1

assertIsNone(x)

x is None

3.1

assertIsNotNone(x)

x is not None

3.1

assertIn(a, b)

a in b

3.1

assertNotIn(a, b)

a not in b

3.1

assertIsInstance(a, b)

isinstance(a, b)

3.2

assertNotIsInstance(a, b)

not isinstance(a, b)

3.2

All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also longMessage). 所有assert方法都接受一个msg参数,如果指定了该参数,则该参数将用作失败时的错误消息(另请参阅longMessage)。Note that the msg keyword argument can be passed to assertRaises(), assertRaisesRegex(), assertWarns(), assertWarnsRegex() only when they are used as a context manager.请注意,msg关键字参数只能在用作上下文管理器时传递给assertRaises()assertRaisesRegex()assertWarns()assertWarnsRegex()

assertEqual(first, second, msg=None)

Test that first and second are equal. If the values do not compare equal, the test will fail.测试firstsecond是否相等。如果两个值的比较不相等,测试将失败。

In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message (see also the list of type-specific methods).此外,如果firstsecond是完全相同的类型,并且是list、tuple、dict、set、frozenset或str中的一个,或者子类用addTypeEqualityFunc()注册的任何类型,则将调用特定于类型的相等函数,以生成更有用的默认错误消息(另请参阅特定于类型方法的列表)。

Changed in version 3.1:版本3.1中更改: Added the automatic calling of type-specific equality function.增加了自动调用类型特定的相等函数。

Changed in version 3.2:版本3.2中更改: assertMultiLineEqual() added as the default type equality function for comparing strings.添加为用于比较字符串的默认类型相等函数。

assertNotEqual(first, second, msg=None)

Test that first and second are not equal. 测试firstsecond是否相等。If the values do compare equal, the test will fail.如果两个值比较相等,测试将失败。

assertTrue(expr, msg=None)
assertFalse(expr, msg=None)

Test that expr is true (or false).测试expr是否为真(或假)。

Note that this is equivalent to bool(expr) is True and not to expr is True (use assertIs(expr, True) for the latter). 请注意,这相当于bool(expr) is True,而不是expr is True(后者使用assertIs(expr, True))。This method should also be avoided when more specific methods are available (e.g. assertEqual(a, b) instead of assertTrue(a == b)), because they provide a better error message in case of failure.当有更具体的方法可用时(例如assertEqual(a, b)而不是assertTrue(a == b)),也应该避免使用这种方法,因为它们在失败的情况下提供了更好的错误消息。

assertIs(first, second, msg=None)
assertIsNot(first, second, msg=None)

Test that first and second are (or are not) the same object.

New in version 3.1.版本3.1中新增。

assertIsNone(expr, msg=None)
assertIsNotNone(expr, msg=None)

Test that expr is (or is not) None.测试expr是否为None

New in version 3.1.版本3.1中新增。

assertIn(member, container, msg=None)
assertNotIn(member, container, msg=None)

Test that member is (or is not) in container.

New in version 3.1.版本3.1中新增。

assertIsInstance(obj, cls, msg=None)
assertNotIsInstance(obj, cls, msg=None)

Test that obj is (or is not) an instance of cls (which can be a class or a tuple of classes, as supported by isinstance()). To check for the exact type, use assertIs(type(obj), cls).

New in version 3.2.版本3.2中新增。

It is also possible to check the production of exceptions, warnings, and log messages using the following methods:还可以使用以下方法检查异常、警告和日志消息的产生:

Method

Checks that

New in

assertRaises(exc, fun, *args, **kwds)

fun(*args, **kwds) raises exc

assertRaisesRegex(exc, r, fun, *args, **kwds)

fun(*args, **kwds) raises exc and the message matches regex r

3.1

assertWarns(warn, fun, *args, **kwds)

fun(*args, **kwds) raises warn

3.2

assertWarnsRegex(warn, r, fun, *args, **kwds)

fun(*args, **kwds) raises warn and the message matches regex r

3.2

assertLogs(logger, level)

The with block logs on logger with minimum level

3.4

assertNoLogs(logger, level)

The with block does not log on

logger with minimum level

3.10

assertRaises(exception, callable, *args, **kwds)
assertRaises(exception, *, msg=None)

Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. 如果引发异常,则测试通过;如果引发另一个异常,则为错误;如果未引发异常,测试失败。To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception.为了捕获一组异常中的任何一个,可以将包含异常类的元组作为异常传递。

If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:

with self.assertRaises(SomeException):
do_something()

When used as a context manager, assertRaises() accepts the additional keyword argument msg.

The context manager will store the caught exception object in its exception attribute. This can be useful if the intention is to perform additional checks on the exception raised:上下文管理器将捕获的异常对象存储在其异常属性中。如果打算对提出的异常进行额外检查,这可能会很有用:

with self.assertRaises(SomeException) as cm:
do_something()
the_exception = cm.exception
self.assertEqual(the_exception.error_code, 3)

Changed in version 3.1:版本3.1中更改: Added the ability to use assertRaises() as a context manager.添加了使用assertRaises()作为上下文管理器的功能。

Changed in version 3.2:版本3.2中更改: Added the exception attribute.添加了exception属性。

Changed in version 3.3:版本3.3中更改: Added the msg keyword argument when used as a context manager.在用作上下文管理器时添加了msg关键字参数。

assertRaisesRegex(exception, regex, callable, *args, **kwds)
assertRaisesRegex(exception, regex, *, msg=None)

Like assertRaises() but also tests that regex matches on the string representation of the raised exception. 类似于assertRaises(),但也测试regex在引发异常的字符串表示形式上是否匹配。regex may be a regular expression object or a string containing a regular expression suitable for use by re.search(). regex可以是正则表达式对象,也可以是包含适用于re.search()的正则表达式的字符串。Examples:例如:

self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$",
int, 'XYZ')

or:

with self.assertRaisesRegex(ValueError, 'literal'):
int('XYZ')

New in version 3.1.版本3.1中新增。Added under the name assertRaisesRegexp.assertRaisesRegexp的名称添加。

Changed in version 3.2:版本3.2中更改: Renamed to assertRaisesRegex().已重命名为assertRaisesRegex()

Changed in version 3.3:版本3.3中更改: Added the msg keyword argument when used as a context manager.在用作上下文管理器时添加了msg关键字参数。

assertWarns(warning, callable, *args, **kwds)
assertWarns(warning, *, msg=None)

Test that a warning is triggered when callable is called with any positional or keyword arguments that are also passed to assertWarns(). The test passes if warning is triggered and fails if it isn’t. Any exception is an error. 如果触发了警告,则测试通过,如果未触发,则测试失败。任何异常都是错误。To catch any of a group of warnings, a tuple containing the warning classes may be passed as warnings.要捕获一组警告中的任何一个,可以将包含警告类的元组作为警告传递。

If only the warning and possibly the msg arguments are given, return a context manager so that the code under test can be written inline rather than as a function:如果只给出了警告和可能的msg参数,则返回一个上下文管理器,以便测试中的代码可以内联编写,而不是作为函数编写:

with self.assertWarns(SomeWarning):
do_something()

When used as a context manager, assertWarns() accepts the additional keyword argument msg.

The context manager will store the caught warning object in its warning attribute, and the source line which triggered the warnings in the filename and lineno attributes. This can be useful if the intention is to perform additional checks on the warning caught:如果打算对捕捉到的警告进行额外检查,这可能会很有用:

with self.assertWarns(SomeWarning) as cm:
do_something()
self.assertIn('myfile.py', cm.filename)
self.assertEqual(320, cm.lineno)

This method works regardless of the warning filters in place when it is called.无论调用该方法时有何警告筛选器,该方法都能正常工作。

New in version 3.2.版本3.2中新增。

Changed in version 3.3:版本3.3中更改: Added the msg keyword argument when used as a context manager.在用作上下文管理器时添加了msg关键字参数。

assertWarnsRegex(warning, regex, callable, *args, **kwds)
assertWarnsRegex(warning, regex, *, msg=None)

Like assertWarns() but also tests that regex matches on the message of the triggered warning. regex may be a regular expression object or a string containing a regular expression suitable for use by re.search(). Example:

self.assertWarnsRegex(DeprecationWarning,
r'legacy_function\(\) is deprecated',
legacy_function, 'XYZ')

or:

with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
frobnicate('/etc/passwd')

New in version 3.2.版本3.2中新增。

Changed in version 3.3:版本3.3中更改: Added the msg keyword argument when used as a context manager.在用作上下文管理器时添加了msg关键字参数。

assertLogs(logger=None, level=None)

A context manager to test that at least one message is logged on the logger or one of its children, with at least the given level.一个上下文管理器,用于测试至少有一条消息记录在logger或其子级中,至少具有给定level

If given, logger should be a logging.Logger object or a str giving the name of a logger. 如果给定logger,则logger应为logging.Logger对象或提供记录器名称的strThe default is the root logger, which will catch all messages that were not blocked by a non-propagating descendent logger.默认为根记录器,它将捕获未被非传播的派生记录器阻止的所有消息。

If given, level should be either a numeric logging level or its string equivalent (for example either "ERROR" or logging.ERROR). 如果给定levellevel应该是数字日志级别或其等效字符串(例如"ERROR"logging.ERROR)。The default is logging.INFO.默认值为logging.INFO

The test passes if at least one message emitted inside the with block matches the logger and level conditions, otherwise it fails.如果with块内部发出的至少一条消息与loggerlevel条件匹配,则测试通过,否则测试失败。

The object returned by the context manager is a recording helper which keeps tracks of the matching log messages. It has two attributes:上下文管理器返回的对象是一个记录助手,用于跟踪匹配的日志消息。它有两个属性:

records

A list of logging.LogRecord objects of the matching log messages.匹配日志消息的logging.LogRecord对象的列表。

output

A list of str objects with the formatted output of matching messages.str对象的列表,带有匹配消息的格式化输出。

Example:例如:

with self.assertLogs('foo', level='INFO') as cm:
logging.getLogger('foo').info('first message')
logging.getLogger('foo.bar').error('second message')
self.assertEqual(cm.output, ['INFO:foo:first message',
'ERROR:foo.bar:second message'])

New in version 3.4.版本3.4中新增。

assertNoLogs(logger=None, level=None)

A context manager to test that no messages are logged on the logger or one of its children, with at least the given level.上下文管理器,用于测试logger或其子级(至少具有给定level)上是否未记录任何消息。

If given, logger should be a logging.Logger object or a str giving the name of a logger. The default is the root logger, which will catch all messages.默认的是根记录器,它将捕获所有消息。

If given, level should be either a numeric logging level or its string equivalent (for example either "ERROR" or logging.ERROR). The default is logging.INFO.

Unlike assertLogs(), nothing will be returned by the context manager.assertLogs()不同,上下文管理器不会返回任何内容。

New in version 3.10.版本3.10中新增。

There are also other methods used to perform more specific checks, such as:还有其他方法用于执行更具体的检查,例如:

Method

Checks that

New in

assertAlmostEqual(a, b)

round(a-b, 7) == 0

assertNotAlmostEqual(a, b)

round(a-b, 7) != 0

assertGreater(a, b)

a > b

3.1

assertGreaterEqual(a, b)

a >= b

3.1

assertLess(a, b)

a < b

3.1

assertLessEqual(a, b)

a <= b

3.1

assertRegex(s, r)

r.search(s)

3.1

assertNotRegex(s, r)

not r.search(s)

3.2

assertCountEqual(a, b)

a and b have the same elements in the same number, regardless of their order.具有相同数量的相同元素,而不管它们的顺序如何。

3.2

assertAlmostEqual(first, second, places=7, msg=None, delta=None)
assertNotAlmostEqual(first, second, places=7, msg=None, delta=None)

Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. Note that these methods round the values to the given number of decimal places (i.e. like the round() function) and not significant digits.

If delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.

Supplying both delta and places raises a TypeError.

Changed in version 3.2:版本3.2中更改: assertAlmostEqual() automatically considers almost equal objects that compare equal. assertNotAlmostEqual() automatically fails if the objects compare equal. Added the delta keyword argument.

assertGreater(first, second, msg=None)
assertGreaterEqual(first, second, msg=None)
assertLess(first, second, msg=None)
assertLessEqual(first, second, msg=None)

Test that first is respectively >, >=, < or <= than second depending on the method name. If not, the test will fail:

>>> self.assertGreaterEqual(3, 4)
AssertionError: "3" unexpectedly not greater than or equal to "4"

New in version 3.1.版本3.1中新增。

assertRegex(text, regex, msg=None)
assertNotRegex(text, regex, msg=None)

Test that a regex search matches (or does not match) text. In case of failure, the error message will include the pattern and the text (or the pattern and the part of text that unexpectedly matched). regex may be a regular expression object or a string containing a regular expression suitable for use by re.search().

New in version 3.1.版本3.1中新增。Added under the name assertRegexpMatches.

Changed in version 3.2:版本3.2中更改: The method assertRegexpMatches() has been renamed to assertRegex().

New in version 3.2.版本3.2中新增。assertNotRegex().

New in version 3.5.版本3.5中新增。The name assertNotRegexpMatches is a deprecated alias for assertNotRegex().

assertCountEqual(first, second, msg=None)

Test that sequence first contains the same elements as second, regardless of their order. When they don’t, an error message listing the differences between the sequences will be generated.测试序列first包含与序列second相同的元素,而不管它们的顺序如何。如果没有,则会生成一条错误消息,列出序列之间的差异。

Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. 比较firstsecond不会忽略重复的元素。它验证两个序列中的每个元素是否具有相同的计数。Equivalent to: assertEqual(Counter(list(first)), Counter(list(second))) but works with sequences of unhashable objects as well.等效于:assertEqual(Counter(list(first)), Counter(list(second))),但也适用于不可处理对象的序列。

New in version 3.2.版本3.2中新增。

The assertEqual() method dispatches the equality check for objects of the same type to different type-specific methods. assertEqual()方法将同一类型的对象的相等性检查分派给不同类型的特定方法。These methods are already implemented for most of the built-in types, but it’s also possible to register new methods using addTypeEqualityFunc():这些方法已经为大多数内置类型实现,但也可以使用addTypeEqualityFunc()注册新方法:

addTypeEqualityFunc(typeobj, function)

Registers a type-specific method called by assertEqual() to check if two objects of exactly the same typeobj (not subclasses) compare equal. 注册assertEqual()调用的特定于类型的方法,以检查完全相同类型的两个对象typeobj(而不是子类)是否相等。function must take two positional arguments and a third msg=None keyword argument just as assertEqual() does. function必须采用两个位置参数和第三个msg=None关键字参数,就像assertEqual()所做的那样。It must raise self.failureException(msg) when inequality between the first two parameters is detected – possibly providing useful information and explaining the inequalities in details in the error message.当检测到前两个参数之间的不平等时,它必须引发self.failureException(msg),这可能会提供有用的信息,并在错误消息中详细解释不平等。

New in version 3.1.版本3.1中新增。

The list of type-specific methods automatically used by assertEqual() are summarized in the following table. 下表总结了assertEqual()自动使用的特定于类型的方法列表。Note that it’s usually not necessary to invoke these methods directly.请注意,通常不需要直接调用这些方法。

Method

Used to compare用于比较

New in

assertMultiLineEqual(a, b)

strings

3.1

assertSequenceEqual(a, b)

sequences

3.1

assertListEqual(a, b)

lists

3.1

assertTupleEqual(a, b)

tuples

3.1

assertSetEqual(a, b)

sets or frozensets

3.1

assertDictEqual(a, b)

dicts

3.1

assertMultiLineEqual(first, second, msg=None)

Test that the multiline string first is equal to the string second. 测试多行字符串first是否等于字符串secondWhen not equal a diff of the two strings highlighting the differences will be included in the error message. 当不相等时,突出显示差异的两个字符串的diff将包含在错误消息中。This method is used by default when comparing strings with assertEqual().在将字符串与assertEqual()进行比较时,默认使用此方法。

New in version 3.1.版本3.1中新增。

assertSequenceEqual(first, second, msg=None, seq_type=None)

Tests that two sequences are equal. 测试两个序列是否相等。If a seq_type is supplied, both first and second must be instances of seq_type or a failure will be raised. 如果提供了seq_type,则firstsecond都必须是seq_type的实例,否则将引发故障。If the sequences are different an error message is constructed that shows the difference between the two.如果序列不同,则会构建一条错误消息,显示两者之间的差异。

This method is not called directly by assertEqual(), but it’s used to implement assertListEqual() and assertTupleEqual().

New in version 3.1.版本3.1中新增。

assertListEqual(first, second, msg=None)
assertTupleEqual(first, second, msg=None)

Tests that two lists or tuples are equal. 测试两个列表或元组是否相等。If not, an error message is constructed that shows only the differences between the two. An error is also raised if either of the parameters are of the wrong type. 如果没有,则会构造一条错误消息,仅显示两者之间的差异。如果其中任何一个参数的类型错误,也会引发错误。These methods are used by default when comparing lists or tuples with assertEqual().在将列表或元组与assertEqual()进行比较时,默认使用这些方法。

New in version 3.1.版本3.1中新增。

assertSetEqual(first, second, msg=None)

Tests that two sets are equal. If not, an error message is constructed that lists the differences between the sets. 测试两组是否相等。如果没有,则会构建一条错误消息,列出集合之间的差异。This method is used by default when comparing sets or frozensets with assertEqual().

Fails if either of first or second does not have a set.difference() method.

New in version 3.1.版本3.1中新增。

assertDictEqual(first, second, msg=None)

Test that two dictionaries are equal. If not, an error message is constructed that shows the differences in the dictionaries. 测试两本字典是否相等。如果没有,则会构造一条错误消息,显示字典中的差异。This method will be used by default to compare dictionaries in calls to assertEqual().默认情况下,此方法将用于比较调用assertEqual()时的字典。

New in version 3.1.版本3.1中新增。

Finally the TestCase provides the following methods and attributes:

fail(msg=None)

Signals a test failure unconditionally, with msg or None for the error message.无条件地发出测试失败的信号,错误消息为msgNone

failureException

This class attribute gives the exception raised by the test method. 这个类属性给出了测试方法引发的异常。If a test framework needs to use a specialized exception, possibly to carry additional information, it must subclass this exception in order to “play fair” with the framework. 如果一个测试框架需要使用一个专门的异常,可能是为了携带额外的信息,它必须将这个异常子类化,以便与框架“公平竞争”。The initial value of this attribute is AssertionError.此属性的初始值为AssertionError

longMessage

This class attribute determines what happens when a custom failure message is passed as the msg argument to an assertXYY call that fails. 该类属性确定当自定义失败消息作为msg参数传递给失败的assertXYY调用时会发生什么。True is the default value. 是默认值。In this case, the custom message is appended to the end of the standard failure message. 在这种情况下,自定义消息被附加到标准失败消息的末尾。When set to False, the custom message replaces the standard message.当设置为False时,自定义消息将替换标准消息。

The class setting can be overridden in individual test methods by assigning an instance attribute, self.longMessage, to True or False before calling the assert methods.类设置可以在单独的测试方法中重写,方法是在调用assert方法之前将实例属性self.longMessage,分配给TrueFalse

The class setting gets reset before each test call.类设置在每次测试调用之前重置。

New in version 3.1.版本3.1中新增。

maxDiff

This attribute controls the maximum length of diffs output by assert methods that report diffs on failure. 此属性控制通过在失败时报告diff的assert方法输出的diff的最大长度。It defaults to 80*8 characters. 默认为80*8个字符。Assert methods affected by this attribute are assertSequenceEqual() (including all the sequence comparison methods that delegate to it), assertDictEqual() and assertMultiLineEqual().受此属性影响的断言方法有assertSequenceEqual()(包括委托给它的所有序列比较方法)、assertDictEqual()(和assertMultiLineEqual())。

Setting maxDiff to None means that there is no maximum length of diffs.maxDiff设置为None意味着没有diff的最大长度。

New in version 3.2.版本3.2中新增。

Testing frameworks can use the following methods to collect information on the test:测试框架可以使用以下方法来收集有关测试的信息:

countTestCases()

Return the number of tests represented by this test object. 返回此测试对象表示的测试数。For TestCase instances, this will always be 1.对于TestCase实例,它将始终为1

defaultTestResult()

Return an instance of the test result class that should be used for this test case class (if no other result instance is provided to the run() method).返回应该用于此测试用例类的测试结果类的实例(如果没有向run()方法提供其他结果实例)。

For TestCase instances, this will always be an instance of TestResult; subclasses of TestCase should override this as necessary.对于TestCase实例,这将始终是TestResult的一个实例;TestCase的子类应该根据需要覆盖它。

id()

Return a string identifying the specific test case. This is usually the full name of the test method, including the module and class name.返回一个标识特定测试用例的字符串。这通常是测试方法的全名,包括模块和类名。

shortDescription()

Returns a description of the test, or None if no description has been provided. The default implementation of this method returns the first line of the test method’s docstring, if available, or None.返回测试的说明,如果未提供说明,则返回None。此方法的默认实现返回测试方法的docstring的第一行(如果可用)或None

Changed in version 3.1:版本3.1中更改: In 3.1 this was changed to add the test name to the short description even in the presence of a docstring. 在3.1中,即使有文档字符串,也将其更改为将测试名称添加到简短描述中。This caused compatibility issues with unittest extensions and adding the test name was moved to the TextTestResult in Python 3.2.这导致了unittest扩展的兼容性问题,并将添加的测试名称移动到Python 3.2中的TextTestResult中。

addCleanup(function, /, *args, **kwargs)

Add a function to be called after tearDown() to cleanup resources used during the test. 添加一个要在tearDown()之后调用的函数,以清理测试期间使用的资源。Functions will be called in reverse order to the order they are added (LIFO). 函数的调用顺序与添加顺序相反(LIFO)。They are called with any arguments and keyword arguments passed into addCleanup() when they are added.添加它们时,会使用传递到addCleanup()的任何参数和关键字参数来调用它们。

If setUp() fails, meaning that tearDown() is not called, then any cleanup functions added will still be called.如果setUp()失败,意味着tearDown()没有被调用,那么添加的任何清理函数仍将被调用。

New in version 3.1.版本3.1中新增。

doCleanups()

This method is called unconditionally after tearDown(), or after setUp() if setUp() raises an exception.

It is responsible for calling all the cleanup functions added by addCleanup(). If you need cleanup functions to be called prior to tearDown() then you can call doCleanups() yourself.

doCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time.从清理函数堆栈中一次弹出一个方法,因此可以随时调用它。

New in version 3.1.版本3.1中新增。

classmethodaddClassCleanup(function, /, *args, **kwargs)

Add a function to be called after tearDownClass() to cleanup resources used during the test class. Functions will be called in reverse order to the order they are added (LIFO). They are called with any arguments and keyword arguments passed into addClassCleanup() when they are added.

If setUpClass() fails, meaning that tearDownClass() is not called, then any cleanup functions added will still be called.如果setUpClass()失败,意味着tearDownClass()没有被调用,那么添加的任何清理函数仍将被调用。

New in version 3.8.版本3.8中新增。

classmethoddoClassCleanups()

This method is called unconditionally after tearDownClass(), or after setUpClass() if setUpClass() raises an exception.

It is responsible for calling all the cleanup functions added by addClassCleanup(). If you need cleanup functions to be called prior to tearDownClass() then you can call doClassCleanups() yourself.

doClassCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time.从清理函数堆栈中一次弹出一个方法,因此可以随时调用它。

New in version 3.8.版本3.8中新增。

classunittest.IsolatedAsyncioTestCase(methodName='runTest')

This class provides an API similar to TestCase and also accepts coroutines as test functions.这个类提供了一个类似于TestCase的API,并且还接受协程作为测试函数。

New in version 3.8.版本3.8中新增。

coroutineasyncSetUp()

Method called to prepare the test fixture. 方法来准备测试夹具。This is called after setUp(). 这是在setUp()之后调用的。This is called immediately before calling the test method; other than AssertionError or SkipTest, any exception raised by this method will be considered an error rather than a test failure. 这是在调用测试方法之前立即调用的;除了AssertionErrorSkipTest之外,此方法引发的任何异常都将被视为错误,而不是测试失败。The default implementation does nothing.默认实现不执行任何操作。

coroutineasyncTearDown()

Method called immediately after the test method has been called and the result recorded. 在调用测试方法并记录结果后立即调用的方法。This is called before tearDown(). 这是在tearDown()之前调用的。This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. 即使测试方法引发异常,也会调用此方法,因此子类中的实现可能需要特别小心检查内部状态。Any exception, other than AssertionError or SkipTest, raised by this method will be considered an additional error rather than a test failure (thus increasing the total number of reported errors). AssertionErrorSkipTest外,此方法引发的任何异常都将被视为额外错误,而不是测试失败(从而增加报告的错误总数)。This method will only be called if the asyncSetUp() succeeds, regardless of the outcome of the test method. 只有当asyncSetUp()成功时,才会调用此方法,而不管测试方法的结果如何。The default implementation does nothing.默认实现不执行任何操作。

addAsyncCleanup(function, /, *args, **kwargs)

This method accepts a coroutine that can be used as a cleanup function.此方法接受一个可以用作清理函数的协程。

run(result=None)

Sets up a new event loop to run the test, collecting the result into the TestResult object passed as result. 设置一个新的事件循环来运行测试,将结果收集到作为结果传递的TestResult对象中。If result is omitted or None, a temporary result object is created (by calling the defaultTestResult() method) and used. 如果省略了resultNone,则会创建并使用一个临时结果对象(通过调用defaultTestResult()方法)。The result object is returned to run()’s caller. 结果对象返回给run()的调用程序。At the end of the test all the tasks in the event loop are cancelled.在测试结束时,事件循环中的所有任务都将被取消。

An example illustrating the order:举例说明顺序:

from unittest import IsolatedAsyncioTestCase
events = []


class Test(IsolatedAsyncioTestCase):


def setUp(self):
events.append("setUp")

async def asyncSetUp(self):
self._async_connection = await AsyncConnection()
events.append("asyncSetUp")

async def test_response(self):
events.append("test_response")
response = await self._async_connection.get("https://example.com")
self.assertEqual(response.status_code, 200)
self.addAsyncCleanup(self.on_cleanup)

def tearDown(self):
events.append("tearDown")

async def asyncTearDown(self):
await self._async_connection.close()
events.append("asyncTearDown")

async def on_cleanup(self):
events.append("cleanup")

if __name__ == "__main__":
unittest.main()

After running the test, events would contain ["setUp", "asyncSetUp", "test_response", "asyncTearDown", "tearDown", "cleanup"].

classunittest.FunctionTestCase(testFunc, setUp=None, tearDown=None, description=None)

This class implements the portion of the TestCase interface which allows the test runner to drive the test, but does not provide the methods which test code can use to check and report errors. This is used to create test cases using legacy test code, allowing it to be integrated into a unittest-based test framework.

Deprecated aliases不推荐的别名

For historical reasons, some of the TestCase methods had one or more aliases that are now deprecated. The following table lists the correct names along with their deprecated aliases:由于历史原因,一些TestCase方法有一个或多个别名,这些别名现在已被弃用。下表列出了正确的名称及其不推荐使用的别名:

Method Name方法名称

Deprecated alias不推荐的别名

Deprecated alias不推荐的别名

assertEqual()

failUnlessEqual

assertEquals

assertNotEqual()

failIfEqual

assertNotEquals

assertTrue()

failUnless

assert_

assertFalse()

failIf

assertRaises()

failUnlessRaises

assertAlmostEqual()

failUnlessAlmostEqual

assertAlmostEquals

assertNotAlmostEqual()

failIfAlmostEqual

assertNotAlmostEquals

assertRegex()

assertRegexpMatches

assertNotRegex()

assertNotRegexpMatches

assertRaisesRegex()

assertRaisesRegexp

Deprecated since version 3.1: The fail* aliases listed in the second column have been deprecated.第二列中列出的fail*别名已被弃用。

Deprecated since version 3.2: The assert* aliases listed in the third column have been deprecated.第三列中列出的assert*别名已被弃用。

Deprecated since version 3.2: assertRegexpMatches and assertRaisesRegexp have been renamed to assertRegex() and assertRaisesRegex().

Deprecated since version 3.5: The assertNotRegexpMatches name is deprecated in favor of assertNotRegex().

Grouping tests分组测试

classunittest.TestSuite(tests=())

This class represents an aggregation of individual test cases and test suites. 这个类表示单个测试用例和测试套件的集合。The class presents the interface needed by the test runner to allow it to be run as any other test case. 该类提供测试运行程序所需的接口,以允许它作为任何其他测试用例运行。Running a TestSuite instance is the same as iterating over the suite, running each test individually.运行一个TestSuite实例与在套件上迭代相同,分别运行每个测试。

If tests is given, it must be an iterable of individual test cases or other test suites that will be used to build the suite initially. Additional methods are provided to add test cases and suites to the collection later on.如果给定了tests,那么它必须是单个测试用例或其他测试套件的可迭代的,这些测试套件将用于最初构建套件。提供了其他方法,以便稍后将测试用例和套件添加到集合中。

TestSuite objects behave much like TestCase objects, except they do not actually implement a test. TestSuite对象的行为与TestCase对象非常相似,只是它们实际上并没有实现测试。Instead, they are used to aggregate tests into groups of tests that should be run together. 相反,它们用于将测试聚合为应该一起运行的测试组。Some additional methods are available to add tests to TestSuite instances:一些其他方法可用于将测试添加到TestSuite实例:

addTest(test)

Add a TestCase or TestSuite to the suite.TestCaseTestSuite添加到套件中。

addTests(tests)

Add all the tests from an iterable of TestCase and TestSuite instances to this test suite.将可迭代的TestCaseTestSuite实例中的所有测试添加到此测试套件中。

This is equivalent to iterating over tests, calling addTest() for each element.这相当于对tests进行迭代,为每个元素调用addTest()

TestSuite shares the following methods with TestCase:TestSuiteTestCase共享以下方法:

run(result)

Run the tests associated with this suite, collecting the result into the test result object passed as result. 运行与此套件关联的测试,将结果收集到作为result传递的测试结果对象中。Note that unlike TestCase.run(), TestSuite.run() requires the result object to be passed in.请注意,与TestCase.run()不同,TestSuite.run()要求传入结果对象。

debug()

Run the tests associated with this suite without collecting the result. 运行与此套件关联的测试,而不收集结果。This allows exceptions raised by the test to be propagated to the caller and can be used to support running tests under a debugger.这允许将测试引发的异常传播到调用方,并可用于支持在调试器下运行测试。

countTestCases()

Return the number of tests represented by this test object, including all individual tests and sub-suites.返回此测试对象表示的测试数,包括所有单独的测试和子套件。

__iter__()

Tests grouped by a TestSuite are always accessed by iteration. Subclasses can lazily provide tests by overriding __iter__(). Note that this method may be called several times on a single suite (for example when counting tests or comparing for equality) so the tests returned by repeated iterations before TestSuite.run() must be the same for each call iteration. After TestSuite.run(), callers should not rely on the tests returned by this method unless the caller uses a subclass that overrides TestSuite._removeTestAtIndex() to preserve test references.

Changed in version 3.2:版本3.2中更改: In earlier versions the TestSuite accessed tests directly rather than through iteration, so overriding __iter__() wasn’t sufficient for providing tests.

Changed in version 3.4:版本3.4中更改: In earlier versions the TestSuite held references to each TestCase after TestSuite.run(). Subclasses can restore that behavior by overriding TestSuite._removeTestAtIndex().

In the typical usage of a TestSuite object, the run() method is invoked by a TestRunner rather than by the end-user test harness.

Loading and running tests加载和运行测试

classunittest.TestLoader

The TestLoader class is used to create test suites from classes and modules. TestLoader类用于从类和模块创建测试套件。Normally, there is no need to create an instance of this class; the unittest module provides an instance that can be shared as unittest.defaultTestLoader. 通常,不需要创建此类的实例;unittest模块提供了一个可以作为unittest.defaultTestLoader共享的实例。Using a subclass or instance, however, allows customization of some configurable properties.然而,使用子类或实例可以自定义一些可配置的属性。

TestLoader objects have the following attributes:对象具有以下属性:

errors

A list of the non-fatal errors encountered while loading tests. 加载测试时遇到的非致命错误的列表。Not reset by the loader at any point. Fatal errors are signalled by the relevant a method raising an exception to the caller. Non-fatal errors are also indicated by a synthetic test that will raise the original error when run.装载机在任何时候都不会重置。致命错误由相关的a方法发出信号,向调用方引发异常。非致命错误也由合成测试指示,该测试将在运行时引发原始错误。

New in version 3.5.版本3.5中新增。

TestLoader objects have the following methods:对象具有以下方法:

loadTestsFromTestCase(testCaseClass)

Return a suite of all test cases contained in the TestCase-derived testCaseClass.

A test case instance is created for each method named by getTestCaseNames(). getTestCaseNames()命名的每个方法创建一个测试用例实例。By default these are the method names beginning with test. 默认情况下,这些是以test开头的方法名称。If getTestCaseNames() returns no methods, but the runTest() method is implemented, a single test case is created for that method instead.如果getTestCaseNames()没有返回任何方法,但实现了runTest()方法,则会为该方法创建一个测试用例。

loadTestsFromModule(module, pattern=None)

Return a suite of all test cases contained in the given module. 返回给定模块中包含的所有测试用例的套件。This method searches module for classes derived from TestCase and creates an instance of the class for each test method defined for the class.此方法在模块中搜索从TestCase派生的类,并为为该类定义的每个测试方法创建该类的实例。

Note

While using a hierarchy of TestCase-derived classes can be convenient in sharing fixtures and helper functions, defining test methods on base classes that are not intended to be instantiated directly does not play well with this method. 虽然使用TestCase派生类的层次结构可以方便地共享fixture和helper函数,但在不打算直接实例化的基类上定义测试方法并不能很好地使用此方法。Doing so, however, can be useful when the fixtures are different and defined in subclasses.然而,当固定装置不同并且在子类中定义时,这样做可能很有用。

If a module provides a load_tests function it will be called to load the tests. 如果一个模块提供了load_tests函数,它将被调用来加载测试。This allows modules to customize test loading. 这允许模块自定义测试加载。This is the load_tests protocol. The pattern argument is passed as the third argument to load_tests.这是load_tests协议pattern参数作为第三个参数传递给load_tests

Changed in version 3.2:版本3.2中更改: Support for load_tests added.添加了对load_tests的支持。

Changed in version 3.5:版本3.5中更改: The undocumented and unofficial use_load_tests default argument is deprecated and ignored, although it is still accepted for backward compatibility. 未记录和非官方的use_load_tests默认参数被弃用并被忽略,尽管它仍然被接受用于向后兼容性。The method also now accepts a keyword-only argument pattern which is passed to load_tests as the third argument.该方法现在还接受一个仅关键字的参数模式,该pattern作为第三个参数传递给load_tests

loadTestsFromName(name, module=None)

Return a suite of all test cases given a string specifier.返回一组给定字符串说明符的所有测试用例。

The specifier name is a “dotted name” that may resolve either to a module, a test case class, a test method within a test case class, a TestSuite instance, or a callable object which returns a TestCase or TestSuite instance. These checks are applied in the order listed here; that is, a method on a possible test case class will be picked up as “a test method within a test case class”, rather than “a callable object”.这些检查按此处列出的顺序进行;也就是说,一个可能的测试用例类上的方法将被提取为“测试用例类中的测试方法”,而不是“可调用对象”。

For example, if you have a module SampleTests containing a TestCase-derived class SampleTestCase with three test methods (test_one(), test_two(), and test_three()), the specifier 'SampleTests.SampleTestCase' would cause this method to return a suite which will run all three test methods. Using the specifier 'SampleTests.SampleTestCase.test_two' would cause it to return a test suite which will run only the test_two() test method. The specifier can refer to modules and packages which have not been imported; they will be imported as a side-effect.说明符可以引用尚未导入的模块和包;它们将作为副作用导入。

The method optionally resolves name relative to the given module.该方法可选地解析相对于给定modulename

Changed in version 3.5:版本3.5中更改: If an ImportError or AttributeError occurs while traversing name then a synthetic test that raises that error when run will be returned. These errors are included in the errors accumulated by self.errors.这些误差包含在自误差累积的误差中。

loadTestsFromNames(names, module=None)

Similar to loadTestsFromName(), but takes a sequence of names rather than a single name. The return value is a test suite which supports all the tests defined for each name.类似于loadTestsFromName(),但采用一系列名称而不是单个名称。返回值是一个测试套件,它支持为每个名称定义的所有测试。

getTestCaseNames(testCaseClass)

Return a sorted sequence of method names found within testCaseClass; this should be a subclass of TestCase.返回在testCaseClass中找到的方法名称的排序序列;这应该是TestCase的一个子类。

discover(start_dir, pattern='test*.py', top_level_dir=None)

Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object containing them. 通过从指定的开始目录递归到子目录中找到所有测试模块,并返回包含这些模块的TestSuite对象。Only test files that match pattern will be loaded. (Using shell style pattern matching.) 将只加载与pattern匹配的测试文件。(使用shell样式模式匹配。)Only module names that are importable (i.e. are valid Python identifiers) will be loaded.只有可导入的模块名称(即有效的Python标识符)才会被加载。

All test modules must be importable from the top level of the project. If the start directory is not the top level directory then the top level directory must be specified separately.所有测试模块必须可从项目的顶层导入。如果起始目录不是顶级目录,则必须单独指定顶级目录。

If importing a module fails, for example due to a syntax error, then this will be recorded as a single error and discovery will continue. If the import failure is due to SkipTest being raised, it will be recorded as a skip instead of an error.如果导入模块失败,例如由于语法错误,则这将被记录为单个错误,并将继续进行查找。如果导入失败是由于SkipTest被引发,它将被记录为跳过而不是错误。

If a package (a directory containing a file named __init__.py) is found, the package will be checked for a load_tests function. If this exists then it will be called package.load_tests(loader, tests, pattern). Test discovery takes care to ensure that a package is only checked for tests once during an invocation, even if the load_tests function itself calls loader.discover.

If load_tests exists then discovery does not recurse into the package, load_tests is responsible for loading all tests in the package.如果load_tests存在,则发现不会重新出现在包中,load_tests负责加载包中的所有测试。

The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. 故意不将模式存储为loader属性,以便包可以继续自己的发现。top_level_dir is stored so load_tests does not need to pass this argument in to loader.discover().

start_dir can be a dotted module name as well as a directory.可以是带点的模块名称以及目录。

New in version 3.2.版本3.2中新增。

Changed in version 3.4:版本3.4中更改: Modules that raise SkipTest on import are recorded as skips, not errors.在导入时引发SkipTest的模块记录为跳过,而不是错误。

Changed in version 3.4:版本3.4中更改: start_dir can be a namespace packages.

Changed in version 3.4:版本3.4中更改: Paths are sorted before being imported so that execution order is the same even if the underlying file system’s ordering is not dependent on file name.路径在导入之前会进行排序,这样即使基础文件系统的顺序不取决于文件名,执行顺序也会相同。

Changed in version 3.5:版本3.5中更改: Found packages are now checked for load_tests regardless of whether their path matches pattern, because it is impossible for a package name to match the default pattern.

The following attributes of a TestLoader can be configured either by subclassing or assignment on an instance:TestLoader的以下属性可以通过在实例上进行子类化或赋值来配置:

testMethodPrefix

String giving the prefix of method names which will be interpreted as test methods. 提供将被解释为测试方法的方法名称前缀的字符串。The default value is 'test'.默认值为'test'

This affects getTestCaseNames() and all the loadTestsFrom*() methods.

sortTestMethodsUsing

Function to be used to compare method names when sorting them in getTestCaseNames() and all the loadTestsFrom*() methods.

suiteClass

Callable object that constructs a test suite from a list of tests. 从测试列表中构造测试套件的可调用对象。No methods on the resulting object are needed. 不需要对结果对象使用任何方法。The default value is the TestSuite class.默认值是TestSuite类。

This affects all the loadTestsFrom*() methods.这会影响所有loadTestsFrom*()方法。

testNamePatterns

List of Unix shell-style wildcard test name patterns that test methods have to match to be included in test suites (see -v option).测试方法必须匹配的Unix外壳风格通配符测试名称模式的列表才能包含在测试套件中(请参见-v选项)。

If this attribute is not None (the default), all test methods to be included in test suites must match one of the patterns in this list. Note that matches are always performed using fnmatch.fnmatchcase(), so unlike patterns passed to the -v option, simple substring patterns will have to be converted using * wildcards.

This affects all the loadTestsFrom*() methods.这会影响所有loadTestsFrom*()方法。

New in version 3.7.版本3.7中新增。

classunittest.TestResult

This class is used to compile information about which tests have succeeded and which have failed.此类用于编译有关哪些测试成功,哪些测试失败的信息。

A TestResult object stores the results of a set of tests. The TestCase and TestSuite classes ensure that results are properly recorded; test authors do not need to worry about recording the outcome of tests.

Testing frameworks built on top of unittest may want access to the TestResult object generated by running a set of tests for reporting purposes; a TestResult instance is returned by the TestRunner.run() method for this purpose.

TestResult instances have the following attributes that will be of interest when inspecting the results of running a set of tests:在检查运行一组测试的结果时,实例具有以下感兴趣的属性:

errors

A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. 一个列表,包含两个元组的TestCase实例和包含格式化回溯的字符串。Each tuple represents a test which raised an unexpected exception.每个元组表示一个引发意外异常的测试。

failures

A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents a test where a failure was explicitly signalled using the TestCase.assert*() methods.

skipped

A list containing 2-tuples of TestCase instances and strings holding the reason for skipping the test.一个列表,包含2元组的TestCase实例和包含跳过测试原因的字符串。

New in version 3.1.版本3.1中新增。

expectedFailures

A list containing 2-tuples of TestCase instances and strings holding formatted tracebacks. Each tuple represents an expected failure or error of the test case.一个列表,包含两个元组的TestCase实例和包含格式化回溯的字符串。每个元组表示测试用例的预期失败或错误。

unexpectedSuccesses

A list containing TestCase instances that were marked as expected failures, but succeeded.

shouldStop

Set to True when the execution of tests should stop by stop().

testsRun

The total number of tests run so far.到目前为止运行的测试总数。

buffer

If set to true, sys.stdout and sys.stderr will be buffered in between startTest() and stopTest() being called. Collected output will only be echoed onto the real sys.stdout and sys.stderr if the test fails or errors. Any output is also attached to the failure / error message.任何输出也会附加到故障/错误消息。

New in version 3.2.版本3.2中新增。

failfast

If set to true stop() will be called on the first failure or error, halting the test run.如果设置为stop(),将在第一次失败或错误时调用stop(),从而停止测试运行。

New in version 3.2.版本3.2中新增。

tb_locals

If set to true then local variables will be shown in tracebacks.如果设置为true,则局部变量将显示在回溯中。

New in version 3.5.版本3.5中新增。

wasSuccessful()

Return True if all tests run so far have passed, otherwise returns False.如果到目前为止运行的所有测试都已通过,则返回True,否则返回False

Changed in version 3.4:版本3.4中更改: Returns False if there were any unexpectedSuccesses from tests marked with the expectedFailure() decorator.

stop()

This method can be called to signal that the set of tests being run should be aborted by setting the shouldStop attribute to True. TestRunner objects should respect this flag and return without running any additional tests.

For example, this feature is used by the TextTestRunner class to stop the test framework when the user signals an interrupt from the keyboard. Interactive tools which provide TestRunner implementations can use this in a similar manner.

The following methods of the TestResult class are used to maintain the internal data structures, and may be extended in subclasses to support additional reporting requirements. This is particularly useful in building tools which support interactive reporting while tests are being run.

startTest(test)

Called when the test case test is about to be run.在即将运行测试用例test时调用。

stopTest(test)

Called after the test case test has been executed, regardless of the outcome.在执行测试用例test后调用,无论结果如何。

startTestRun()

Called once before any tests are executed.在执行任何测试之前调用一次。

New in version 3.1.版本3.1中新增。

stopTestRun()

Called once after all tests are executed.在执行完所有测试后调用一次。

New in version 3.1.版本3.1中新增。

addError(test, err)

Called when the test case test raises an unexpected exception. 当测试用例测试引发意外异常时调用。err is a tuple of the form returned by sys.exc_info(): (type, value, traceback).

The default implementation appends a tuple (test, formatted_err) to the instance’s errors attribute, where formatted_err is a formatted traceback derived from err.

addFailure(test, err)

Called when the test case test signals a failure. err is a tuple of the form returned by sys.exc_info(): (type, value, traceback).

The default implementation appends a tuple (test, formatted_err) to the instance’s failures attribute, where formatted_err is a formatted traceback derived from err.

addSuccess(test)

Called when the test case test succeeds.

The default implementation does nothing.默认实现不执行任何操作。

addSkip(test, reason)

Called when the test case test is skipped. reason is the reason the test gave for skipping.

The default implementation appends a tuple (test, reason) to the instance’s skipped attribute.

addExpectedFailure(test, err)

Called when the test case test fails or errors, but was marked with the expectedFailure() decorator.

The default implementation appends a tuple (test, formatted_err) to the instance’s expectedFailures attribute, where formatted_err is a formatted traceback derived from err.

addUnexpectedSuccess(test)

Called when the test case test was marked with the expectedFailure() decorator, but succeeded.

The default implementation appends the test to the instance’s unexpectedSuccesses attribute.默认实现将测试附加到实例的unexpectedSuccesses属性。

addSubTest(test, subtest, outcome)

Called when a subtest finishes. test is the test case corresponding to the test method. subtest is a custom TestCase instance describing the subtest.

If outcome is None, the subtest succeeded. Otherwise, it failed with an exception where outcome is a tuple of the form returned by sys.exc_info(): (type, value, traceback).

The default implementation does nothing when the outcome is a success, and records subtest failures as normal failures.当结果为成功时,默认实现不执行任何操作,并将子测试失败记录为正常失败。

New in version 3.4.版本3.4中新增。

classunittest.TextTestResult(stream, descriptions, verbosity)

A concrete implementation of TestResult used by the TextTestRunner.

New in version 3.2.版本3.2中新增。This class was previously named _TextTestResult. 这个类以前被命名为_TextTestResultThe old name still exists as an alias but is deprecated.旧名称仍然作为别名存在,但已被弃用。

unittest.defaultTestLoader

Instance of the TestLoader class intended to be shared. If no customization of the TestLoader is needed, this instance can be used instead of repeatedly creating new instances.

classunittest.TextTestRunner(stream=None, descriptions=True, verbosity=1, failfast=False, buffer=False, resultclass=None, warnings=None, *, tb_locals=False)

A basic test runner implementation that outputs results to a stream. 将结果输出到流的基本测试运行器实现。If stream is None, the default, sys.stderr is used as the output stream. 如果streamNone(默认值),则使用sys.stderr作为输出流。This class has a few configurable parameters, but is essentially very simple. 这个类有一些可配置的参数,但本质上非常简单。Graphical applications which run test suites should provide alternate implementations. 运行测试套件的图形应用程序应该提供替代实现。Such implementations should accept **kwargs as the interface to construct runners changes when features are added to unittest.当特性被添加到单元测试中时,这样的实现应该接受**kwargs作为构造运行程序更改的接口。

By default this runner shows DeprecationWarning, PendingDeprecationWarning, ResourceWarning and ImportWarning even if they are ignored by default. Deprecation warnings caused by deprecated unittest methods are also special-cased and, when the warning filters are 'default' or 'always', they will appear only once per-module, in order to avoid too many warning messages. This behavior can be overridden using Python’s -Wd or -Wa options (see Warning control) and leaving warnings to None.

Changed in version 3.2:版本3.2中更改: Added the warnings argument.添加了warnings参数。

Changed in version 3.2:版本3.2中更改: The default stream is set to sys.stderr at instantiation time rather than import time.默认流在实例化时而不是导入时设置为sys.stderr

Changed in version 3.5:版本3.5中更改: Added the tb_locals parameter.

_makeResult()

This method returns the instance of TestResult used by run(). It is not intended to be called directly, but can be overridden in subclasses to provide a custom TestResult.

_makeResult() instantiates the class or callable passed in the TextTestRunner constructor as the resultclass argument. It defaults to TextTestResult if no resultclass is provided. The result class is instantiated with the following arguments:

stream, descriptions, verbosity
run(test)

This method is the main public interface to the TextTestRunner. 此方法是TextTestRunner的主要公共接口。This method takes a TestSuite or TestCase instance. A TestResult is created by calling _makeResult() and the test(s) are run and the results printed to stdout.

unittest.main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None, warnings=None)

A command-line program that loads a set of tests from module and runs them; this is primarily for making test modules conveniently executable. 一个命令行程序,从module加载一组测试并运行它们;这主要是为了使测试模块能够方便地执行。The simplest use for this function is to include the following line at the end of a test script:此函数最简单的用途是在测试脚本的末尾包含以下行:

if __name__ == '__main__':
unittest.main()

You can run tests with more detailed information by passing in the verbosity argument:您可以通过传入verbose参数来运行包含更详细信息的测试:

if __name__ == '__main__':
unittest.main(verbosity=2)

The defaultTest argument is either the name of a single test or an iterable of test names to run if no test names are specified via argv. If not specified or None and no test names are provided via argv, all tests found in module are run.

The argv argument can be a list of options passed to the program, with the first element being the program name. If not specified or None, the values of sys.argv are used.

The testRunner argument can either be a test runner class or an already created instance of it. By default main calls sys.exit() with an exit code indicating success or failure of the tests run.

The testLoader argument has to be a TestLoader instance, and defaults to defaultTestLoader.

main supports being used from the interactive interpreter by passing in the argument exit=False. This displays the result on standard output without calling sys.exit():

>>> from unittest import main
>>> main(module='test_module', exit=False)

The failfast, catchbreak and buffer parameters have the same effect as the same-name command-line options.

The warnings argument specifies the warning filter that should be used while running the tests. If it’s not specified, it will remain None if a -W option is passed to python (see Warning control), otherwise it will be set to 'default'.

Calling main actually returns an instance of the TestProgram class. This stores the result of the tests run as the result attribute.

Changed in version 3.1:版本3.1中更改: The exit parameter was added.

Changed in version 3.2:版本3.2中更改: The verbosity, failfast, catchbreak, buffer and warnings parameters were added.

Changed in version 3.4:版本3.4中更改: The defaultTest parameter was changed to also accept an iterable of test names.

load_tests Protocol

New in version 3.2.版本3.2中新增。

Modules or packages can customize how tests are loaded from them during normal test runs or test discovery by implementing a function called load_tests.模块或包可以通过实现一个名为load_tests的函数,自定义在正常测试运行或测试发现期间如何从中加载测试。

If a test module defines load_tests it will be called by TestLoader.loadTestsFromModule() with the following arguments:如果测试模块定义了load_tests,它将由TestLoader.loadTestsFromModule()使用以下参数调用:

load_tests(loader, standard_tests, pattern)

where pattern is passed straight through from loadTestsFromModule. It defaults to None.

It should return a TestSuite.

loader is the instance of TestLoader doing the loading. standard_tests are the tests that would be loaded by default from the module. It is common for test modules to only want to add or remove tests from the standard set of tests. The third argument is used when loading packages as part of test discovery.测试模块通常只想在标准测试集中添加或删除测试。第三个参数在作为测试发现的一部分加载包时使用。

A typical load_tests function that loads tests from a specific set of TestCase classes may look like:从一组特定的TestCase类加载测试的典型load_tests函数可能如下所示:

test_cases = (TestCase1, TestCase2, TestCase3)
def load_tests(loader, tests, pattern):
suite = TestSuite()
for test_class in test_cases:
tests = loader.loadTestsFromTestCase(test_class)
suite.addTests(tests)
return suite

If discovery is started in a directory containing a package, either from the command line or by calling TestLoader.discover(), then the package __init__.py will be checked for load_tests. If that function does not exist, discovery will recurse into the package as though it were just another directory.如果该函数不存在,则发现将递归到包中,就好像它只是另一个目录一样。 Otherwise, discovery of the package’s tests will be left up to load_tests which is called with the following arguments:否则,包的测试的发现将留给load_tests,它使用以下参数调用:

load_tests(loader, standard_tests, pattern)

This should return a TestSuite representing all the tests from the package. (standard_tests will only contain tests collected from __init__.py.)

Because the pattern is passed into load_tests the package is free to continue (and potentially modify) test discovery. A ‘do nothing’ load_tests function for a test package would look like:

def load_tests(loader, standard_tests, pattern):
# top level directory cached on loader instance
this_dir = os.path.dirname(__file__)
package_tests = loader.discover(start_dir=this_dir, pattern=pattern)
standard_tests.addTests(package_tests)
return standard_tests

Changed in version 3.5:版本3.5中更改: Discovery no longer checks package names for matching pattern due to the impossibility of package names matching the default pattern.由于包名称不可能与默认pattern匹配,发现不再检查包名称是否匹配模式。

Class and Module Fixtures类和模块固定装置

Class and module level fixtures are implemented in TestSuite. 类和模块级固定装置在TestSuite中实现。When the test suite encounters a test from a new class then tearDownClass() from the previous class (if there is one) is called, followed by setUpClass() from the new class.当测试套件遇到来自新类的测试时,调用上一个类(如果有)的tearDownClass(),然后调用新类的setUpClass()

Similarly if a test is from a different module from the previous test then tearDownModule from the previous module is run, followed by setUpModule from the new module.

After all the tests have run the final tearDownClass and tearDownModule are run.

Note that shared fixtures do not play well with [potential] features like test parallelization and they break test isolation. They should be used with care.请注意,共享固定装置不能很好地发挥测试并行化等潜在功能,它们破坏了测试隔离。它们应该小心使用。

The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. unittest测试加载程序创建的测试的默认顺序是将来自相同模块和类的所有测试分组在一起。This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.如果将顺序随机化,使得来自不同模块和类的测试彼此相邻,那么这些共享的fixture函数可能会在一次测试运行中被多次调用。

Shared fixtures are not intended to work with suites with non-standard ordering. 共享固定装置不适用于具有非标准订购的套件。A BaseTestSuite still exists for frameworks that don’t want to support shared fixtures.对于不想支持共享固定装置的框架,BaseTestSuite仍然存在。

If there are any exceptions raised during one of the shared fixture functions the test is reported as an error. 如果在其中一个共享夹具功能期间出现任何异常,则测试将报告为错误。Because there is no corresponding test instance an _ErrorHolder object (that has the same interface as a TestCase) is created to represent the error. If you are just using the standard unittest test runner then this detail doesn’t matter, but if you are a framework author it may be relevant.如果您只是使用标准的单元测试运行器,那么这个细节并不重要,但如果您是框架作者,那么它可能是相关的。

setUpClass and tearDownClass

These must be implemented as class methods:这些必须作为类方法实现:

import unittest
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls._connection = createExpensiveConnectionObject()

@classmethod
def tearDownClass(cls):
cls._connection.destroy()

If you want the setUpClass and tearDownClass on base classes called then you must call up to them yourself. The implementations in TestCase are empty.

If an exception is raised during a setUpClass then the tests in the class are not run and the tearDownClass is not run. Skipped classes will not have setUpClass or tearDownClass run. If the exception is a SkipTest exception then the class will be reported as having been skipped instead of as an error.如果异常是SkipTest异常,则类将被报告为已跳过,而不是错误。

setUpModule and tearDownModule

These should be implemented as functions:这些功能应实现为:

def setUpModule():
createConnection()
def tearDownModule():
closeConnection()

If an exception is raised in a setUpModule then none of the tests in the module will be run and the tearDownModule will not be run. If the exception is a SkipTest exception then the module will be reported as having been skipped instead of as an error.

To add cleanup code that must be run even in the case of an exception, use addModuleCleanup:要添加即使在异常情况下也必须运行的清理代码,请使用addModuleCleanup

unittest.addModuleCleanup(function, /, *args, **kwargs)

Add a function to be called after tearDownModule() to cleanup resources used during the test class. 添加一个要在tearDownModule()之后调用的函数,以清理测试类期间使用的资源。Functions will be called in reverse order to the order they are added (LIFO). 函数的调用顺序与添加顺序相反(LIFO)。They are called with any arguments and keyword arguments passed into addModuleCleanup() when they are added.在添加它们时,使用传递到addModuleCleanup()的任何参数和关键字参数来调用它们。

If setUpModule() fails, meaning that tearDownModule() is not called, then any cleanup functions added will still be called.如果setUpModule()失败,意味着tearDownModule()没有被调用,那么添加的任何清理函数仍将被调用。

New in version 3.8.版本3.8中新增。

unittest.doModuleCleanups()

This function is called unconditionally after tearDownModule(), or after setUpModule() if setUpModule() raises an exception.此函数在tearDownModule()之后无条件调用,或者在setUpModule()之后(如果setUpModule()引发异常)无条件调用。

It is responsible for calling all the cleanup functions added by addCleanupModule(). 它负责调用addCleanupModule()添加的所有清理函数。If you need cleanup functions to be called prior to tearDownModule() then you can call doModuleCleanups() yourself.如果您需要在tearDownModule()之前调用清理函数,那么您可以自己调用doModuleCleanups()

doModuleCleanups() pops methods off the stack of cleanup functions one at a time, so it can be called at any time.从清理函数堆栈中一次弹出一个方法,因此可以随时调用它。

New in version 3.8.版本3.8中新增。

Signal Handling信号处理

New in version 3.2.版本3.2中新增。

The -c/--catch command-line option to unittest, along with the catchbreak parameter to unittest.main(), provide more friendly handling of control-C during a test run. With catch break behavior enabled control-C will allow the currently running test to complete, and the test run will then end and report all the results so far. A second control-c will raise a KeyboardInterrupt in the usual way.

The control-c handling signal handler attempts to remain compatible with code or tests that install their own signal.SIGINT handler. If the unittest handler is called but isn’t the installed signal.SIGINT handler, i.e. it has been replaced by the system under test and delegated to, then it calls the default handler. This will normally be the expected behavior by code that replaces an installed handler and delegates to it. For individual tests that need unittest control-c handling disabled the removeHandler() decorator can be used.

There are a few utility functions for framework authors to enable control-c handling functionality within test frameworks.对于框架作者来说,有一些实用函数可以在测试框架中启用control-c处理功能。

unittest.installHandler()

Install the control-c handler. When a signal.SIGINT is received (usually in response to the user pressing control-c) all registered results have stop() called.

unittest.registerResult(result)

Register a TestResult object for control-c handling. 注册一个TestResult对象以进行control-c处理。Registering a result stores a weak reference to it, so it doesn’t prevent the result from being garbage collected.注册一个结果会存储对它的弱引用,因此它不会阻止结果被垃圾收集。

Registering a TestResult object has no side-effects if control-c handling is not enabled, so test frameworks can unconditionally register all results they create independently of whether or not handling is enabled.

unittest.removeResult(result)

Remove a registered result. 删除已注册的结果。Once a result has been removed then stop() will no longer be called on that result object in response to a control-c.

unittest.removeHandler(function=None)

When called without arguments this function removes the control-c handler if it has been installed. This function can also be used as a test decorator to temporarily remove the handler while the test is being executed:当在没有参数的情况下调用时,如果已安装control-c处理程序,则此函数将删除该处理程序。此函数还可以用作测试装饰器,以便在执行测试时临时删除处理程序:

@unittest.removeHandler
def test_signal_handling(self):
...