Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution order on Python unittest

I need to set an order of execution for my tests, because I need some data verified before the others. Is possible to set an 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()
like image 336
Carlos Avatar asked May 03 '13 17:05

Carlos


People also ask

Do unit tests run in order?

Occasionally, you may want to have unit tests run in a specific order. Ideally, the order in which unit tests run should not matter, and it is best practice to avoid ordering unit tests. Regardless, there may be a need to do so.

What is the correct order of the unit test layout?

Hence, the correct order of testing is Unit testing, Integration testing, Validation testing & System testing.

How does unittest work in Python?

The unit test framework in Python is called unittest , which comes packaged with Python. Unit testing makes your code future proof since you anticipate the cases where your code could potentially fail or produce a bug. Though you cannot predict all of the cases, you still address most of them.


2 Answers

You can do it like this:

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. Probably you also want to set failfast = True for the testrunner, so it fails instantly, as soon as the first test fails.

like image 78
Michael Avatar answered Oct 13 '22 07:10

Michael


Better do not do it.

Tests should be independent.

To do what you want best would be to put the code into functions that are called by the test.

Like that:

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 to split the test class and put the assertions into the setUp function.

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

    def test_1(self):
        ...

When I split the class I often write more and better tests because the tests are split up and I can see better through all the cases that should be tested.

like image 40
User Avatar answered Oct 13 '22 08:10

User