如何确定方法是否使用 Python mock 调用但不替换函数体?
How to determine if method is called using Python mock but does not replace the function body?
有很多示例展示了如何断言已使用 Mock 调用了一个方法,例如。 assert_called_with()
,但都涉及用Mock实例替换方法
我想要的有点不同,我希望函数在不替换函数体的情况下正常执行,但仍然想断言函数是否已被调用。
例如。
def dosomething(...)
# creates records that I will test later on.
....
def execute():
....
dosomething()
在我的测试中
def test_a(...):
with patch(dosomething...) as mocked:
execute()
mocked.assert_called_with()
我知道我可以针对 dosomething()
创建的记录进行测试。是的,我同意,但我只是想看看是否可以按照我的问题去做。
使用 Mock
的 wraps
kwarg 并传递原始方法。
例如,
>>> from unittest import mock
>>> def hi(name): print('hi', name)
>>> mock_hi = mock.Mock(wraps=hi)
包装的函数被模拟调用。
>>> mock_hi('Bob')
hi Bob
但它仍然是一个记住电话的模拟。
>>> mock_hi.call_args_list
[call('Bob')]
回想一下,patch()
会将额外的 kwargs 传递给它生成的 Mock
,因此您也可以在此处使用 wraps
参数。例如,
>>> with mock.patch('builtins.float', wraps=float) as mock_float:
... x = float('inf')
... print(x) # If we hadn't wrapped, x would be a mock.
... print(mock_float.call_args_list)
...
inf
[call('inf')]
有很多示例展示了如何断言已使用 Mock 调用了一个方法,例如。 assert_called_with()
,但都涉及用Mock实例替换方法
我想要的有点不同,我希望函数在不替换函数体的情况下正常执行,但仍然想断言函数是否已被调用。
例如。
def dosomething(...)
# creates records that I will test later on.
....
def execute():
....
dosomething()
在我的测试中
def test_a(...):
with patch(dosomething...) as mocked:
execute()
mocked.assert_called_with()
我知道我可以针对 dosomething()
创建的记录进行测试。是的,我同意,但我只是想看看是否可以按照我的问题去做。
使用 Mock
的 wraps
kwarg 并传递原始方法。
例如,
>>> from unittest import mock
>>> def hi(name): print('hi', name)
>>> mock_hi = mock.Mock(wraps=hi)
包装的函数被模拟调用。
>>> mock_hi('Bob')
hi Bob
但它仍然是一个记住电话的模拟。
>>> mock_hi.call_args_list
[call('Bob')]
回想一下,patch()
会将额外的 kwargs 传递给它生成的 Mock
,因此您也可以在此处使用 wraps
参数。例如,
>>> with mock.patch('builtins.float', wraps=float) as mock_float:
... x = float('inf')
... print(x) # If we hadn't wrapped, x would be a mock.
... print(mock_float.call_args_list)
...
inf
[call('inf')]