我使用的是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
中定义了一个测试来测试调用函数helpers.some_long_operation
的package1.helper_functions.helper_func1
这个函数是我想要模拟的
我也是
# 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
中创建一个fixture并在测试函数中本地导入该函数时,mock可以工作,并且不会调用原始函数
所以我在tests/package1/conftest.py
中创建了一个fixture
# 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() == {}
现在我还可以,但我很好奇为什么会这样。
目前没有回答
相关问题 更多 >
编程相关推荐