2
與this question類似,但在那裏的答案不適合我在做什麼。如何重置for循環中的模擬迭代器?
我想測試這樣的方法:
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
內,功能將是侵入性的。
這樣做。你搖滾 – TinyTheBrontosaurus