python - 模拟来自同一个 python 模块的相对导入

标签 python mocking python-unittest

给定以下包结构:

# tree
.
├── setup.py
└── src
    └── package
        ├── bar.py
        ├── __init__.py
        └── test.py

以及以下代码:

# bar.py
from glob import glob

def baz():
    return glob('./*')

test.py 中执行相对导入时,如何正确模拟对 bar.baz 中的 glob 的调用?我尝试了多种方法,包括

# test.py
from unittest import mock
from .bar import baz

@mock.patch('package.bar.baz')
def test_baz(mock_baz):
    mock_baz.return_value = ['fizz']
    assert "fizz" in baz()


# pytest src/package/test.py
============================= test session starts ==============================
platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /home/bewing/package, inifile:
plugins: cov-2.6.0, pylama-7.6.6, celery-4.2.1
collected 1 item

src/package/test.py F                                                    [100%]

=================================== FAILURES ===================================
___________________________________ test_baz ___________________________________

mock_baz = <MagicMock name='baz' id='140447846207104'>

    @mock.patch('package.bar.baz')
    def test_baz(mock_baz):
        mock_baz.return_value = ['fizz']
>       assert "fizz" in baz()
E       AssertionError: assert 'fizz' in ['./setup.py', './src']
E        +  where ['./setup.py', './src'] = baz()

src/package/test.py:7: AssertionError
=========================== 1 failed in 0.33 seconds ===========================

# test.py
from unittest import mock
from .bar import baz

    @mock.patch('.bar.baz')
    def test_baz(mock_baz):
        mock_baz.return_value = ['fizz']
        assert "fizz" in baz()

# pytest src/package/test.py
============================= test session starts ==============================
platform linux -- Python 3.7.1, pytest-4.0.0, py-1.7.0, pluggy-0.8.0
rootdir: /home/bewing/package, inifile:
plugins: cov-2.6.0, pylama-7.6.6, celery-4.2.1
collected 1 item

src/package/test.py F                                                    [100%]

=================================== FAILURES ===================================
___________________________________ test_baz ___________________________________

args = (), keywargs = {}, extra_args = [], entered_patchers = []
exc_info = (<class 'ValueError'>, ValueError('Empty module name'), <traceback object at 0x7effb803a4c8>)
patching = <unittest.mock._patch object at 0x7effbab69a58>

    @wraps(func)
    def patched(*args, **keywargs):
        extra_args = []
        entered_patchers = []

        exc_info = tuple()
        try:
            for patching in patched.patchings:
>               arg = patching.__enter__()

/home/bewing/.pyenv/versions/3.7.1/lib/python3.7/unittest/mock.py:1183:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/home/bewing/.pyenv/versions/3.7.1/lib/python3.7/unittest/mock.py:1239: in __enter__
    self.target = self.getter()
/home/bewing/.pyenv/versions/3.7.1/lib/python3.7/unittest/mock.py:1409: in <lambda>
    getter = lambda: _importer(target)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

target = '.bar'

    def _importer(target):
        components = target.split('.')
        import_path = components.pop(0)
>       thing = __import__(import_path)
E       ValueError: Empty module name

/home/bewing/.pyenv/versions/3.7.1/lib/python3.7/unittest/mock.py:1092: ValueError
=========================== 1 failed in 0.47 seconds ===========================

最佳答案

您应该修补glob而不是baz。像这样的东西:

@mock.patch('package.bar.glob')
def test_baz(mock_glob):
    mock_glob.return_value = ['fizz']
    assert "fizz" in baz()

关于python - 模拟来自同一个 python 模块的相对导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54680532/

相关文章:

python - 如何在 python 中模拟 self ?

unit-testing - Mockito - thenCallRealMethod() 在 void 函数上

Python Flask unittest 无法为 GET 请求设置 header

Python pytest-mock assert_has_calls

python - 在 Go 中创建哈希

python - Stripe - 检查卡余额

python - 如何更改登录 Twitter 用户的 Django Social 身份验证密码

python - 在 Flask + Google App Engine 上启用 SSL

python - py.test -- 模拟常量并在测试函数中引发异常

python - 如何修补 ConfigParser 键/值?