How can I test several cases for the same function without duplicating test logic?
Quick answer
Put each input and expected result in a case list, then loop over it inside one unittest test method. Wrap each assertion in self.subTest(...) and give every case a useful name. Python’s unittest subtests display supplied messages or parameters when a case fails, helping identify the failing input without repeating the assertion [S1].
The question, the details, the next step.
A practical checklist
Write down each input and its expected result before adding it to the loop.
Give every case a short label that describes its purpose.
Include useful input values in
self.subTest(...)parameters.Keep one shared assertion for cases that check the same kind of behavior.
Use a separate test method when a scenario needs a different assertion or setup.
A few more useful answers
Will a failure show which input caused it?
The subtest’s supplied message or parameters are displayed when that subtest fails [S1]. Include a meaningful case label and relevant input values to make the failure easier to recognize.
Do subtests tell me whether I have enough test cases?
No. They help identify which listed iteration failed, but they do not determine whether your examples cover the function’s intended behavior. Choose cases that reflect the behaviors you need to check.
Sources
References used for this guide.
- [S1] Python unittest: Distinguishing test iterations with subtests docs.python.org · Checked
