Python 如何在for循环中重置模拟迭代器?
与类似,但其中的答案不足以说明我在做什么 我正在尝试测试这样一种方法:Python 如何在for循环中重置模拟迭代器?,python,unit-testing,mocking,Python,Unit Testing,Mocking,与类似,但其中的答案不足以说明我在做什么 我正在尝试测试这样一种方法: 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=ite
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\u overflow\u required\u output()
时,我得到以下结果:
1.upvote
1.this
1.question!
2.upvote
2.this
2.question!
3.upvote
3.this
3.question!
1.upvote
1.this
1.question!
但是当我调用stack\u overflow\u mock()
时,我只得到以下结果:
1.upvote
1.this
1.question!
2.upvote
2.this
2.question!
3.upvote
3.this
3.question!
1.upvote
1.this
1.question!
有没有办法让迭代器在for循环结束时耗尽时自行重置?将重置放在
打印功能的内部几次将是侵入性的。将模拟对象环绕在实际列表的\uuuuuuuuuuuu
方法周围
def stack_overflow_mocked():
the_mock = mock.Mock()
the_mock.__iter__ = mock.Mock(wraps=["upvote", "this", "question"].__iter__)
print_a_few_times(the_mock)
成功了。你真厉害