pytestmock:如果在没有fixture的情况下进行模拟,并且导入是全局的,则模拟不起作用

2024-05-08 15:15:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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

我正在使用pytestpytest-mock

我在tests/package1/test_helper_functions.py中定义了一个测试来测试调用函数helpers.some_long_operationpackage1.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() == {}

现在我还可以,但我很好奇为什么会这样。


Tags: 函数pytesthelperinitpytesttestssome