How do I run multiple Classes in a single test suite in Python using unit testing?
The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .
TestCase is used to create test cases by subclassing it. The last block of the code at the bottom allows us to run all the tests just by running the file.
If you want to run all of the tests from a specific list of test classes, rather than all of the tests from all of the test classes in a module, you can use a TestLoader
's loadTestsFromTestCase
method to get a TestSuite
of tests for each class, and then create a single combined TestSuite
from a list containing all of those suites that you can use with run
:
import unittest # Some tests class TestClassA(unittest.TestCase): def testOne(self): # test code pass class TestClassB(unittest.TestCase): def testOne(self): # test code pass class TestClassC(unittest.TestCase): def testOne(self): # test code pass def run_some_tests(): # Run only the tests in the specified classes test_classes_to_run = [TestClassA, TestClassC] loader = unittest.TestLoader() suites_list = [] for test_class in test_classes_to_run: suite = loader.loadTestsFromTestCase(test_class) suites_list.append(suite) big_suite = unittest.TestSuite(suites_list) runner = unittest.TextTestRunner() results = runner.run(big_suite) # ... if __name__ == '__main__': run_some_tests()
I'm a bit unsure at what you're asking here, but if you want to know how to test multiple classes in the same suite, usually you just create multiple testclasses in the same python file and run them together:
import unittest class TestSomeClass(unittest.TestCase): def testStuff(self): # your testcode here pass class TestSomeOtherClass(unittest.TestCase): def testOtherStuff(self): # testcode of second class here pass if __name__ == '__main__': unittest.main()
And run with for example:
python mytestsuite.py
Better examples can be found in the official documention.
If on the other hand you want to run multiple test files, as detailed in "How to organize python test in a way that I can run all tests in a single command?", then the other answer is probably better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With