Pytest with mock / pytest-mock

时间:2017-05-24 18:33:25

标签: python unit-testing pytest

出于某种原因,我无法在使用Pytest的任何场景中使用mock.patch。它根本不做补丁。我错误地使用它还是搞砸了我的配置?

base.py

def foo():
    return 'foo'

def get_foo():
    return foo()

test_base.py

import pytest
import mock
from pytest_mock import mocker

from base import get_foo

@mock.patch('base.foo') 
def test_get_foo(mock_foo):
    mock_foo.return_value = 'bar'
    assert get_foo() == 'bar'

def test_get_foo2(mocker):
    m = mocker.patch('base.foo', return_value='bar')
    assert get_foo() == 'bar'

def test_get_foo3():
    with mock.patch('base.foo', return_value='bar') as mock_foo:
        assert get_foo() == 'bar'

pytest结果

============================================================= test session starts =============================================================
platform linux2 -- Python 2.7.13, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: /projects/git/ABC/query, inifile:
plugins: mock-1.6.0
collected 13 items 

test_base.py .....FFF.....

================================================================== FAILURES ===================================================================
________________________________________________________________ test_get_foo _________________________________________________________________

mock_foo = <MagicMock name='foo' id='140418877133648'>

    @mock.patch('base.foo')
    def test_get_foo(mock_foo):
        mock_foo.return_value = 'bar'
>       assert get_foo() == 'bar'
E       AssertionError: assert 'foo' == 'bar'
E         - foo
E         + bar

test_base.py:67: AssertionError
________________________________________________________________ test_get_foo2 ________________________________________________________________

mocker = <pytest_mock.MockFixture object at 0x7fb5d14bc210>

    def test_get_foo2(mocker):
        m = mocker.patch('base.foo', return_value='bar')
>       assert get_foo() == 'bar'
E       AssertionError: assert 'foo' == 'bar'
E         - foo
E         + bar

test_base.py:71: AssertionError
________________________________________________________________ test_get_foo3 ________________________________________________________________

    def test_get_foo3():
        with mock.patch('base.foo', return_value='bar') as mock_foo:
>           assert get_foo() == 'bar'
E           AssertionError: assert 'foo' == 'bar'
E             - foo
E             + bar

test_base.py:75: AssertionError

1 个答案:

答案 0 :(得分:6)

问题是由于我的导入规范和PATH变量之间的关系。如果我在patch参数中指定了整个路径,例如:@mock.patch('<PROJECT_ROOT>.<SUBPACKAGE>.base.foo')其中PATH的父目录为条目,则它起作用。我不知道为什么在没有找到base.foo的情况下不会抛出导入错误。如果它没有找到它,我不明白范围是如何不同的。