繁体   English   中英

如何在Python对象的模拟方法中调用self?

[英]How to call self in a mock method of an object in Python?

我尝试测试一些代码,这些代码除了将结果保存到数据库外不会返回任何内容。 通过模拟save方法,我希望检查事物是否已正确处理:

def mock_save(self):
    assert(self.attr, 'dest_val')
with mock.patch.object(Item, "save", create=True) as save:
    save.side_effect = mock_save
    func_to_call() //in func_to_call, I call item.save()

但是,似乎不允许这样做。 它说参数不匹配的数量。

如果我定义def mock_save(),它将无法正常工作。

我怎么也可以引用模拟方法所作用的对象? (我在另一个线程中看到了它,该线程适用于可以直接从类中调用的init方法)

您需要autospec=True

def mock_save(self):
    assert self.attr == 'dest_val'
with mock.patch.object(Item, "save", autospec=True) as save:
    save.side_effect = mock_save
    func_to_call()

有时,您只想检查一个方法是否已被调用,但是您无法控制其类的实例化位置或所调用的方法。 这是一种方法,可以为那些偶然发现此模式的人节省一些时间:

# first get a reference to the original unbound method we want to mock
original_save = Item.save
# then create a wrapper whose main purpose is to record a reference to `self`
# when it will be passed, then delegates the actual work to the unbound method
def side_fx(self, *a, **kw):
    side_fx.self = self
    return original_save(self, *a, **kw)
# you're now ready to play
with patch.object(Item, 'save', autospec=True, side_effect=side_fx) as mock_save:
    data = "the data"
    # your "system under test"
    instance = SomeClass()
    # the method where your mock is used
    instance.some_method(data) 

    # you now want to check if it was indeed called with all the proper arguments
    mock_save.assert_called_once_with(side_fx.self, data) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM