我在一个类中有几种测试方法,这些方法使用一种类型的对象修补程序,因此我使用类装饰器进行了修补。对于另一个方法,我想以不同的方式修补同一对象。我尝试了以下方法,但是尽管方法本身使用了不同的补丁来装饰,但作为类装饰器制作的补丁仍然有效。我希望方法补丁能覆盖类补丁。为什么不是这样?
在这种特殊情况下,我可以删除类补丁并修补单个方法,但这将是重复的。如何实现这种覆盖(方法覆盖类补丁)机制?
from unittest TestCase
from unittest import mock
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('testing'))
class SwitchViewTest(TestCase):
def test_use_class_patching(self):
# several other methods like this
# test code ..
@mock.patch('my_module.cls.method', mock.Mock(side_effect=RuntimeError('custom'))
def test_override_class_patching(self):
# test code ...
最佳答案
使用with
:
def test_override_class_patching(self):
with mock.patch('my_module.cls.method') as mock_object:
mock_object.side_effect = RuntimeError('custom')
# test code ...
关于python - 用方法补丁(装饰器)覆盖类补丁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39651686/