Python unittest execution order

I need to set the execution order for my tests, because I need some data checked against others. Can I establish order?

class OneTestCase(unittest.TestCase): def setUp(self): # something to do def test_login (self): # first test pass def test_other (self): # any order after test_login def test_othermore (self): # any order after test_login if __name__ == '__main__': unittest.main() 

thank

+6
python unit-testing
May 03 '13 at 17:21
source share
2 answers

Better not do this.

Tests must be independent.

To do what you need, it would be best to turn the code into functions called by the test.

Like:

 def assert_can_log_in(self): ... def test_1(self): self.assert_can_log_in() ... def test_2(self): self.assert_can_log_in() ... 

Or even break the test class and put the statements in the setUp function.

 class LoggedInTests(unittest.TestCase): def setUp(self): # test for login or not - your decision def test_1(self): ... 

When I break up a class, I often write more and better tests, because the tests are divided, and I can better see all the tests that need to be checked.

+1
May 03 '13 at 17:23
source share

You can do it as follows:

 class OneTestCase(unittest.TestCase): @classmethod def setUpClass(cls): # something to do pass def test_01_login (self): # first test pass def test_02_other (self): # any order after test_login def test_03_othermore (self): # any order after test_login if __name__ == '__main__': unittest.main(failfast=True, exit=False) 

Tests are sorted alphabetically, so just add numbers to get your desired order. You probably also want to set failfast = True for testrunner, so it doesn't work instantly as soon as the first test fails.

+18
May 03 '13 at 17:26
source share



All Articles