使用方法补丁(装饰器)覆盖类补丁

时间:2016-09-23 02:32:51

标签: python unit-testing tdd python-unittest python-unittest.mock

我在一个类中有几个测试方法,它们对一个对象使用一种类型的修补,所以我修补了类装饰器。对于另一种方法,我想以不同方式修补相同的对象。我尝试了以下方法,但是作为类装饰器制作的补丁虽然方法本身用不同的补丁装饰,但仍然有效。我期望方法补丁覆盖类补丁。为什么不是这样?

在这种特殊情况下,我可以删除类补丁并修补单个方法,但这将是重复的。如何实现这样的重写(方法覆盖类补丁)机制?

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 ...

3 个答案:

答案 0 :(得分:2)

这只有在编写类装饰器时才能使用方法装饰器。尽管类装饰器首先出现,但它只能在创建类对象之后运行,这在定义(和修饰)所有方法之后发生。

类装饰器在方法装饰器之后运行,而不是之前。

答案 1 :(得分:2)

使用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 ...

答案 2 :(得分:0)

我会采取完全不同的方法。

class SwitchViewTest(TestCase):

  class SwitchViewStub(SwitchView):
    """ Stub out class under test """
    def __init__(self):
    """ Bypass Constructor """
      self.args = None
      ... #  Fill in the rest

  def setUp():
    self.helper = self.SwitchViewStub()
    self.helper.method_to_mock = MagicMock(...)
    ...

  def test_override_class_patching(self):
    with mock.patch.object(self.helper, 'method_to_mock', ...):
      ...