Unit-level regression tests
Validate a small function or class behavior with explicit expected values.
Python · Module
Python’s unittest module provides a standard framework for automating unit tests, sharing setup and cleanup, grouping tests, and reporting results. Tests are commonly organized as TestCase instances and run through the module’s command-line interface.
The module models tests as TestCase instances, usually created by subclassing TestCase and adding methods whose names begin with test. Assertions check expected behavior, while the command-line runner can execute modules, classes, methods, or discovered tests and report results.
python -m unittest [options] [module[.Class[.method]] ...]| Name | Type | Description |
|---|---|---|
target | module, class, or method name | A module, TestCase class, or individual test method target passed to the command-line runner. |
A test run report; failures and errors are reported by the runner.
import unittest
def add(left, right):
return left + right
class AddTests(unittest.TestCase):
def test_adds_numbers(self):
self.assertEqual(add(2, 3), 5)
if __name__ == "__main__":
unittest.main()Defines a TestCase subclass, checks an expected result, and runs the test module directly.
Validate a small function or class behavior with explicit expected values.
Run a complete test module or selected dotted test target from a shell.
Organize multiple test cases into reusable collections for a larger suite.
A TestCase is the basic unit of a unittest test. Create one by subclassing unittest.TestCase and define test methods containing assertions.
Follow-up: How can one test be run without running its whole module? Pass the dotted module, class, and method name to python -m unittest.
The command supports module names, TestCase class names, and individual test method names. Add -v to request more detailed output.
Follow-up: What is the command-line shortcut for discovery? Running python -m unittest without a target is equivalent to unittest discover.
unittest supports test automation, shared setup and shutdown code, grouping tests into collections, and separating tests from the reporting framework.
Follow-up: Which mechanism finds tests automatically? Test discovery can locate tests across a project, while explicit targets restrict execution to chosen tests.
unittest.TestCaseunittest.TestSuiteunittest.TestLoaderunittest.mainunittest discover