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

the*_*lse 1 python mocking python-2.7

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

myClass.do.side_effect = iter([processStatus, memoryStatus, processStatus, memoryStatus, processStatus, memoryStatus, processStatus, memoryStatus])
Run Code Online (Sandbox Code Playgroud)

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

但我正在寻找一种更好的方式来写这个。我试过[....]*4哪个不起作用。

我该怎么做?简单地说,就是让迭代器在结束时从头开始。

DSM*_*DSM 5

我想你可以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']
Run Code Online (Sandbox Code Playgroud)

或者,正如@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]]
Run Code Online (Sandbox Code Playgroud)

但正如评论中所指出的,也iter([1,2,3]*n)应该有效。