Python Unittest Module
The unittest module provides a rich set of tools for constructing and running tests. 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.
Importing the Module
import unittest
Basic Test Structure
A test case is created by subclassing unittest.TestCase. Individual tests are defined with methods whose names start with test.
import unittest
def add(x, y):
return x + y
class TestAddFunction(unittest.TestCase):
def test_add_integers(self):
self.assertEqual(add(1, 2), 3)
def test_add_strings(self):
self.assertEqual(add('a', 'b'), 'ab')
if __name__ == '__main__':
unittest.main()
Common Assertions
The TestCase class provides several assertion methods to check for and report failures.
| Method | Checks that |
|---|---|
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 |
assertIsNone(x) |
x is None |
assertIn(a, b) |
a in b |
assertIsInstance(a, b) |
isinstance(a, b) |
Testing Exceptions
You can verify that a specific exception is raised using assertRaises().
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
class TestMath(unittest.TestCase):
def test_divide_by_zero(self):
with self.assertRaises(ValueError):
divide(10, 0)
Test Fixtures (Setup and Teardown)
Test fixtures represent the preparation needed to perform one or more tests, and any associate cleanup actions.
Method Level
setUp(): Called immediately before calling the test method.tearDown(): Called immediately after the test method has been called.
class TestDatabase(unittest.TestCase):
def setUp(self):
self.db = create_db_connection()
def tearDown(self):
self.db.close()
Class Level
setUpClass(): Called once before running all tests in the class. Must be decorated with@classmethod.tearDownClass(): Called once after running all tests in the class. Must be decorated with@classmethod.
Command Line Interface
The unittest module can be used from the command line to run tests from modules, classes or even individual test methods.
# Run tests from a specific module
python -m unittest test_module
# Automatically discover and run tests
python -m unittest discover