我正在使用 PyCharm Pro,并且我将 Python 解释器配置为来自 Docker 的远程解释器。
我的项目结构是这样的
├── helpers.py
├── package1
│ ├── helper_functions.py
│ └── __init__.py
├── package2
│ ├── helpers_functions.py
│ ├── __init__.py
└── tests
├── conftest.py
├── __init__.py
├── package1
│ ├── conftest.py
│ ├── __init__.py
│ ├── test_helper_functions.py
└── package2
├── conftest.py
├── __init__.py
我正在使用pytest
和pytest-mock
。
我定义了一个测试tests/package1/test_helper_functions.py
来测试package1.helper_functions.helper_func1
调用helpers.some_long_operation
我想模拟的这个函数的函数。
所以我愿意。
# package1/helper_functions.py
from helpers import some_long_operation
def helper_func1():
return some_long_operation()
# tests/package1/test_helper_functions.py
from package1.helper_functions import helper_func1
def test_helper_func1(mocker):
mocker.patch("helpers.some_long_operation", return_value={})
assert helper_func1() == {}
因此,当我执行测试时,原始helpers.some_long_operation
文件会被调用。
但是,当我在测试函数中创建一个夹具并在conftest.py
本地导入该函数时,模拟工作并且不会调用原始函数。
所以我在tests/package1/conftest.py
# tests/package1/conftest.py
import pytest
@pytest.fixture
def mocked_some_long_operation(mocker):
mocker.patch("helpers.some_long_operation", return_value={})
我在测试中使用这个夹具并package1.helper_functions.helper_func1
在函数内部本地导入。
# tests/package1/test_helper_functions.py
def test_helper_func1(mocked_some_long_operation):
from package1.helper_functions import helper_func1
assert helper_func1() == {}
现在我很好,这暂时有效,但我很好奇它为什么会发生。