如何在`moock.Mock().call_args`中获取`self`实例?

问题描述

我在修补伪类时观察到不一致的行为:

class A:

  def f(self, *args, **kwargs):
    pass

如果我手动修补函数:

call_args_list = []
def mock_fn(*args, **kwargs):
  call_args_list.append(mock.call(*args, **kwargs))

with mock.patch.object(A, 'f', mock_fn):
  A().f(1, 2)

print(call_args_list)  # [call(<__main__.A object at 0x7f0da0c08b50>, 1, 2)]

正如预期的那样,使用self参数(mock_fn(self, 1, 2))调用mock_fn

但是,如果我使用mock.Mock对象,self参数将从调用中删除:

mock_obj = mock.Mock()

with mock.patch.object(A, 'f', mock_obj):
  A().f(1, 2)

print(mock_obj.call_args_list)  # [call(1, 2)]

这感觉不一致。mock_obj称为mock_obj(self, 1, 2),但mock_obj.call_args == call(1, 2)。它从call_args中删除self参数。如何访问绑定方法实例?


解决方案

with mock.patch.object(A, 'f', autospec=True) as mock_obj:
    A().f(1, 2)

print(mock_obj.call_args_list)  # [call(<__main__.A object at 0x7fb2908fc880>, 1, 2)]

发件人the documentation:

如果您通过autospec=True[...]如果被模拟的函数是从实例中获取的,则它将被转换为绑定方法。它将self作为第一个参数[...]

传入

相关文章