Table-Driven Tests in Python (unittest)
Run a single unittest test against many input cases using a list of tuples and subTest.
Python code
20 linesimport unittest
def add(a, b):
return a + b
class TestAddFunction(unittest.TestCase):
def test_add_with_table(self):
cases = [
(1, 2, 3),
(-1, 1, 0),
(0, 0, 0),
(2, -3, -1),
]
for x, y, expected in cases:
with self.subTest(x=x, y=y, expected=expected):
self.assertEqual(add(x, y), expected)
if __name__ == "__main__":
unittest.main()
Output
....
----------------------------------------------------------------------
Ran 4 tests in 0.001s
OK
How it works
The cases list holds tuples of (x, y, expected). Each iteration unpacks those values and calls add(x, y). Calling self.subTest with the current values makes each case a separate subtest; if one fails, the others still run and you get a clear report naming the failing input. This pattern keeps tests DRY and makes adding new cases as easy as appending a line to the list.
Common mistakes
- Using `assertEqual` outside the loop, which only tests one case.
- Forgetting to use `subTest`, so a failure stops the whole test and hides other cases.
- Skipping the `expected` value in the tuple definition, causing unpacking errors.
Variations
- Use `pytest` with `@pytest.mark.parametrize` to achieve the same result.
- Use a list of dictionaries instead of tuples for clearer failure messages.
Real-world use cases
- Validating a sorting algorithm against many edge-case arrays and expected results in a CI pipeline.
- Testing an API client by running a batch of request-status-code pairs to verify response handling.
- Checking a price calculator with a table of quantity, discount, and tax combos.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.