Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在for循环中重置模拟迭代器?_Python_Unit Testing_Mocking - Fatal编程技术网

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)

成功了。你真厉害