The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages. 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. unittest单元测试框架源于JUnit的启发,并和其他语言的单元测试风格异曲同工。它支持自动化测试,为测试提供setup和shutdown代码,集合测试用例,并生成独立的测试报告。
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 associate cleanup actions. This may involve, for example, creating temporary or proxy databases, directories, or starting a server process
1. test fixture
test fixture表示进行测试的准备工作 和相关的清理工作。比如,构造临时或者代理数据库,目录或开启一个服务进程。
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.
2.test case
测试用例是一个测试的独立单元。用来对特殊的输入集的指定结果进行验证。单元测试提供一个基类,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.3.test suite测试套件是一系列测试用例或套件的集合。用来集合需要一起执行的测试集。
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. 4.test runner
test runner执行测试,并提供结果。运行器可能使用一个图形界面,文本界面或者返回一个表示运行结果的特殊值。
----------------------------------------------------------------------------------------
二、基本例子
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.
单元测试模块提供丰富的工具集来构建和运行测试。本节演示一下足以满足大部分需求的工具中一个很小的子集。
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
. 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.
测试用例继承自TestCase的子集,这三个测试方法都以test开头,这个命名规则用于通知runner,哪个方法是测试方法。
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. These methods are used instead of the assert
statement so the test runner can accumulate all test results and produce a report.
每个测试的关键是使用 assertEqual() 验证期望的结果。assertTrue()or assertFalse() 验证一个条件,assertRaises()用于验证一个特殊的raised的预期值。这些方法用于替代assert声明,因此runner可以总结所有测试结果并产生报表。
The setUp()
and tearDown()
methods allow you to define instructions that will be executed before and after each test method. They are covered in more detail in the section Organizing test code.
setUp和tearDown方法允许去定义测试前与后的指令。在组织测试用例这节里会介绍细节。
The final block shows a simple way to run the tests. unittest.main()
provides a command-line interface to the test script. When run from the command line, the above script produces an output that looks like this:
最后一块展示了运行测试的简单方法。unittest.main()
为测试脚本提供一个命令行界面。当从命令行运行时,上述脚本产生如下结果。
... ---------------------------------------------------------------------- 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. The remainder of the documentation explores the full feature set from first principles.
三、命令行界面
The unittest module can be used from the command line to run tests from modules, classes or even individual test methods:
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. The path is converted to a module name by removing the ‘.py’ and converting path separators into ‘.’. 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:
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: In earlier versions it was only possible to run individual test methods and not modules or classes.
单元测试模块可以用命令行界面来运行测试。