简体   繁体   中英

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.

Now I would like to create pytest and try to create a patch for this generator, I have no luck. 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.

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.' 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.

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