Python Forum
StopIteration exception when mock PostgreSQL connection in several tests
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
StopIteration exception when mock PostgreSQL connection in several tests
#1
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?
Reply
#2
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?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need consultation about running tests for a Github repo Askic 1 770 Apr-29-2026, 03:31 AM
Last Post: alvacurdy
  Python com PostgreSQL Anderson_Nup 0 520 Aug-01-2025, 06:38 PM
Last Post: Anderson_Nup
  How to Connect to PostgreSQL Through Jump Server and SSH Tunnel using Python? nishans 1 6,179 Jan-02-2024, 10:37 AM
Last Post: khanzain
  unittest.mock for an api key silver 3 3,080 Aug-29-2022, 03:52 PM
Last Post: ndc85430
  Mock obj - How to call the side_effect every time during the run? pythonisbae 3 6,886 Mar-06-2022, 09:37 AM
Last Post: pythonisbae
  Ran 0 tests in 0.000s - unittest Peaches 8 10,254 Dec-31-2021, 08:58 AM
Last Post: Peaches
  Serial connection connection issue Joni_Engr 15 16,483 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  RuntimeError: generator raised StopIteration quest 1 8,189 Mar-28-2021, 08:11 PM
Last Post: quest
  maintain a postgresql database using osm2pgsql apollo 1 3,615 Aug-03-2020, 10:33 PM
Last Post: Larz60+
  VSCode not able to discover tests rpk2006 5 20,681 Jul-15-2020, 06:03 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020