CKTIS / Python
Load tests from a class with loadTestsFromTestCase
Build a suite from one `unittest.TestCase` subclass and distinguish the number of loaded test methods from the number of subtests those methods execute.
Version: Python 3.12
Syntax
unittest.defaultTestLoader.loadTestsFromTestCase(testCaseClass)
unittest.TestLoader().loadTestsFromTestCase(testCaseClass)In Python 3.12, TestLoader.loadTestsFromTestCase takes a unittest.TestCase subclass, not an instance. It finds methods on that class rather than scanning files like discover(), and it does not run the tests. It returns a suite, which by default is a unittest.TestSuite.
The loader creates a separate instance of the class for each method selected by getTestCaseNames(). With default settings, it selects methods whose names start with test (no underscore is required), including inherited methods. If no methods are selected but the class implements runTest(), the loader creates one case for runTest().
Use the shared unittest.defaultTestLoader when you do not need custom settings. To change a setting such as testMethodPrefix without modifying the shared loader, create your own unittest.TestLoader(). Call countTestCases() before running the suite to count its cases. subTest() iterations happen inside an already loaded method and do not add separate cases to the suite.
Examples
import unittest
class TwoTests(unittest.TestCase):
def test_positive(self):
for n in range(1, 6):
with self.subTest(n=n):
self.assertEqual(abs(n), n)
def test_negative(self):
for n in range(-4, 0):
with self.subTest(n=n):
self.assertEqual(abs(n), -n)
class FourTests(TwoTests):
def test_zero(self):
self.assertEqual(abs(0), 0)
def test_negative_float(self):
self.assertEqual(abs(-1.5), 1.5)
def main():
loader = unittest.defaultTestLoader
for case_class in (TwoTests, FourTests):
suite = loader.loadTestsFromTestCase(case_class)
loaded = suite.countTestCases()
result = unittest.TestResult()
suite.run(result)
print(f"{case_class.__name__}: loaded={loaded}, run={result.testsRun}, ok={result.wasSuccessful()}")
if __name__ == "__main__":
main()
Result
TwoTests: loaded=2, run=2, ok=True FourTests: loaded=4, run=4, ok=True
`TwoTests` has two test methods that execute nine subtests in total. `FourTests` inherits both methods and adds two of its own. So `loaded` and `run` are both 2 for the first class and both 4 for the second. `ok=True` on both lines means both suites passed.
Related lessons
- Python · Lesson 37 · Advanced · Version: 5
- Python · Lesson 34 · Intermediate · Version: 3