我有一个单元测试,我想检查一个函数是否被调用。如何使用pytest
和pytest-mock
库执行此操作?
例如,这是一个单元测试test_hello.py
。在此测试中,我调用函数my_function
并想要验证它是否使用给定参数调用hello
。
def hello(name):
return f'Hello {name}'
def my_function():
hello('Sam')
def test_hello(mocker):
mocker.patch('hello')
my_function()
hello.assert_called_once_with('Sam')
上面的代码返回以下错误:
target = 'hello'
def _get_target(target):
try:
> target, attribute = target.rsplit('.', 1)
E ValueError: not enough values to unpack (expected 2, got 1)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1393: ValueError
During handling of the above exception, another exception occurred:
mocker = <pytest_mock.MockFixture object at 0x109c5e978>
def test_hello(mocker):
> mocker.patch('hello')
test_hello.py:8:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytest_mock.py:156: in __call__
return self._start_patch(self.mock_module.patch, *args, **kwargs)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/pytest_mock.py:134: in _start_patch
p = mock_func(*args, **kwargs)
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1544: in patch
getter, attribute = _get_target(target)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
target = 'hello'
def _get_target(target):
try:
target, attribute = target.rsplit('.', 1)
except (TypeError, ValueError):
raise TypeError("Need a valid target to patch. You supplied: %r" %
> (target,))
E TypeError: Need a valid target to patch. You supplied: 'hello'
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/mock.py:1396: TypeError
答案 0 :(得分:2)
通过
解决错误将mocked_hello
分配给mocked.patch
将side_effect
分配给模拟的func
def bonjour(name):
return 'bonjour {}'.format(name)
def hello(name):
return 'Hello {}'.format(name)
def my_function():
return hello('Sam')
def test_hellow_differnt_from_module(mocker):
# mocked func with `test_hello.py` as module name
mocked_hello = mocker.patch('test_hello.hello')
# assign side_effect to mocked func
mocked_hello.side_effect = bonjour
# the mocked func return_value changed by side_effect
assert mocked_hello('Sam') == 'bonjour Sam'
# the mocked func called with Sam, but with different return value
mocked_hello.assert_called_with('Sam')
调用一个真实的函数my_function()并验证它是否调用了hello
def test_my_function(mocker):
mocker.patch('test_hello.hello', side_effect=bonjour)
mf = my_function()
hello.assert_called_with('Sam')
assert mf == 'bonjour Sam'