Hướng dẫn unit test python example
Source code: Lib/unittest/__init__.py Show
(If you are already familiar with the basic concepts of testing, you might want to skip to the list of assert methods.) The To achieve this,
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 caseA test case is the individual unit of testing. It checks for a specific response to a particular set of inputs. 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 runnerA 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 Moduledoctest Another test-support module with a very different flavor. Simple Smalltalk Testing: With PatternsKent Beck’s original paper on testing frameworks using the pattern shared by Third-party unittest framework with a lighter-weight syntax for writing tests. For example, An extensive list of Python testing tools including functional testing frameworks and mock object libraries. Testing in Python Mailing ListA special-interest-group for discussion of testing, and testing tools, in Python. The script Basic example¶The 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 The crux of each test is a call to
The
The final block shows a simple way to run the tests. ... ---------------------------------------------------------------------- Ran 3 tests in 0.000s OK Passing the 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 Command-Line Interface¶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: For a list of all the command-line options: Changed in version 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
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 ( Patterns are matched against the fully qualified test method name as imported by the test loader. For example, --locals ¶Show local variables in tracebacks. New in
version 3.2: The command-line options New in version 3.5: The command-line option New in version 3.7: The command-line option 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. 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). Test discovery
is implemented in cd project_directory python -m unittest discover Note As a shortcut, The -v
, --verbose ¶Verbose output -s
, --start-directory directory ¶Directory to start discovery ( -p
, --pattern pattern ¶Pattern to match test files ( -t
, --top-level-directory directory ¶Top level directory of project (defaults to start directory) The
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 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 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. Test modules and packages can customize test loading and discovery by through the load_tests protocol. Changed in version 3.4: Test discovery supports namespace packages for the start directory. Note that you need to specify the top level directory too (e.g. 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 The testing code of a The
simplest 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 Tests
can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called 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 Similarly, we can provide a
import unittest class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() If 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. Thus It is recommended that you use TestCase implementations to group tests together according to the features they test.
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
Re-using old test code¶Some users will find that they have existing test code that they would like to run from For this reason, 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
In some cases, the existing tests may have been written using the Skipping tests and expected failures¶New in version 3.1. Unittest supports skipping individual test methods and even whole classes of tests. 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 Skipping a test is simply a matter of using the
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
Expected failures use the 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 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. @ 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 Skipped tests will not have Distinguishing test iterations using subtests¶New in version 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
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 ====================================================================== 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 Test cases¶classunittest. TestCase (methodName='runTest')¶Instances of the
Each instance of Changed in version 3.2:
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
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
setUpClass ()¶A class
method called before tests in an individual class are run. @classmethod def setUpClass(cls): ... See Class and Module Fixtures for more details. New in version 3.2. tearDownClass ()¶A class method called after tests in an individual class have run. @classmethod def tearDownClass(cls): ... See Class and Module Fixtures for more details. New in version 3.2. run (result=None)¶Run the test, collecting the result into the The same effect may be had by simply calling the
Changed in version 3.3: Previous versions of skipTest (reason)¶Calling this during a test method or New in version 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. 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. 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
All the assert methods accept a msg argument that, if specified, is used as the error message on failure (see also assertEqual (first, second,
msg=None)¶Test that first and second are equal. If the values do not compare equal, the test will fail. 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 Changed in version 3.1: Added the automatic calling of type-specific equality function. Changed in version 3.2: assertNotEqual (first, second,
msg=None)¶Test that first and second are not equal. 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). Note that this is equivalent to 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. assertIsNone (expr,
msg=None)¶ assertIsNotNone (expr,
msg=None)¶Test that expr is (or is not) New in version 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. 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 New in version 3.2. It is also possible to check the production of exceptions, warnings, and log messages using the following methods:
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 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,
The context manager will store the caught exception object in its with self.assertRaises(SomeException) as cm: do_something() the_exception = cm.exception self.assertEqual(the_exception.error_code, 3) Changed in version 3.1: Added the ability to use
Changed in version 3.2: Added the Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertRaisesRegex (exception,
regex, callable, *args, **kwds)¶ assertRaisesRegex (exception, regex, *,
msg=None)
Like self.assertRaisesRegex(ValueError, "invalid literal for.*XYZ'$", int, 'XYZ') or: with self.assertRaisesRegex(ValueError, 'literal'): int('XYZ') New in version 3.1: Added under the name Changed in version 3.3: Added the msg keyword argument when used as a context manager. 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
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: with self.assertWarns(SomeWarning): do_something() When used as a context manager, The context manager will store the caught warning object in its 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. Changed in version 3.3: Added the msg keyword argument when used as a context manager. assertWarnsRegex (warning, regex,
callable, *args, **kwds)¶ assertWarnsRegex (warning, regex, *, msg=None)Like
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. Changed in version 3.3: Added the msg keyword argument when used as a context manager. 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. If given, logger should be a If given, level should be either a numeric logging level or its string equivalent (for example either The test passes if at least one message emitted inside the 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 output ¶A list of 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. 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. If given, logger should be a
If given, level should be either a numeric logging level or its string equivalent (for example either Unlike New in version 3.10. There are also other methods used to perform more specific checks, such as:
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 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 Changed in version 3.2:
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. 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 New in version 3.1: Added under the name Changed in version 3.2: The method New in version 3.5: The name 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. Duplicate elements are not ignored when comparing first and second. It verifies whether each element has the same count in both sequences. Equivalent to: New in version 3.2. The
addTypeEqualityFunc (typeobj, function)¶Registers
a type-specific method called by New in version 3.1. The list of type-specific methods automatically used by
assertMultiLineEqual (first, second, msg=None)¶Test that the multiline string first is equal to the string second. When not equal a
diff of the two strings highlighting the differences will be included in the error message. This method is used by default when comparing strings with New in version 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. If the sequences are different an error message is constructed that shows the difference between the two. This method is not called directly by New in version 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 New in version 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
Fails if either of first or second does not have a New in version 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
New in version 3.1. Finally the fail (msg=None)¶Signals a test failure unconditionally, with msg or 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
longMessage ¶This class attribute determines what happens when a custom failure message is passed as the msg argument to an assertXYY call that fails. The class setting can be overridden in individual test methods by assigning an instance attribute, self.longMessage, to The class setting gets reset before each test call. New in version 3.1. maxDiff ¶This attribute controls the maximum length of diffs output by assert methods that report diffs on failure. It defaults to 80*8 characters. Assert methods affected by this attribute are
Setting New in version 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 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
For 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 Changed in version 3.1: In 3.1 this was changed to add the test name to the short description even in the presence of a docstring. This caused compatibility issues with unittest extensions and adding the test name was moved to the addCleanup (function, /, *args, **kwargs)¶Add a function to be called after
If New in version 3.1. doCleanups ()¶This method is called unconditionally after It is responsible for calling all the cleanup functions added by
New in version 3.1. classmethodaddClassCleanup (function, /, *args, **kwargs)¶Add a function to be called after
If New in version 3.8. classmethoddoClassCleanups ()¶This method is called unconditionally after It is responsible for calling all the cleanup functions added by
New in version 3.8. classunittest. IsolatedAsyncioTestCase (methodName='runTest')¶This class provides an API similar to
New in version 3.8. coroutineasyncSetUp ()¶Method called to prepare the test fixture. This is called after asyncTearDown ()¶Method called immediately after the test method has been called and the result recorded. This is called before 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 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, unittest. FunctionTestCase (testFunc, setUp=None, tearDown=None, description=None)¶This class implements the portion of the Deprecated aliases¶For historical reasons, some of the
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 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.
addTest (test)¶Add a
addTests (tests)¶Add all the tests from an iterable of This is equivalent to iterating over tests, calling
run (result)¶Run the tests associated with this suite, collecting the result into the test result object passed as
result. Note that unlike 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 Changed in version 3.2: In earlier versions the
Changed in version 3.4: In earlier versions the
In the typical usage of a Loading and running tests¶classunittest. TestLoader ¶The
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. New in version 3.5.
loadTestsFromTestCase (testCaseClass)¶Return
a suite of all test cases contained in the A test case instance is created for each method named by loadTestsFromModule (module,
pattern=None)¶Return a suite of all test cases contained in the given module. This method searches module for classes derived from Note While using a hierarchy of If a module provides a Changed in version 3.2: Support for Changed in version
3.5: The undocumented and unofficial use_load_tests default argument is deprecated and ignored, although it is still accepted for backward compatibility. The method also now accepts a keyword-only argument pattern which is passed to 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
For example, if you have a module The method optionally resolves name relative to the given module. Changed in version 3.5: If an
loadTestsFromNames (names, module=None)¶Similar to getTestCaseNames (testCaseClass)¶Return a sorted sequence of method names found within
testCaseClass; this should be a subclass of 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. Only test files that match pattern will be loaded. (Using shell style pattern matching.) Only module names that are importable (i.e. are valid Python identifiers) will be loaded. 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
If a package (a directory containing a file named If The pattern is deliberately not stored as a loader attribute so that packages can continue discovery themselves. top_level_dir is stored so start_dir can be a dotted module name as well as a directory. New in version 3.2. Changed in version 3.4: Modules that raise Changed in version 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: Found
packages are now checked for The following attributes of a testMethodPrefix ¶String giving the prefix of method names which will be interpreted as test methods. The default value is This affects sortTestMethodsUsing ¶Function to be used to compare method names when sorting them in
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 This affects all the testNamePatterns ¶List of Unix shell-style wildcard test name patterns that test methods have to match to be included in test suites (see If this attribute is not This affects all the New in version 3.7. classunittest. TestResult ¶This class is used to compile information about which tests have succeeded and which have failed. A Testing frameworks built on top of
errors ¶A list containing 2-tuples of failures ¶A list containing 2-tuples of skipped ¶A list containing 2-tuples of New in version 3.1. expectedFailures ¶A list containing 2-tuples of unexpectedSuccesses ¶A list containing shouldStop ¶Set to testsRun ¶The total number of tests run so far. buffer ¶If set to true, New in version 3.2. failfast ¶If set to true New in version 3.2. tb_locals ¶If set to true then local variables will be shown in tracebacks. New in version 3.5. wasSuccessful ()¶Return stop ()¶This method can be called to signal that the set of tests being run should be aborted by setting the For example, this feature is used by the The following methods of the
startTest (test)¶Called when the test case test is about to be run. stopTest (test)¶Called after the test case test has been executed, regardless of the outcome. startTestRun ()¶Called once before any tests are executed. New in version 3.1. stopTestRun ()¶Called once after all tests are executed. New in version 3.1. addError (test,
err)¶Called when the test case test raises an unexpected exception. err is a tuple of the form returned by The default implementation appends a tuple addFailure (test,
err)¶Called when the test case test signals a failure. err is a tuple of the form returned by The default implementation appends a tuple 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 addExpectedFailure (test, err)¶Called when the test case test fails or errors, but was marked with the
The default implementation appends a tuple addUnexpectedSuccess (test)¶Called when the test case test was marked with the The default implementation appends the test to the instance’s addSubTest (test, subtest,
outcome)¶Called when a subtest finishes. test is the test case corresponding to the test method. subtest is a custom If
outcome is The default implementation does nothing when the outcome is a success, and records subtest failures as normal failures. New in version 3.4. classunittest. TextTestResult (stream, descriptions, verbosity)¶A concrete implementation of
New in version 3.2: This class was previously named unittest. defaultTestLoader ¶Instance of the unittest. 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 By default this runner shows Changed in version 3.2: Added the Changed in version 3.2: The default stream is set to Changed in version 3.5: Added the tb_locals parameter. _makeResult ()¶This method returns the instance of
stream, descriptions, verbosity run (test)¶This method is the main public interface to the 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. 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: 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 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 The testRunner argument can either be a test runner class or an already created instance of it. By default The
testLoader argument has to be a
>>> 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 Calling Changed in version 3.1: The exit parameter was added. Changed in version 3.2: The verbosity, failfast, catchbreak, buffer and warnings parameters were added. Changed in version 3.4: The defaultTest parameter was changed to also accept an iterable of test names. load_tests Protocol¶New in version 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 If a test module defines load_tests(loader, standard_tests, pattern) where pattern is passed straight through from It should return a loader
is the instance of A typical 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 load_tests(loader, standard_tests, pattern) This should return a Because the pattern is passed into 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: Discovery no longer checks package names for matching pattern due to the impossibility of package names matching the default pattern. Class and Module Fixtures¶Class and module level fixtures are implemented in Similarly if a test is from a different module from the previous test then After all the tests have run the final 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. This will lead to Shared fixtures are not intended to work with suites with non-standard ordering. A 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 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 If an exception is raised during a setUpModule and tearDownModule¶These should be implemented as functions: def setUpModule(): createConnection() def tearDownModule(): closeConnection() If an exception is raised in a To add cleanup code that must be run even in the case of an exception, use unittest. addModuleCleanup (function, /, *args,
**kwargs)¶Add a function to be called after If New in version 3.8. unittest. doModuleCleanups ()¶This function is called unconditionally after It is responsible for calling all the cleanup functions added by
New in version 3.8. Signal Handling¶New in version 3.2. The
The control-c handling signal handler attempts to remain compatible with code or tests that install their own There are a few utility functions for framework authors to enable control-c handling functionality within test frameworks. unittest. installHandler ()¶Install the control-c handler. When a unittest. registerResult (result)¶Register a
Registering a unittest. removeResult (result)¶Remove a registered result. Once a result has been removed then
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: @unittest.removeHandler def test_signal_handling(self): ... |