How do I run multiple Classes in a single test suite in Python using unit testing?

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.


The unittest.TestLoader.loadTestsFromModule() method will discover and load all classes in the specified module. So you can just do this:

import unittest
import sys

class T1(unittest.TestCase):
  def test_A(self):
    pass
  def test_B(self):
    pass

class T2(unittest.TestCase):
  def test_A(self):
    pass
  def test_B(self):
    pass

if __name__ == "__main__":
  suite = unittest.TestLoader().loadTestsFromModule( sys.modules[__name__] )
  unittest.TextTestRunner(verbosity=3).run( suite )