Mock infinite generator in Python

I'm trying to mock an infinite generator function using the mock library. (Or unittest.mock if you have Python 3.3)

Here is a minimum working example of an infinite generator. If I can successfully mock this, then I will hopefully be able to mock the actual function I am using.

import itertools
def infinite_generator():
    thing = itertools.cycle([1, 2])
    while True:
        yield next(thing)

This is what I have tried so far:

import mock
import itertools
mock_func = mock.MagicMock()
mock_func.__iter__.return_value = itertools.cycle([1, 2])

I want mock_func to function exactly as infinite_generator functions.

e.g. I expect to be able to do the following:

>>> a = mock_func()
>>> next(a)
1
>>> next(a)
2
>>> next(a)
1
>>> next(a)
2

etc.

However, at the moment next(a) returns things like

<MagicMock name='mock().__next__()' id='3043937712'>

Answers


Leave out __iter__ here because you don't intend to iterate over the mock_func object itself:

mock_func.__iter__.return_value = itertools.cycle([1, 2])

Instead:

>>> mock_func = mock.Mock()
>>> mock_func.return_value = itertools.cycle([1, 2])
>>> a = mock_func()
>>> next(a)
1
>>> next(a)
2
>>> next(a)
1
>>> next(a)
2

Need Your Help

Initialization Lists in Const Fields dont generate operator=

c++ visual-studio-2010 compiler-construction const initializer-list

For some reason , the compiler cannot generate the operator= for this class because of the initialization of the const field _constFoo, I just wanna know why. Using VS2010.

What JSON library to use in Scala?

json scala

I need to build a JSON string, something like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.