python - 如何在 for 循环中重置模拟迭代器?

标签 python unit-testing mocking

类似于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/

相关文章:

python - scipy.ndimage.zoom 结果取决于图像大小

java - 在 JUnit 测试的 @Before 方法中使用断言语句?

python - Pytest mocker.patch 返回 NonCallableMagicMock

java - 模拟创建 ThreadSafeClientConnManager 对象的类

python - 如何在 sqlalchemy 中模拟创建时间?

python - 对数据框进行操作以将行转换为单独的列

python - 无法在 Django Flatpages 中使用 {{MEDIA_URL}}?

python - 在循环 python 中查找下一个迭代

Java:测试通过 Interface、Mockito、JUnit 传递的具体类

python - 如何在请求上下文之外工作时模拟 Flask.g 和 Flask-RESTful.request