Skip to content
Merged
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
106 changes: 106 additions & 0 deletions tests/unit/test_vote_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import os

os.environ["GEMINI_API_KEY"] = "test"
import uuid

import pytest
from fastapi import HTTPException

from app.api.v1.endpoints.chat import get_rated, vote_chat
from app.db.connector import DB


# Monkeypatch DB methods for testing
class DummyDB:
def __init__(self, voted_return=None, rated_data=None):
self.voted_return = voted_return or {"status": "ok"}
# rated_data is list of tuples (q,a,feedback,id)
self.rated_data = rated_data or []
self.change_votes_called = False
self.get_answers_called = False

def change_votes(self, chat_id, up, down, equal, user_id, comment):
self.change_votes_called = True
# echo parameters for verification
return {
"chat_id": chat_id,
"up": up,
"down": down,
"equal": equal,
"user_id": str(user_id),
"comment": comment,
}

def get_answers_with_votes(self, offset):
self.get_answers_called = True
return self.rated_data


@pytest.fixture(autouse=True)
def patch_db(monkeypatch):
# Prepare dummy DB instance
dummy = DummyDB(
rated_data=[
("Q1 ", "A1 ", "C1 ", "id1"),
("Q2", "A2", "C2", "id2"),
]
)
monkeypatch.setattr(DB, "__new__", lambda cls, *args, **kwargs: dummy)
yield dummy


def test_vote_chat_success(patch_db):
chat_id = str(uuid.uuid4())
user_id = uuid.uuid4()
# Call vote_chat: upvote
result = vote_chat(
chat_id, user_id, up=True, down=False, equal=False, comment="Nice"
)
# Should delegate to DB.change_votes
assert patch_db.change_votes_called
assert result == {
"chat_id": chat_id,
"up": True,
"down": False,
"equal": False,
"user_id": str(user_id),
"comment": "Nice",
}


def test_vote_chat_exception(monkeypatch):
# Simulate DB.change_votes raising
error_db = DummyDB()

def raise_exc(*args, **kwargs):
raise HTTPException(status_code=500, detail="Oops")

error_db.change_votes = raise_exc
monkeypatch.setattr(DB, "__new__", lambda cls, *args, **kwargs: error_db)

with pytest.raises(HTTPException) as exc:
vote_chat("any", uuid.uuid4())
assert exc.value.status_code == 500
assert "Oops" in exc.value.detail


def test_get_rated_returns_data(patch_db):
# Call get_rated
result = get_rated(page=2)
# Should call DB.get_answers_with_votes
assert patch_db.get_answers_called
# Data transformed: strip whitespace
assert result == {
"data": [
{"question": "Q1", "answer": "A1", "feedback": "C1", "id": "id1"},
{"question": "Q2", "answer": "A2", "feedback": "C2", "id": "id2"},
]
}


def test_get_rated_empty(patch_db):
# Simulate no data
patch_db.rated_data = []
result = get_rated(page=0)
assert patch_db.get_answers_called
assert result == {"data": []}