I am trying to test execute_query method but it’s not work
res:
AssertionError: assert [] == [{‘id’: 1, ‘n…lary’: 70000}] E
E Right contains 3 more items, first extra item: {‘id’: 1,
‘name’: ‘Alice’, ‘salary’: 50000} E Use -v to get more diff
class PostgresqlConnection():
dbname: str = PG_ETL_DATABASE user: str = PG_ETL_USER password: str = PG_ETL_PASSWORD host: str = PG_ETL_HOST port: str = PG_ETL_PORT @property def connection(self): return psycopg.connect(**self.dict()) def execute_query(self, query, is_fetch_result=False, is_commit=False): """Method execute a query on the database""" with self.connection as conn: with conn.cursor() as cursor: cursor.execute(query) results = [] if is_fetch_result: print(f"cursor.description1: {cursor.description.return_value}") column_names = [desc[0] for desc in cursor.description] print(f"column_names: {column_names}") rows = cursor.fetchall() print(f"rows: {rows}") for row in rows: results.append(dict(zip(column_names, row))) if is_commit: conn.commit() return results
The test:
@mock.patch("psycopg.connect")
def test_execute_query(self, mock_connect):
"""test execute query"""
expected = [
{"id": 1, "name": "Alice", "salary": 50000},
{"id": 2, "name": "Bob", "salary": 60000},
{"id": 3, "name": "Charlie", "salary": 70000},
]
mock_con = mock_connect.return_value
mock_cur = mock_con.cursor.return_value
mock_cur.description.return_value = [
("id", None, None, None, None, None, None),
("name", None, None, None, None, None, None),
("salary", None, None, None, None, None, None),
]
mock_cur.fetchall.return_value = [
(1, "Alice", 50000),
(2, "Bob", 60000),
(3, "Charlie", 70000),
]