繁体   English   中英

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

[英]How do I correctly use mock call_args with Python's unittest.mock?

考虑以下文件:

圣手手榴弹.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 strTypeError: 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 3.8 中引入的一个特性。

3.7 文档没有提到它(而最新的文档有) - 所以你必须在 Python < 3.8 中通过索引访问参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM