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内将具有侵入性。

最佳答案

将模拟对象环绕实际列表的__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)

关于python - 如何在for循环中重置模拟迭代器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45494371/

10-12 00:43