我希望能够设置一个模拟,允许我在应用内置 dict
方法时返回一些东西。
我试过使用 __iter__
无济于事。除了一本空字典,我似乎什么也得不到:
import mock
mocked_object = mock.MagicMock()
mocked_object.__iter__.return_value = [1, 2, 3]
dict(mocked_object)
# {}
最佳答案
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/