Reputation: 1679
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')]
[]
Upvotes: 3
Views: 1750
Reputation: 26901
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.
Upvotes: 3