【问题标题】:Mocking function imported at the top of the file在文件顶部导入的模拟函数
【发布时间】:2019-05-16 20:54:34
【问题描述】:

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

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

这是文件结构:

.
├── 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

错误:

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

提前感谢您为解释mock.patch的这种行为提供任何帮助

版本:

  • Python 3.7.3
  • pytest 4.4.1

【问题讨论】:

  • 你需要模拟some_package.some_file.math.floor,因为它是从那里导入的,尽管如果你使用pytest,你应该使用monkeypatch夹具
  • 但是为什么当我在函数内部导入时它起作用了?
  • 因为你在同一个文件中导入它,所以它知道去哪里看
  • 在这种情况下,您将如何使用monkeypatch 而不是mock.patch

标签: python testing mocking pytest


【解决方案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'

就像我在 cmets 中提到的,您需要在导入函数的地方打补丁。

【讨论】:

    猜你喜欢
    • 2016-03-16
    • 2019-09-19
    • 2016-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 2017-08-16
    相关资源
    最近更新 更多