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

Ashish Singh :

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.

MatsLindh :

Create a parent test class without the decorators - TestParent which contains the code from your setUp method, then inherit from this class in two subclasses - one that's decorated, and one that's not:

class TestClassParent(testcases.TestCase):
    def setUp(self):
        # contains my setup that I want to use in all functions for this test class

@mock.patch.object(MyClass, 'class_fun_2')
@mock.patch.object(MyClass, 'class_fun_1')
class TestClassMocked(TestClassParent):
    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

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

That will allow you to share the setup code, and specify which methods shouldn't be mocked.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=395349&siteId=1