gpt4 book ai didi

python-3.x - Pytest assert_has_calls 用法

转载 作者:行者123 更新时间:2023-12-01 11:17:59 24 4
gpt4 key购买 nike

我正在尝试使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com