简体   繁体   English

使unittest.mock.Mock()返回字典列表

[英]Make unittest.mock.Mock() return list of dicts

I'm trying to mock a call of method extra_get() which usually returns a list of dicts. 我试图模拟方法extra_get()的调用,该方法通常返回字典列表。 As far as I understand from the Mock docs , if I want to return iterable, I should set side_effect param. 据我从Mock 文档了解,如果我想返回iterable,则应设置side_effect参数。

client.extra_get = mock.Mock(
            **{'side_effect': [{'foo': 'bar'}]})

But then the following code calls that mocked method: 但是随后,以下代码调用了该模拟方法:

extra = client.extra_get(request, type_id)
result = {x.key: x.value for x in extra}
return result

And the dict comprehention fails because extra there is not a list, but dict {'foo': 'bar'} . 而且因为字典理解中失败, extra还没有一个清单,但字典{'foo': 'bar'} What I'm doing wrong? 我做错了什么? How can I make Mock method return a list of dicts? 如何使Mock方法返回字典列表?

with mock.patch.object(client, 'extra_get', return_value=[{...}, {...}]) as mock_get:
  # fill in the rest

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

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