[英]How do I correctly use mock call_args with Python's unittest.mock?
[英]How to get `self` instance in `mock.Mock().call_args`?
我在修补虚拟类时观察到不一致的行为:
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_fn(self, 1, 2)
。
但是,如果我使用的是mock.Mock
对象, 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)
:
创建绑定实例方法对象。
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)]
从文档:
如果您传递
autospec=True
[...] ,如果从实例中获取,则autospec=True
函数将变成绑定方法。 它将self
作为第一个参数传入 [...]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.