8
votes

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()
2
unit test means tests are unitary. they are not supposed to depend on one another. - njzk2
If you're actually interacting with a real server over the wire, you're not doing unit testing. - user395760
Unitary is nice in philosophy, but quite unhandy in practice sometimes. Imagine a long setup, loading files from disk, network connections ... You don't want your test cases to take an eternity. The slower they are, the less you'll run them, so the less useful they are. - Michael
Well, it's still the best option to do it. You just shouldn't be too dogmatic about it. I have a lot of unit tests for lengthy mathematical computations, without saving temporary results and setup code in setUpClass for a whole set of tests, it would be painfully slow. So as long as your tests proof, what you want to proof, who cares about dogma? - Michael

2 Answers

1
votes

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.

27
votes

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.