jeudi 2 avril 2020

How do I use same decorators on more than one function in python?

I am testing in django and using decorator mock.patch.object() for mocking object methods. I want to use same decorators in another funtion of that class. For this I moved the decorators from function to class. This solved my problem, but now I want to add another test funtion, which should not mock those functions.

@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClass(testcases.TestCase):
    def setUp(self):
    # contains my setup that I want to use in all functions for this test class

    def test_function_1(self, mocked_class_fun_1, mocked_class_fun_2):
    # I want to use those mocked functions here

    def test_function_2(self, mocked_class_fun_1, mocked_class_fun_2):
    # I want to use those mocked functions here too

    def test_function_3(self):
    # I do not want to use those mocked functions here

If I do this, it is throwing an error:

TypeError: test_function_3() takes 1 positional argument but 3 were given

So what should I do, so that I can use the setUp in all functions and mocked funtions in only two funtions?

PS: I have shown only 2 mocked funtions, but in reality I am mocking 8 functions, so repetition of mock.patch might not be a good idea.

Aucun commentaire:

Enregistrer un commentaire