Table-Driven Tests in Python (unittest)

Run a single unittest test against many input cases using a list of tuples and subTest.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Python code

20 lines
Python 3.9+
import 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

stdout
....
----------------------------------------------------------------------
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

  1. Use `pytest` with `@pytest.mark.parametrize` to achieve the same result.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.