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

标签 python django unit-testing testing django-testing

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

@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 可能不是一个好主意。

最佳答案

创建一个不带装饰器的父测试类 - TestParent,其中包含 setUp 方法中的代码,然后在两个子类中继承该类 - 一个是经过装饰的,以及一个不是:

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

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

关于python - 如何在 python 中的多个函数上使用相同的装饰器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60987251/

相关文章:

python - SQLAlchemy 0.6.5(和0.6.8)SessionExtension after_flush 不会被调用

python - 重新排列嵌套目录

python - 从 Aptana Studio PyDev 运行时取消抑制 UnicodeEncodeError 异常

python - 属性错误: 'module' object has no attribute 'register_success'

java - 将圈复杂度保持在 5-10 之间是否会使单元测试更容易?

c# - 单元测试自动实现的属性是否有值(value)

python - 如何在 Python 3 中的输入后添加字符串?

python - 通过多个网址进行网页抓取

python - Django:以表单保存多对多