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
  How to Connect to PostgreSQL Through Jump Server and SSH Tunnel using Python? nishans 1 843 Jan-02-2024, 10:37 AM
Last Post: khanzain
  unittest.mock for an api key silver 3 1,335 Aug-29-2022, 03:52 PM
Last Post: ndc85430
  Mock obj - How to call the side_effect every time during the run? pythonisbae 3 2,554 Mar-06-2022, 09:37 AM
Last Post: pythonisbae
  Ran 0 tests in 0.000s - unittest Peaches 8 4,924 Dec-31-2021, 08:58 AM
Last Post: Peaches
  Serial connection connection issue Joni_Engr 15 7,828 Aug-30-2021, 04:46 PM
Last Post: deanhystad
  RuntimeError: generator raised StopIteration quest 1 5,750 Mar-28-2021, 08:11 PM
Last Post: quest
  maintain a postgresql database using osm2pgsql apollo 1 2,254 Aug-03-2020, 10:33 PM
Last Post: Larz60+
  VSCode not able to discover tests rpk2006 5 10,709 Jul-15-2020, 06:03 AM
Last Post: ndc85430
  PostgreSQL psycopg2.errors.DuplicateColumn: column specified more than once rajnish_nationfirst 2 3,691 Jun-21-2020, 08:17 AM
Last Post: ibreeden
  How to mock an object that is created during function call? Schlangenversteher 0 1,946 Jan-31-2020, 01:36 PM
Last Post: Schlangenversteher

Forum Jump:

User Panel Messages

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