Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 17 additions & 17 deletions src/app/db/connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,23 +172,23 @@ def get_answers_with_votes(
if connection:
self.pool.putconn(connection)

def flush(self):
"""
Delete all entries from the chats table.
"""
connection = None
try:
connection = self.pool.getconn()
cursor = connection.cursor()
cursor.execute("DELETE FROM chats;")
connection.commit()
cursor.close()
except Exception as e:
print(f"Failed to flush chats table: {e}")
finally:
if connection:
# always return the connection to the pool
self.pool.putconn(connection)
# def flush(self):
# """
# Delete all entries from the chats table.
# """
# connection = None
# try:
# connection = self.pool.getconn()
# cursor = connection.cursor()
# cursor.execute("DELETE FROM chats;")
# connection.commit()
# cursor.close()
# except Exception as e:
# print(f"Failed to flush chats table: {e}")
# finally:
# if connection:
# # always return the connection to the pool
# self.pool.putconn(connection)

def update_dataframe(self, rows):
connection = None
Expand Down
61 changes: 60 additions & 1 deletion tests/unit/test_db.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import uuid
from unittest.mock import MagicMock

import psycopg2.errors
import pytest
from fastapi import Response
from fastapi import HTTPException, Response

from app.db.connector import DB # ajusta el import a tu ruta real

Expand Down Expand Up @@ -133,3 +134,61 @@ def test_change_votes_success_up():

# 3) Verifica que devolvió la conexión al pool
assert db.pool.putconn.called, "No se llamó a pool.putconn()"


def test_change_votes_invalid_uuid_raises_400(monkeypatch):
"""
Simula que el cursor.execute levanta
InvalidTextRepresentation y debe traducirse en un HTTPException 400.
"""
db = DB()
fake_conn = db.pool.getconn()
fake_cursor = fake_conn.cursor_obj

# Patch ejecuta para lanzar InvalidTextRepresentation
def raise_invalid(*args, **kwargs):
raise psycopg2.errors.InvalidTextRepresentation("bad uuid")

fake_cursor.execute.side_effect = raise_invalid

with pytest.raises(HTTPException) as exc:
db.change_votes(
chat_id="not-a-uuid",
up=True,
down=False,
equal=False,
user_id="also-not-uuid",
comment="",
)
assert exc.value.status_code == 400
assert "Invalid UUID format" in exc.value.detail
# También en este caso debe devolver la conexión
assert db.pool.putconn.called


def test_change_votes_unexpected_exception_propagates(monkeypatch):
"""
Simula que el cursor.execute lanza una excepción genérica;
debe propagarse esa excepción, pero la conexión aún debe
devolverse al pool (desde el finally).
"""
db = DB()
fake_conn = db.pool.getconn()
fake_cursor = fake_conn.cursor_obj

class CustomError(Exception):
pass

fake_cursor.execute.side_effect = CustomError("boom!")

with pytest.raises(CustomError):
db.change_votes(
chat_id="11111111-1111-1111-1111-111111111111",
up=True,
down=False,
equal=False,
user_id=uuid.uuid4(),
comment="test",
)
# A pesar de la excepción, el finally debe devolver la conexión
assert db.pool.putconn.called