【问题标题】:How to reset mock iterator inside a for loop?如何在 for 循环中重置模拟迭代器?
【发布时间】:2017-08-03 20:57:07
【问题描述】:

类似于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 循环结束时自行重置?将 reset 放在 print_a_few_times, 函数 as described in the aforementioned question 内部将具有侵入性。

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    将您的模拟对象包裹在实际列表的 __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)
    

    【讨论】:

    • 做到了。你摇滚
    猜你喜欢
    • 2011-09-17
    • 2022-12-08
    • 2021-06-30
    • 2018-09-12
    • 2022-12-16
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    相关资源
    最近更新 更多