与this question类似,但那里的答案不足以满足我的目标。
我试图测试这样的方法:
import mock
def stack_overflow_desired_output():
print_a_few_times(['upvote', 'this', 'question!'])
def stack_overflow_mocked():
the_mock = mock.Mock()
the_mock.__iter__ = mock.Mock(return_value=iter(["upvote", "this", "question"]))
print_a_few_times(the_mock)
def print_a_few_times(fancy_object):
for x in [1, 2, 3]:
for y in fancy_object:
print("{}.{}".format(x, y))
当我致电stack_overflow_desired_output()
时,我明白了:
1.upvote
1.this
1.question!
2.upvote
2.this
2.question!
3.upvote
3.this
3.question!
但是当我打电话给stack_overflow_mocked()
时,我只能得到这个:
1.upvote
1.this
1.question!
有没有办法让迭代器在for循环结束时耗尽时重置?将重置放在print_a_few_times
,函数as described in the aforementioned question内,将是侵入性的。
答案 0 :(得分:1)
将模拟对象包裹在实际列表的__iter__
方法周围。
def stack_overflow_mocked():
the_mock = mock.Mock()
the_mock.__iter__ = mock.Mock(wraps=["upvote", "this", "question"].__iter__)
print_a_few_times(the_mock)