python - Pytest 适用于旧模拟,但不适用于 unittest.mock

标签 python unit-testing python-3.x mocking pytest

我正在将一些代码从 Python 2 移植到 3,而 py.test 不能很好地与来自 unittest.mock< 的 patch 装饰器一起玩。当我使用 patch 装饰器将模拟传递给测试函数的参数时,py.test 反而将该参数解释为固定装置,并且无法设置测试。

这里有一个人为的例子,希望能说明问题:

@patch('my_module.my_func')
def test_my_func(mock_func):
    mock_func()
    mock_func.assert_called_once_with()

运行 py.test 后,错误消息如下所示:

E       fixture 'my_func' not found
>       available fixtures: cache, capfd, capsys, doctest_namespace, monkeypatch, pytestconfig, record_xml_property, recwarn, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

这是发生此故障的唯一情况。如果我显式调用测试(即运行 test_my_func()),没有错误。如果我使用其他任何一种修补技术修补 my_func,都不会出错。如果我从 mock 而不是 unittest.mock 导入补丁,没有错误。

只有在使用 py.test 运行我的测试时,使用 unittest.mock,并在发生这种情况时使用装饰器进行修补。

我正在运行 Python 3.4.5。

最佳答案

是的,不支持模拟装饰器。 这还不错——通过装饰器更改函数签名被认为是个坏主意。 但是您仍然可以使用 with mock.patch(...) 语法。

还有一个选项是 pytest-mock带有非常干净的 api 的插件,用于模拟:

def test_foo(mocker):
    # all valid calls
    mocker.patch('os.remove')
    mocker.patch.object(os, 'listdir', autospec=True)
    mocked_isfile = mocker.patch('os.path.isfile')

关于python - Pytest 适用于旧模拟,但不适用于 unittest.mock,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39169563/

相关文章:

python - 将字典的字符串表示形式转换为实际的字典

python - 如何在参数中使用关键字为 "self"的 Python 函数

python-3.x - 使用具有 logloss 和 RFECV 的不平衡数据集的问题

python - 如果数字介于两个值之间则返回 [Python]

python-3.x - H2O 类型错误 : 'training_frame' must be a valid H2OFrame

python - 从哪里可以获得 python27.dll 和 wxmsw dll

python - 在 Python 中延迟评估/惰性评估

c# - 使用 Moq 和 Xunit 测试接口(interface)

c++ - 使用 Google Mock 的 Mock 方法实现

c# - 如何使用 NUnit 在 C# 中对线程安全通用列表进行单元测试?