Pytest assert_has_calls用法

Gre*_*uhn 3 pytest python-3.x

我正在尝试使用pytest的模拟程序夹具,特别是模拟模块中的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)
Run Code Online (Sandbox Code Playgroud)

我得到这个:

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 ===========================
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

如果我手动检查了mock_list,则可以使其正常工作:

differences = set((str(c) for c in calls)) ^ set( (str(s) for s in os.remove.mock_calls))
assert len(differences) == 0
Run Code Online (Sandbox Code Playgroud)

Ron*_*nny 5

assert_has_calls不应在assert语句中使用,

该函数确实总是返回None并自行执行断言

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