python - 如何使用pytest-mock检查单元测试中是否调用了函数?

标签 python unit-testing mocking pytest

我有一个单元测试,我想检查是否调用了一个函数。我如何使用 pytestpytest-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

最佳答案

通过

解决错误

分配一个mocked_hellomocked.patch

为模拟函数分配一个side_effect

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

call a real function my_function() and the verify that it called 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'

关于python - 如何使用pytest-mock检查单元测试中是否调用了函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49807449/

相关文章:

c - Google Test C 中的调试、系统函数(fopen、fclose、fread、fwrite、...)和 for 循环

python - 如何通过模拟库模拟套接字对象

unit-testing - 如何对 try-catch block 进行单元测试?

python - Matplotlib:将两个 y 轴围绕零对齐

.net - 可以更改批准测试的文件名

python - Tensorflow:如何将 EagerTensor 转换为 numpy 数组?

java - 使用 Mockito 对 Runnable 进行单元测试

java - 如果使用mock,这种场景下单元测试的目的是什么

python - Django 可以单独运行在 Gunicorn 上吗(没有 Apache 或 nginx)?

python - 使用 noise_shape 的 Keras Dropout