从"beginning to end" "over and over again"进行side_effect迭代器循环



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

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

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

但我正在寻找一种更好的写作方式。我尝试了[....]*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)也应该起作用。

最新更新