Python的unittest.mock
允许我修补一个函数,使其返回多个值:
m = Mock(side_effect=["myName", 100, 200])
多次调用m()
将返回"myName", 100
,最后返回200
。
我还可以使用patch.dict
修补dict以返回模拟值,但我所追求的是:
with DictMock(d, return_values=(('a',1), ('a', 2))) as d:
assert d['a'] == 1
assert d['a'] == 2
我创建了一个类:
In [19]: d_
Out[19]: {'a': 1, 'b': 1}
In [20]: class MockDict:
...:
...: def __init__(self, in_dict, values=(), clear=False):
...: self.in_dict = in_dict
...: keys, values = zip(*values)
...: self.keys = list(keys)
...: self.values = list(values)
...:
...: def __enter__(self):
...: self.orig_dict = self.in_dict.copy()
...: return self
...:
...: def __exit__(self, *args):
...:
...: return False
...:
...: def __getitem__(self, key):
...: try:
...: idx = self.keys.index(key)
...: self.keys.pop(idx)
...: val = self.values.pop(idx)
...: return val
...: except ValueError:
...: raise KeyError(key)
...:
In [21]: with MockDict(d_, values=(("a",4),("a",5))) as d:
...: print(d["a"])
...: print(d["a"])
...:
4
5
我知道我的班级有限的方式是不复制原始的键值对......当然可以改进。
你能建议一个更好的方法来实现这个目标吗?
我需要测试以下代码段:
code = self.instance.state['Code']
while code != status:
time.sleep(3)
self.instance.reload()
code = self.instance.state['Code']
我必须两次致电instance.state['Code']
,查看功能代码并转到self.instance.reload()