Python Forum

Full Version: StopIteration exception when mock PostgreSQL connection in several tests
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi
I mock connect to Postgresql(psycopg2) in two tests

from unittest.mock import patch, MagicMock

with patch('psycopg2.pool.ThreadedConnectionPool') as mock_connect:
    mock_connect().getconn.return_value.cursor.return_value = mock_cursor
In first test set data in side_effect, in second using return_value:

# first test
mock_cursor = MagicMock()
mock_cursor.fetchall.side_effect = mock_data

# second test
mock_cursor = MagicMock()
mock_cursor.fetchall.return_value = data
One by one works fine.

If I run
'python -m unittest discover -s test'
First test(side_effect) works fine, second test failed, StopIteration. In second test mock-object trying get data from side_effect from first test. I'm trying set side_effect in both test, the same result, StopIteration exception in second test. I'm trying ti give different names(name=) to patch and MagicMock, the same result.

How can I mock one object(psycopg2.pool.ThreadedConnectionPool) and one function(fetchall) mock in several test using 'python -m unittest discover'? It's possible with unittest.mock?
I know nothing of mock or MagicMock, but I know something of databases and how to use cursors.
You get a StopIterarion exception, I think this means all rows are already fetched. So my guess is you have to close the cursor after "first test".
Does that help?