简体   繁体   English

如何在 python 中模拟生成器

[英]How to mock a generator in python

I have a generator that yields a string value and in my main app.py I utilize them.我有一个生成yields a string值的生成器,在我的主 app.py 中使用它们。

Now I would like to create pytest and try to create a patch for this generator, I have no luck.现在我想创建 pytest 并尝试为这个生成器创建一个补丁,我没有运气。 Can anyone suggest a better working approach?谁能建议更好的工作方法? I'm followed the StackOverflow previous question and solution but still didn't manage to get it done.我关注了 StackOverflow 之前的问题和解决方案,但仍然没有设法完成它。

def test_index_route():
    with patch("main._method") as mock_method:
        mock_method.iter.return_value = iter(['1234'])
        response = app.test_client().get('/')

        assert response.status_code == 200
        assert response.data.decode('utf-8') == 'hello world version 1234.' 

this gives assert failed as E assert "hello wo R...0854476448'>." == 'hello world version 1234.'这给出了 assert failed as E assert "hello wo R...0854476448'>." == 'hello world version 1234.' E assert "hello wo R...0854476448'>." == 'hello world version 1234.' hello world version <MagicMock name='_version_if_file_exists().__next__()' id='140400854476448'>.

mock.method.return_value = iter(['1234'])

This is a lie, but Python treats generators and functions that return an iterator the same way.这是一个谎言,但 Python 以相同的方式对待返回迭代器的生成器和函数。

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

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