Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 356
passionTime Avatar asked Mar 19 '11 07:03

passionTime


People also ask

How do I run a unit test in Python?

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 .

Which function in unit test will run all of your tests in Python?

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.


Video Answer


2 Answers

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() 
like image 161
rakslice Avatar answered Sep 23 '22 04:09

rakslice


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.

like image 28
tddtrying Avatar answered Sep 22 '22 04:09

tddtrying