使side_effect迭代器循环从“开始到结束”“一遍又一遍”

时间:2012-09-10 14:05:14

标签: python mocking python-2.7

我必须说我是 python mock 的新手。 我有一个 side_effect迭代器

myClass.do.side_effect = iter([processStatus, memoryStatus, processStatus, memoryStatus, processStatus, memoryStatus, processStatus, memoryStatus])

以上按预期工作,测试用例通过

但我正在寻找一种更好的方法来写这篇文章。 我尝试了[....]*4但没有效果。

我该怎么办?简单地说,一旦迭代器结束就让它从头开始。

1 个答案:

答案 0 :(得分:4)

我认为你可以在这里使用itertools.cycle,如果你想要“一遍又一遍”:

>>> s = range(3)
>>> s
[0, 1, 2]
>>> from itertools import cycle
>>> c = cycle(s)
>>> c
<itertools.cycle object at 0xb72697cc>
>>> [next(c) for i in range(10)]
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0]
>>> c = cycle(['pS', 'mS'])
>>> [next(c) for i in range(10)]
['pS', 'mS', 'pS', 'mS', 'pS', 'mS', 'pS', 'mS', 'pS', 'mS']

或者,正如@mgilson所说,如果你想要有限数量的2元素术语(我不完全确定你需要什么样的数据格式):

>>> from itertools import repeat
>>> repeat([2,3], 3)
repeat([2, 3], 3)
>>> list(repeat([2,3], 3))
[[2, 3], [2, 3], [2, 3]]

但正如评论中所述,iter([1,2,3]*n)也应该有用。