如何确定是否使用Python嘲笑方法调用了方法,但不替换函数体?

问题描述 投票:0回答:1

[有许多示例显示了如何断言已使用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()创建的记录进行测试。是的,我同意,但是我只是想确定是否有可能按照我的问题去做。

python python-mock
1个回答
0
投票

使用Mockwraps 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')]
© www.soinside.com 2019 - 2024. All rights reserved.