Search code examples
pythondjangopython-unittestpython-decorators

Switch order of decorators based on what test case is running?


In order to test a feature flag, I'm mocking/patching two functions with patch.

However, whenever I switch the order of these mock decorators it causes some tests to fail. When I switch them again, those failing tests pass and the previously passing tests fail.

To my knowledge, this is due to the order in which decorators are evaluated in Python.

Is there a way to declare/specify for one specific test which decorator should be evaluated first?

@mock.patch.object(MyMockClass, '_some_function', return_value=False)
@mock.patch.object(MyMockClass, '_another_function', return_value=False)
class MyClassTestCase(TestCase):
    # code...

Solution

  • You can apply the decorators to each method of your MyClassTestCase class individually, thereby specifying the order in which to evaluate the decorators for each method.

    Basically change:

    @mock.patch.object(MyMockClass, '_some_function', return_value=False)
    @mock.patch.object(MyMockClass, '_another_function', return_value=False)
    class MyClassTestCase(TestCase):
        def test_that_it_works(self, *args):
            # do test stuff
    

    To:

    class MyClassTestCase(TestCase):
        @mock.patch.object(MyMockClass, '_some_function', return_value=False)
        @mock.patch.object(MyMockClass, '_another_function', return_value=False)
        def test_that_it_works(self, mock_another, mock_some):
            # do test stuff