python - 在文件顶部导入的模拟函数

标签 python testing mocking pytest

我正在尝试在一个项目中进行测试,但我遇到了一个奇怪的错误。

我用下面的玩具示例重现了非常相似的情况:

这是文件结构:

.
├── some_package
│   ├── __init__.py
│   └── some_file.py
└── test_mock_patch.py
"""some_package/some_file.py"""

# when I import here, the test fails
from math import floor


def some_func(a, b):
    # if I import here, the test passes
    # from math import floor
    return floor(a + b)
"""test_mock_patch.py"""

import pytest
from unittest import mock
from some_package.some_file import some_func


@pytest.fixture
def mock_floor():
    with mock.patch('math.floor', autospec=True) as m:
        yield m


def test_some_func(mock_floor):
    some_func(1.1, 1)
    assert mock_floor.call_count == 1

使用的命令:pytest -v -s test_mock_patch.py​​

错误:

enter image description here

为什么当我在函数内部导入时,test_some_func 通过,而当我在顶部导入时,测试失败?

预先感谢您帮助解释 mock.patch

的这种行为

版本:

  • python 3.7.3
  • pytest 4.4.1

最佳答案

这是一个最小的示例,说明如何通过更改 test_mock_patch.py​​ 文件来获得所需的结果。

import pytest
from some_package.some_file import some_func


def test_some_func(monkeypatch):
    with monkeypatch.context() as mc:
        mc.setattr('some_package.some_file.floor', lambda x: 'foo')
        res = some_func(1.1, 1)
        assert res == 'foo'

就像我在评论中提到的,您需要在导入函数的地方修补它。

关于python - 在文件顶部导入的模拟函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56176467/

相关文章:

java - Mockito 非 stub 函数

angular - 无法读取 Angular Testing 模拟的属性 'subscribe'

mocking - 如何在 Mockoon 响应中迭代分解的(数组)查询参数?

python - 如何使用静态变量、自定义 getter 和 setter 扩展 SWIG 中的结构?

PHPunit:测试问题

python - Pygame "No module called pygame.base"

unit-testing - 自动化测试用例执行 - 何时停止

unit-testing - 什么是测试纯函数的更好方法?

python - 在给定的时间和分钟使用 crontab 时,周期性任务不起作用

python - python 中的宏