python-3.x - Pytest assert_has_calls 用法

标签 python-3.x pytest

我正在尝试使用 pytest 的 mocker fixture ,特别是 assert_has_calls模拟模块中的函数。

当我运行这个:

import os
from mock import call
def test_assert_(mocker):
    mocker.patch('os.remove')

    file_list = [f'file_{i}.txt' for i in range(20)]

    for f in file_list:
        os.remove(f)

    calls = [call(f) for f in file_list]

    assert os.remove.assert_has_calls(calls, any_order=True)

我明白了:
c:\temp
λ python -m pytest test_mock.py
============================= test session starts =============================
platform win32 -- Python 3.6.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: c:\temp, inifile:
plugins: mock-1.6.3
collected 1 items

test_mock.py F

================================== FAILURES ===================================
________________________________ test_assert_ _________________________________

mocker = <pytest_mock.MockFixture object at 0x0000000003ED6BE0>

    def test_assert_(mocker):
        mocker.patch('os.remove')

        file_list = [f'file_{i}.txt' for i in range(20)]

        for f in file_list:
            os.remove(f)

        calls = [call(f) for f in file_list]

>       assert os.remove.assert_has_calls(calls, any_order=True)
E       AssertionError: assert None
E        +  where None = <bound method wrap_assert_has_calls of <MagicMock name='remove' id='65891856'>>([call('file_0.txt'), call('file_1.txt'), call('file_2.txt'), call('file_3.txt'), call('file_4.txt'), call('file_5.txt'), ...], any_order=True)
E        +    where <bound method wrap_assert_has_calls of <MagicMock name='remove' id='65891856'>> = <MagicMock name='remove' id='65891856'>.assert_has_calls
E        +      where <MagicMock name='remove' id='65891856'> = os.remove

test_mock.py:13: AssertionError
========================== 1 failed in 0.17 seconds ===========================

我究竟做错了什么?

如果我手动检查 mock_list,我可以让它工作:
differences = set((str(c) for c in calls)) ^ set( (str(s) for s in os.remove.mock_calls))
assert len(differences) == 0

最佳答案

assert_has_calls 不应该在断言语句中使用,

该函数始终返回 None 并自行执行断言

所以正确的用法是直接调用它

关于python-3.x - Pytest assert_has_calls 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48152560/

相关文章:

python - 使用 py.test 以编程方式收集或创建测试

python - 如何在 django TestCase 中使用 pytest 固定装置

在 Python/Flask 中测试计划任务

python - 断言失败后如何继续单元测试?

python - 使 Python 3.x Slack (slackclient) 使用企业代理

python - 安装python3-dev时出现的问题

python - 从另一个 pip 安装的包针对本地代码运行 py.test 测试

python - ValueError:选项名称已添加 pytest

python - 有没有办法在测试集上计算 PCA 的解释方差?

python-3.x - 无法捕获TweepError异常