Nick Chapman
Nick Chapman

Reputation: 4634

Python unittest run TestCases in a specific order

I have a number of test cases, well say TestA, TestB, TestC, and I want them to be run in a specific order such as TestB --> TestC --> TestA. How can I make sure that the tests are actually run in this order?

Note that those test cases are classes which inherit from unittest.TestCase not just methods inside of a TestCase. That is to say, I am not wondering about the execution order of tests within a TestCase, I'm wondering about how to change the order in which the TestCase's themselves are run.

For those of you who are going to say that I'm doing something terrible and that's not how you write unit tests, I'm doing integration testing and I am aware this is a bad practice for unit tests.

Upvotes: 0

Views: 763

Answers (2)

Nick Chapman
Nick Chapman

Reputation: 4634

The answer to this question is to use a unittest.TestSuite which preserves the order in which tests are added. You can do the following:

loader = unittest.TestLoader()
suite = unittest.TestSuite()
tests_to_run = [TestCaseA, TestCaseB, TestCaseC]
for test in tests_to_run:
    suite.addTests(loader.loadTestsFromTestCase(test)
runner = unittest.TextTestRunner()
runner.run(suite)

Upvotes: 1

geckos
geckos

Reputation: 6299

You can select a specific test case to run by passing it to the unittest module. You may put something like this in a script!

python -m unittest your.package.test.TestCaseB
python -m unittest your.package.test.TestCaseA

Upvotes: 0

Related Questions