diff --git a/routes/openai_route.py b/routes/openai_route.py index 2786039..316b745 100644 --- a/routes/openai_route.py +++ b/routes/openai_route.py @@ -1,4 +1,5 @@ from fastapi import APIRouter, Response, HTTPException +from data_access_layer.topics_db_functions import get_topics from globals import globals from data_access_layer import users_db_functions from services.openai_service import get_question_and_answer, evaluate_answer @@ -16,10 +17,14 @@ async def gen_question(body: GenBody, response: Response): max_attempts = 5 attempts = 0 + allowed_topics = get_topics() + if body.topic not in allowed_topics: + raise HTTPException(status_code=400, detail=f"Invalid topic: {body.topic}. Must be one of {allowed_topics}.") + try: while attempts < max_attempts: answer = get_question_and_answer(topic, difficulty, answers_num) - if answers_num == len(answer['Answer']): + if (answers_num and answers_num == len(answer['Answer'])) or (not answers_num and len(answer['Answer']) == 1): return answer attempts += 1 @@ -30,7 +35,6 @@ async def gen_question(body: GenBody, response: Response): response.status_code = 400 return {"error": str(e)} - @router.post('/evaluate') async def evaluate_question(body: QARequest,ai_answer:str, response: Response): try: @@ -41,9 +45,10 @@ async def evaluate_question(body: QARequest,ai_answer:str, response: Response): answer = body.answer evaluation_score = evaluate_answer(question=question_text, answer=answer,ai_answer=ai_answer) users_db_functions.add_user_stats(user_id=user_id, question_text=question_text, answer=answer, topic=topic, - difficulty=difficulty, - score=evaluation_score["Score"], answer_correct=(evaluation_score["Score"] >= 5), - client=globals.mongo_client) + difficulty=difficulty, + score=evaluation_score["Score"], + answer_correct=(evaluation_score["Score"] >= 5), + client=globals.mongo_client) evaluation_score["question"] = question_text evaluation_score["user_answer"] = answer return evaluation_score diff --git a/tests/test_openai_service.py b/tests/test_openai_service.py index 732a820..e845992 100644 --- a/tests/test_openai_service.py +++ b/tests/test_openai_service.py @@ -70,6 +70,13 @@ def test_question_generation_wrong_difficulty(): response = requests.post(url, json={"topic": "python", "difficulty": "HARD"}) assert response.status_code == 422 +def test_question_generation_invalid_topic(): + server_url = os.getenv("SERVER_URL") + assert server_url is not None + url = f"{server_url}/question/generate" + response = requests.post(url, json={"topic": "invalid_topic"}) + assert response.status_code == 400 + assert "Invalid topic: invalid_topic. Must be one of" in response.json()['detail'] def test_gen_question_answers_num(): server_url = os.getenv("SERVER_URL")