Pytest assert_has_calls用法

时间:2018-01-08 14:42:43

标签: python-3.x pytest

我正在尝试使用pytest的mocker fixture,特别是mock模块中的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

1 个答案:

答案 0 :(得分:2)

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

该函数总是返回None并且自己执行断言

所以正确的用法就是调用它