Python Forum
StopIteration exception when mock PostgreSQL connection in several tests - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: StopIteration exception when mock PostgreSQL connection in several tests (/thread-27537.html)



StopIteration exception when mock PostgreSQL connection in several tests - igor87z - Jun-10-2020

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?


RE: StopIteration exception when mock PostgreSQL connection in several tests - ibreeden - Jun-10-2020

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?