From 0598a17de74006c46ccfa5f3e5a98f887d52375e Mon Sep 17 00:00:00 2001 From: Suresh Kumar Date: Sat, 30 Oct 2021 19:46:33 +0530 Subject: [PATCH] fixed cursor close check + added tests for fetchone, fetchmany, fetchall --- psycopg/psycopg/cursor.py | 2 +- tests/test_cursor.py | 59 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/psycopg/psycopg/cursor.py b/psycopg/psycopg/cursor.py index 71b66cb90..7b3d79ce5 100644 --- a/psycopg/psycopg/cursor.py +++ b/psycopg/psycopg/cursor.py @@ -451,7 +451,7 @@ class BaseCursor(Generic[ConnectionType, Row]): ) def _check_result(self) -> None: - if self._conn.closed: + if self.closed: raise e.InterfaceError("the cursor is closed") res = self.pgresult if not res: diff --git a/tests/test_cursor.py b/tests/test_cursor.py index 5a4a7b8cc..8948f50c5 100644 --- a/tests/test_cursor.py +++ b/tests/test_cursor.py @@ -26,6 +26,65 @@ def test_close(conn): assert cur.closed +def test_cursor_close_fetchone(conn): + cur = conn.cursor() + assert not cur.closed + + query = "select * from generate_series(1, 10)" + cur.execute(query) + for _ in range(5): + cur.fetchone() + + cur.close() + assert cur.closed + + with pytest.raises(psycopg.InterfaceError): + cur.fetchone() + + +def test_cursor_close_fetchmany(conn): + cur = conn.cursor() + assert not cur.closed + + query = "select * from generate_series(1, 10)" + cur.execute(query) + cur.close() + assert cur.closed + + with pytest.raises(psycopg.InterfaceError): + cur.fetchmany(1) + + +def test_cursor_close_fetchmany(conn): + cur = conn.cursor() + assert not cur.closed + + query = "select * from generate_series(1, 10)" + cur.execute(query) + assert len(cur.fetchmany(2)) == 2 + + cur.close() + assert cur.closed + + with pytest.raises(psycopg.InterfaceError): + cur.fetchmany(2) + + +def test_cursor_close_fetchall(conn): + cur = conn.cursor() + assert not cur.closed + + query = "select * from generate_series(1, 10)" + cur.execute(query) + assert len(cur.fetchall()) == 10 + + cur.close() + assert cur.closed + + with pytest.raises(psycopg.InterfaceError): + cur.fetchall() + + def test_context(conn): with conn.cursor() as cur: assert not cur.closed -- 2.47.2