简体   繁体   English

重置python模拟生成器返回值

[英]Reset a python mock generator return value

How can I "reset" a method that returns a generator. 如何“重置”返回生成器的方法。 If I mock this method but use the parent class twice in a method under test, the first call consumes the generator and the second call has no data. 如果我模拟此方法,但在测试的方法中两次使用父类,则第一个调用将消耗生成器,而第二个调用将没有数据。 Sample code below. 下面的示例代码。 The two calls to get_values should return the same (mocked) list. 两次调用get_values应该返回相同的(模拟的)列表。

import mock

class MyTestClass(object):
    def __init__(self, param):
        self.param = param

    def get_values(self):
        return self.param


class MyTestRunner(object):
    def __init__(self):
        pass

    def run(self):
        cls = MyTestClass(2)
        print list(cls.get_values())
        cls = MyTestClass(3)
        print  list(cls.get_values())


with mock.patch.object(MyTestClass, 'get_values') as mock_class:
    mock_class.return_value = ({'a': '10', 'b': '20'}).iteritems()
    m = MyTestRunner()
    m.run()

Expected: 预期:

[('a', '10'), ('b', '20')]
[('a', '10'), ('b', '20')]

Actual: 实际:

[('a', '10'), ('b', '20')]
[]

How's this? 这个怎么样?

mock_class.side_effect = lambda x: {'a': '10', 'b': '20'}.iteritems()

Side effect occurs every call thus recreates every time. 每次调用都会发生副作用,因此每次都会重新创建。

You can even set the dict before like so 您甚至可以像这样设置字典

my_dict = {'a': '10', 'b': '20'}
mock_class.side_effect = lambda x: my_dict.iteritems()

The return value of side_effect is the result of the call. side_effect的返回值是调用的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM