如何在 python 中对多个函数使用相同的装饰器?

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

我正在 Django 中测试并使用装饰器 mock.patch.object() 来模拟对象方法。我想在 class 的另一个功能中使用相同的装饰器。为此,我将装饰器从函数移到了 class。这解决了我的问题,但现在我想添加另一个测试功能,它不应该模拟这些功能。

@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

如果我这样做,它会抛出一个错误:

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

那么我应该怎么做,才能在所有函数中使用 setUp 而只在两个函数中使用模拟函数?

PS:我只展示了 2 个模拟函数,但实际上我模拟了 8 个函数,所以重复 mock.patch 可能不是一个好主意。

创建一个没有装饰器的父测试 class - TestParent 其中包含来自您的 setUp 方法的代码,然后在两个子 [= 中继承此 class 17=]es - 一个装饰过的,一个没有装饰过的:

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

这将允许您共享设置代码,并指定不应模拟哪些方法。