首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用pytest-mock检查单元测试中是否调用了函数?

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

Stack Overflow用户
提问于 2018-04-13 08:01:20
回答 2查看 16.7K关注 0票数 16

我有一个单元测试,我想在其中检查函数是否被调用。如何使用pytestpytest-mock库做到这一点?

例如,下面是一个单元测试test_hello.py。在这个测试中,我调用了函数my_function,并希望验证它是否使用给定的参数调用了hello

代码语言:javascript
复制
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')

上面的代码返回以下错误:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-04-13 10:00:19

通过以下方式解决错误

mocked.patch分配mocked_hello

side_effect分配给模拟函数

代码语言:javascript
复制
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

代码语言:javascript
复制
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'
票数 10
EN

Stack Overflow用户

发布于 2021-10-18 17:30:21

我认为只需对OP的代码进行最小程度的更改,就可以完全限定被模拟函数的名称。例如,如果代码在一个名为test.py的文件中

代码语言:javascript
复制
import pytest

def hello(name):
    return f'Hello {name}'

def my_function():
    hello('Sam')

def test_hello(mocker):
    mocker.patch('test.hello')
    my_function()
    hello.assert_called_once_with('Sam')

(我假设test.py位于sys.path的某个地方。)

但是,我认为最好将测试函数更改为:

代码语言:javascript
复制
def test_hello(mocker):
    mocked_func = mocker.patch('test.hello')
    my_function()
    mocked_func.assert_called_once_with('Sam')

这种形式对我来说似乎更清晰,不太可能在更复杂的代码中引发AttributeError。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49807449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档