我如何在Python的unittest.mock中正确使用模拟call_args?

问题描述 投票:2回答:1

请考虑以下文件:

holy_hand_grenade.py

def count(one, two, five='three'):
    print('boom')

test_holy_hand_grenade.py

from unittest import mock
import holy_hand_grenade

def test_hand_grenade():
    mock_count = mock.patch("holy_hand_grenade.count", autospec=True)
    with mock_count as fake_count:
        fake_count(1, 2, five=5)

        # According to https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.call_args
        # this should work
        assert fake_count.call_args.kwargs['five'] == 5

根据文档,call_args应该为:

这可以是None(如果尚未调用该模拟),也可以是最后一次使用该模拟的参数。这将采用元组的形式:第一个成员(也可以通过args属性进行访问)是使用该模拟程序调用的任何有序参数(或空的元组),第二个成员也可以是通过kwargs属性访问的是任何关键字参数(或空字典)。

(重点是我的)

但是这在我的脸上冒出,TypeError: tuple indices must be integers or slices, not str

嗯。否?

我真的不明白,如果这是一个调用对象,那是因为,

assert isinstance(fake_count.call_args, (mock._Call,))

通过,应该有kwargs和args。而且...嗯,有点。但是它们似乎实际上并不是正确的东西:

assert isinstance(fake_count.call_args.kwargs, (mock._Call,))  #this works
assert isinstance(fake_count.call_args.kwargs, (dict,))  # doesn't work

我在这里做错了什么?

python python-3.x mocking python-mock
1个回答
0
投票
[这是this issue中的Python 3.8中引入的功能。

[3.7 documentation没有提到它(而newest docs却提到了-因此您必须在Python <3.8中通过索引访问参数。

© www.soinside.com 2019 - 2024. All rights reserved.