Search code examples
django-testing

Best practice for ensuring test methods order


Django 1.9. I want to test that input forms are invisible normally. And only when a user presses toggle menu button, login and password input elements appear.

The problem is that this is all about methods of a class. I want to be sure that one method executes before another. I have found this solution with 0 and 1 in method names.

class FuncTestTablets(TestCase):

    @classmethod
    def setUpClass(cls):
        pass

    @classmethod
    def tearDownClass(cls):
        pass

    def test_0_tablets_login_input_form_absent(self):
        # At home page with tablet screen size Edith sees no login input element.
        ## 0 is for stating explicitly that this test goes before the ones with 1 in their name. 
        self.browser.get('http://localhost:8000')
        login_input = self.browser.find_element_by_id('login')        
        self.assertFalse(login_input.is_displayed(), "Login input element is visible on large devices")

    def test_1_tablets_login_input_form_present_when_menu_button_pressed(self):
        # At home page Edith presses menu button and login input appears.
        ## 1 is for stating explicitly that this test goes after the ones with 0 in their name.
        menu_button = self.browser.find_element_by_class_name('navbar-toggle')
        menu_button.click()
        login_input = self.browser.find_element_by_id('login')
        self.assertTrue(login_input.is_displayed(), "Login input element is not visible on tablet devices when menu button is pressed.")

This seems to work. Could you tell me is there some generally known methodology for such cases. Maybe some best practice.

I've just started Django and I don't think that my solution is at once the best.

That's why I decided to ask you. Thank you in advance.


Solution

  • Best practice is that the order of your test methods does not matter at all and if you inherit from django.test.TestCase, it should not matter. I have, however, been in the situation where I wanted to test a feature 'foo' in one method and then, for convenience (like not having to wrap it in try-except), assume that it is working properly in other methods that test something else ('bar').

    I named my test methods

    test_a_foo
    test_b_bar
    

    This seems more appropriate then using numbers because tests are executed in lexicographic order where, e.g.

    test_11_eleven
    

    is executed before

    test_2_two
    

    If you then have to insert another test later, you can still change the names to:

    test_b1_first_b
    test_b2_second_b