python - 在模拟上调用 python 内置 dict

标签 python dictionary mocking

我希望能够设置一个模拟,允许我在应用内置 dict 方法时返回一些东西。

我试过使用 __iter__ 无济于事。除了一本空字典,我似乎什么也得不到:

import mock
mocked_object = mock.MagicMock()
mocked_object.__iter__.return_value = [1, 2, 3]
dict(mocked_object)
# {}

最佳答案

来自 dict documentation

If a positional argument is given and it is a mapping object, a dictionary is created with the same key-value pairs as the mapping object. Otherwise, the positional argument must be an iterable object. Each item in the iterable must itself be an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.

MagicMock 对象 公开 keys 方法只是因为是模拟对象,所以 dict() 会考虑它们映射对象。不幸的是,如果我们希望在 dict 上调用 mock 成为具有预定义键值的字典,那么这种方法使用起来有点复杂。以下示例展示了如何使用映射对象 协议(protocol)将dict 转换为预定义字典:

>>> m = MagicMock()
>>> d = {"a":"A", "b":"B", "c":"C"}
>>> m.keys.return_value.__iter__.return_value = ["a", "b", "c"]
>>> m.__getitem__.side_effect = ["A","B","C"]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> #Little bit generic
>>> m.keys.return_value.__iter__.return_value = d.keys()
>>> m.__getitem__.side_effect = lambda k:d[k]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}

两者都有点难读,在我们的测试中,我们希望读起来更简单。

要引导 dict 使用迭代器而不是映射,我们可以从 mock 中删除 keys 方法并设置 __iter__.return_value:

>>> del m.keys
>>> m.__iter__.return_value = [("a","A"),("b","B"),("c","C")]
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}
>>> #Little bit generic
>>> m.__iter__.return_value = d.items()
>>> dict(m)
{'a': 'A', 'c': 'C', 'b': 'B'}

恕我直言,这是一种设置模拟并从 dict 调用中获取预定义字典的简单而巧妙的方法。

关于python - 在模拟上调用 python 内置 dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361564/

相关文章:

c# - AutoMapper 模拟 UnitOfWork 失败

python - 使用 Python 删除对象列表中的重复项

python - matplotlib 轴 ('tight' )不起作用?

python - 如何从 3d NumPy 数组绘制单个像素值?

python - 使用 pandas、python 创建字典,返回错误 : "return self._engine.get_loc(key)"

java - 静态方法的 doAnswer - PowerMock

python - 在django中迭代manyToOne关系执行数百个查询

python - 如何将字符串拆分为字典并返回特定的字典值?

python - 从数组值过滤字典

javascript - 从主方法调用并包含 http 请求授权的子方法的单元测试