[英]Mock infinite generator in Python
I'm trying to mock an infinite generator function using the mock
library. 我正在尝试使用mock
库来模拟无限生成器函数。 (Or unittest.mock
if you have Python 3.3) (如果你有Python 3.3,还是unittest.mock
)
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. 我希望mock_func
完全像infinite_generator
函数一样运行。
eg 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 然而,在next(a)
的那一刻next(a)
返回类似的东西
<MagicMock name='mock().__next__()' id='3043937712'>
Leave out __iter__
here because you don't intend to iterate over the mock_func
object itself: 在这里省略__iter__
,因为你不打算迭代mock_func
对象本身:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.