查看补丁
call_args_list
功能,我发现了一些奇怪的东西。
在 Python3.7 和 python3.11 上运行以下代码会返回不同类型的 call_args_list.kwargs
。<class 'unittest.mock._Call'>
,而在 python3.11 上,类型为 <class 'dict'>
。
官方文档找不到,哪里改的?
使用调用参数的正确方法是什么?假设我想验证在对模拟函数的调用中名为 foo 的
kwarg
是否设置为“bar”(使用 dict 非常简单,使用 _Call 我还没有找到这样做的方法)。
from unittest import mock
def foobar(foo = None, bar = None):
print(f'args: {foo}, {bar}')
l = None
with mock.patch('__main__.foobar') as m:
foobar(foo=1, bar=4)
l = m.call_args_list
type(l[0].kwargs)
我希望这个答案能够满足你的第二个问题;我想这对你来说已经足够了,因为指令
type(l[0].kwargs)
return <class 'unittest.mock._Call'>
的执行也在我的系统中,因为我已经使用 Python 3.6.9 执行了以下代码< Python 3.7 (as you can see in the output of the script execution).
from unittest import mock
import sys
def foobar(foo = None, bar = None):
print(f'args: {foo}, {bar}')
l = None
with mock.patch('__main__.foobar') as m:
foobar(foo=1, bar=4)
l = m.call_args_list
print(sys.version)
print(type(l[0].kwargs))
for args, kwargs in l:
for arg in args:
print(f"arg = {arg}")
for key in kwargs:
print(f"Value of kwarg['{key}'] = {kwargs[key]}")
前面代码执行的输出如下:
3.6.9 (default, Mar 10 2023, 16:46:00)
[GCC 8.4.0]
<class 'unittest.mock._Call'>
Value of kwarg['foo'] = 1
Value of kwarg['bar'] = 4
kwargs
是一本字典,尽管 type(l[0].kwargs)
返回