Getting Started with Python's unittest Framework for Automated Testing
The unittest framework is inspired by JUnit and shares a common design with mainstream testing tools in other languages. It enables automated test execution, shared configuration, and teardown logic. Tests can be grouped into collections and reported independently of the test runner.
Core Concepts
| Concept | Description |
|---|---|
| Setup Context | Preparatory steps before a test and cleanup actions afterward. |
| Test Unit | A single test case; created by subclassing unittest.TestCase. |
| Test Group | A set of test units or nested groups, allowing batch execution. |
| Loader | Component that discovers and loads test units. |
| Executor | Runs tests and presents results via CLI, GUI, or return codes. |
Setup Context Execution Order
Setup contexts run in a fixed sequence: preparation → test → cleanup.
Defining a Test Unit
- Test identifiers must start with
test, applicable to modules, classes, or methods. - Class-based tests inherit from
unittest.TestCase.
Example
import unittest
class StringChecks(unittest.TestCase):
def test_to_uppercase(self):
self.assertEqual('bar'.upper(), 'BAR')
def test_all_caps(self):
self.assertTrue('BAR'.isupper())
self.assertFalse('Bar'.isupper())
def test_break_text(self):
txt = 'hi there everyone'
self.assertEqual(txt.split(), ['hi', 'there', 'everyone'])
with self.assertRaises(TypeError):
txt.split(5)
if __name__ == '__main__':
unittest.main()
Running Tests
- Invoke
unittest.main()within the test file. - Use the command line to specify modules, classes, methods, or file paths:
python -m unittest mod_one mod_two
python -m unittest mod.ClassX
python -m unittest mod.ClassX.method_y
python -m unittest path/to/test_file.py
Add -v for verbose output:
python -m unittest -v mod
New in version 3.2: options -b, -c, -f.
New in version 3.5: option --locals.
New in version 3.7: option -k.
These flags support exploratory runs over all or part of a project's test suite.
Command-Line Options
| Option | Effect |
|---|---|
-v |
Show detailed results. |
-b |
Buffer stdout/stderr during run; flush on failure. |
-c |
On first Ctrl+C, finish current test and report; second raises KeyboardInterrupt. |
-f |
Stop on first error or failure. |
-k |
Run tests matching pattern (case-sensitvie); supports * wildcards against full method names. |
--locals |
Include local variables in tracebacks. |