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

2024-04-27 22:41:04 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下文件:

神圣手榴弹.py

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

测试手榴弹。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应该是:

This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with. This will be in the form of a tuple: the first member, which can also be accessed through the args property, is any ordered arguments the mock was called with (or an empty tuple) and the second member, which can also be accessed through the kwargs property, is any keyword arguments (or an empty dictionary).

(强调矿山)

但是这在我的脸上炸开了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

我做错了什么


Tags: orthecountwithargsassertbeunittest