简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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