Repository navigation
Unittest The Python builtin library for unit testing
The unittest unit testing framework was originally inspired by JUnit and has a similar flavor as major unit testing frameworks in other languages.
Unittest supports some important testing concepts:
-
test fixture: represents the preparation needed to perform one or more tests, and any associated cleanup actions.
-
test case: is the individual unit of testing. It checks for a specific response to a particular set of inputs.
-
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: is a component which orchestrates the execution of tests and provides the outcome to the user.
As we saw in A brief introduction of the case study, we have a class called Point that will help us to represent the points of the figures that we are going to create. So let's start by writing the necessary tests that we want the Point class to implement.
First of all, we are going to create two files: test_point.py (where we define what properties we want the Point class to have) and Point.py (where we will implement those properties).
So, our project would look similar to:
src/
__init__.py
Point.py
tests/
__init__.py
test_point.py
Now, let's write the first tests for the properties we want from the Point class:
# test_point.py
import unittest
from src.Point import Point
class TestPoint(unittest.TestCase):
def setUp(self):
"""Creates a Point() object with (x, y) = (3.0, 4.0)"""
self.point = Point(3.0, 4.0)
def test_get_x(self):
self.assertEqual(self.point.get_x(), 3.0)
def test_get_y(self):
self.assertEqual(self.point.get_y(), 4.0)# Point.py
class Point:
passThen, we run the following command (note that poetry is only to handle dependencies correctly and for that reason we do not explain it in this wiki):
$ poetry run python -m unittest -v tests/test_point.py
======================================================================
ERROR: test_get_x (tests.test_point.TestPoint)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path_to_project/tests/test_point.py", line 8, in setUp
self.point = Point(3.0, 4.0)
TypeError: Point() takes no arguments
======================================================================
ERROR: test_get_y (tests.test_point.TestPoint)
----------------------------------------------------------------------
Traceback (most recent call last):
File "path_to_project/tests/test_point.py", line 8, in setUp
self.point = Point(3.0, 4.0)
TypeError: Point() takes no arguments
----------------------------------------------------------------------
Ran 2 tests in 0.001s
FAILED (errors=2)Now, we add the methods required to pass the tests:
# Point.py
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def get_x(self):
return self.x
def get_y(self):
return self.y$ poetry run python -m unittest -v tests/test_point.py
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
Now, we refactor the code:
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def get_x(self) -> float:
return self.x
def get_y(self) -> float:
return self.y$ poetry run python -m unittest -v tests/test_point.py
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OKCongratulations! We just finished our first iteration!
For practical purposes we are not going to show all the iterations to make the code (which can be seen finished in this repository). We prefer then, to show more in detail the tools that unittest offers us as a library.
For a list of all the command-line options:
$ python -m unittest -h
Usage: python -m unittest [options] [tests] Options: -h, --help Show this message -v, --verbose Verbose output -q, --quiet Minimal output -f, --failfast Stop on first failure -c, --catch Catch control-C and display results -b, --buffer Buffer stdout and stderr during test runsExamples: python -m unittest test_module - run tests from test_module python -m unittest module.TestClass - run tests from module.TestClass python -m unittest module.Class.test_method - run specified test method
[tests] can be a list of any number of test modules, classes and test methods.
Alternative Usage: python -m unittest discover [options]
Options: -v, --verbose Verbose output -f, --failfast Stop on first failure -c, --catch Catch control-C and display results -b, --buffer Buffer stdout and stderr during test runs -s directory Directory to start discovery ('.' default) -p pattern Pattern to match test files ('test*.py' default) -t directory Top level directory of project (default to start directory)
For test discovery all test modules must be importable from the top level directory of the project.
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.
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.
It is recommended that you use TestCase implementations to group tests together according to the features they test. unittest provides a mechanism for this: the test suite, represented by unittest’s TestSuite class.
For example, if we want to have a TestSuite with the tests of all the figures we would do:
# tests/test_suite.py
import unittest
from tests import test_point
from tests import test_ellipse
from tests import test_circle
from tests import test_triangle
from tests import test_rectangle
def suite():
test_suite = unittest.TestSuite()
loader = unittest.TestLoader()
test_suite.addTests(loader.loadTestsFromModule(test_point))
test_suite.addTests(loader.loadTestsFromModule(test_rectangle))
test_suite.addTests(loader.loadTestsFromModule(test_triangle))
test_suite.addTests(loader.loadTestsFromModule(test_ellipse))
test_suite.addTests(loader.loadTestsFromModule(test_circle))
return test_suite
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite())$ poetry run python -m unittest -v tests/test_suite.py
test_distanceTo (tests.test_point.TestPoint) ... ok
test_equals (tests.test_point.TestPoint) ... ok
test_get_x (tests.test_point.TestPoint) ... ok
test_get_y (tests.test_point.TestPoint) ... ok
test_str (tests.test_point.TestPoint) ... ok
test_area (tests.test_rectangle.TestRectangle) ... ok
test_base (tests.test_rectangle.TestRectangle) ... ok
test_even_area (tests.test_rectangle.TestRectangle) ... ok
test_height (tests.test_rectangle.TestRectangle) ... ok
test_is_rectangle (tests.test_rectangle.TestRectangle) ... ok
test_perimeter (tests.test_rectangle.TestRectangle) ... ok
test_str (tests.test_rectangle.TestRectangle) ... ok
test_area (tests.test_triangle.TestTriangle) ... ok
test_is (tests.test_triangle.TestTriangle) ... ok
test_perimeter (tests.test_triangle.TestTriangle) ... ok
test_str (tests.test_triangle.TestTriangle) ... ok
test_area (tests.test_ellipse.TestEllipse) ... ok
test_is (tests.test_ellipse.TestEllipse) ... ok
test_perimeter (tests.test_ellipse.TestEllipse) ... ok
test_str (tests.test_ellipse.TestEllipse) ... ok
testSkip (tests.test_circle.TestCircle) ... skipped 'This could be used to avoid a test'
test_area (tests.test_circle.TestCircle) ... Test finished!
ok
test_is (tests.test_circle.TestCircle) ... Test finished!
ok
test_perimeter (tests.test_circle.TestCircle) ... Test finished!
ok
test_perimeter_fail (tests.test_circle.TestCircle) ... Test finished!
expected failure
test_str (tests.test_circle.TestCircle) ... Test finished!
ok
----------------------------------------------------------------------
Ran 26 tests in 0.002s
OK (skipped=1, expected failures=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 will fail, but shouldn’t be counted as a failure on a TestResult.
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.
exception unittest.SkipTest(reason)
This exception is raised to skip a test.
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.
| Method |
|---|
assertTrue(x, msg=None) |
assertFalse(x, msg=None) |
assertIsNone(x, msg=None) |
assertIsNotNone(x, msg=None) |
assertEqual(a, b, msg=None) |
assertNotEqual(a, b, msg=None) |
assertIs(a, b, msg=None) |
assertIsNot(a, b, msg=None) |
assertIn(a, b, msg=None) |
assertNotIn(a, b, msg=None) |
assertIsInstance(a, b, msg=None) |
assertNotIsInstance(a, b, msg=None) |
| Method |
|---|
assertAlmostEqual(a, b, places=7, msg=None, delta=None) |
assertNotAlmostEqual(a, b, places=7, msg=None, delta=None) |
assertGreater(a, b, msg=None) |
assertGreaterEqual(a, b, msg=None) |
assertLess(a, b, msg=None) |
assertLessEqual(a, b, msg=None) |
assertRegex(text, regexp, msg=None) |
assertNotRegex(text, regexp, msg=None) |
assertCountEqual(a, b, msg=None) |
assertMultiLineEqual(a, b, msg=None) |
assertSequenceEqual(a, b, msg=None) |
assertListEqual(a, b, msg=None) |
assertTupleEqual(a, b, msg=None) |
assertSetEqual(a, b, msg=None) |
assertDictEqual(a, b, msg=None) |
| Method |
|---|
assertRaises(exception) |
assertRaisesRegex(exception, regexp) |
assertWarns(warn, fun, *args, **kwds) |
assertWarnsRegex(warn, fun, *args,**kwds) |
As you develop multiple tests and work on your project, we would like to avoid executing things like:
python -m unittest test_1.py test_2.py test_3.py ... test_n.pySo the class TestSuite is used to represent an aggregation of individual test cases and other test suites.
A Test suite is a collection of test cases.
Given a TestSuite you can add individual tests or other test suites to it with the following methods:
| Method |
|---|
addTest(test) Add a TestCase or TestSuite to the suite. |
addTests(tests) Add all the tests from an iterable of TestCase and TestSuite instances. |
| TestSuite shares the following methods with TestCase |
run(result) Run the tests associated with this suite, collecting the result into the test result object passed as result. Note that unlike TestCase.run(), TestSuite.run() requires the result object to be passed in.
|
debug() Run the tests associated with this suite without collecting the result. |
countTestCases() Return the number of tests represented by this test object, including all individual tests and sub-suites. |
The run() method is not usually invoked, we rather create a TestRunner class and run the suite from there, as seen in the Organizing test code example.
When developing a TestSuite, a TestLoader is used to load the tests on to the suite. The unittest module already has a unittest.defaultTestLoader that you can use, but in these examples we do use a custom one to show how it can be done.
The TestLoader class has a few attributes that become very helpful for TDD. The most used one is,
- errors: Here you can find information about any non-fatal errors that occurred while loading the tests.
The TestLoader class has many methods that exceed the reach of this wiki, so we encourage you to read them from here.
TestSuite has Class and Module level fixtures. This assures the programmer that they have the ability to set up and tear down all the data needed for each collection of tests.
For example, when we do setUp the data in these example we do something like this:
# tests/test_circle.py
...
class TestCircle(unittest.TestCase):
def setUp(self):
self.circle = Circle(Point(0.0, 0.0), 2.3)
...We do not use the tearDown or tearDownClass methods here because python's own trash collector can handle the things we created, but if we were interacting with a DB or an API you should tear down what you have built.
Finally, unittest has the means to handle and catch signals even though they are rarely used and can be avoided most of the time. But, if you wished to use them, you could use the methods explained here.