CKTIS / Python
unittest subtests: equality and expected exceptions
Check multiple inputs in one test method, label failing cases, and distinguish an equality assertion from a callable-form exception assertion.
Version: Python 3.12
Syntax
with self.subTest("case label", value=value):
self.assertEqual(actual, expected)
with self.subTest(value=value):
self.assertRaises(ExpectedError, func, *args, **kwargs)
with self.assertRaises(ExpectedError):
func(*args, **kwargs)In Python 3.12, unittest.TestCase.subTest returns a context manager. Use with self.subTest("label", value=value): to mark a block as one subtest, for example one loop iteration. The optional message msg and keyword arguments **params identify the subtest in a failure report; they are not passed to the function under test.
Without failfast, a failed assertion ends the current with block, but the test method continues after it and can run later subtests. Subtests are not separate test methods and do not run setUp() or tearDown() separately. With failfast enabled, do not assume later subtests will run.
self.assertEqual(actual, expected) checks value equality (==), not object identity (is). If the values are unequal, the assertion fails. Put it inside the subtest so the report identifies the input that produced the unexpected result.
In the callable form, self.assertRaises(ExpectedError, func, *args, **kwargs) calls func with the supplied arguments. Pass func, not func(...). The assertion passes if the expected exception or a subclass is raised, fails if no exception is raised, and lets a nonmatching exception propagate. Alternatively, use with self.assertRaises(ExpectedError): and call the function inside the block.
Examples
import unittest
class ParseTests(unittest.TestCase):
def test_parse(self):
for text, expected in [("12", 13), ("-3", -3)]:
with self.subTest("valid integer", text=text):
self.assertEqual(int(text), expected)
with self.subTest("invalid integer", text="bad"):
self.assertRaises(ValueError, int, "bad")
print("Invalid input rejected")
if __name__ == "__main__":
result = ParseTests("test_parse").run()
tests, failures, errors = result.testsRun, len(result.failures), len(result.errors)
print(f"tests={tests}, failures={failures}, errors={errors}")
# The demonstration succeeds only if it records the deliberate failure.
if (tests, failures, errors) != (1, 1, 0):
raise SystemExit(1)
Result
Invalid input rejected tests=1, failures=1, errors=0
The expected value `13` for `"12"` is deliberately wrong. The `"-3"` subtest passes, and the `"bad"` case prints its message only after the expected `ValueError` has been caught. The summary counts one test method, one failure, and zero errors. The script exits with status `0` when the counts match those expected values.
Related lessons
- Python · Lesson 37 · Advanced · Version: 5
Sources
- Python 3.12 unittest — TestCase.subTest
- Python 3.12 unittest — Distinguishing test iterations using subtests
- Python 3.12 unittest — TestCase.assertEqual
- Python 3.12 unittest — TestCase.assertRaises
- Python 3.12 unittest — TestCase.run
- Python 3.12 unittest — TestResult.addSubTest
- Python 3.12 unittest — failfast command-line option