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

How to get `self` instance in `mock.Mock().call_args`?

我在修补虚拟机时观察到不一致的行为 class:

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)]

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

但是,如果我使用 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 参数。如何访问有界方法实例?

从 Python 控制台,help(mock.MethodType):

Create a bound instance method object.

from unittest import mock

class A:

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


mock_obj = mock.Mock()
a = A()
with mock.patch.object(A, 'f', mock_obj):
    a.f(1, 2)
    print(mock_obj.call_args)

# fixed self in call_args by patching
# with a bound instance method mock
mock_obj = mock.Mock()
with mock.patch.object(A, 'f', mock.MethodType(mock_obj, a)):
    a.f(1, 2)
    print(mock_obj.call_args)

输出:

call(1, 2)
call(<__main__.A object at 0x7ff8223e1dc0>, 1, 2)
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

If you pass autospec=True [...] the mocked function will be turned into a bound method if it is fetched from an instance. It will have self passed in as the first argument [...]