首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟/ Pytest -模拟

模拟/ Pytest -模拟
EN

Stack Overflow用户
提问于 2017-05-24 18:33:24
回答 1查看 7K关注 0票数 8

由于某些原因,当使用Pytest时,我无法让mock.patch在任何场景中工作。它根本不做修补。我是不正确地使用它,还是我的配置被搞砸了?

base.py

代码语言:javascript
复制
def foo():
    return 'foo'

def get_foo():
    return foo()

test_base.py

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

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-24 19:22:35

这个问题是由于我的导入规范和路径变量之间的关系造成的。如果我在patch参数中指定了整个路径,比如:@mock.patch('<PROJECT_ROOT>.<SUBPACKAGE>.base.foo') where path的父目录作为条目,那么它就有效了。如果没有找到base.foo,我不知道它为什么不抛出一个导入错误。如果它找不到它,我不明白它的范围有什么不同。

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

https://stackoverflow.com/questions/44166134

复制
相关文章

相似问题

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