From 163e6dc8489b4292dd5a6dccc8d8d59085cfd18a Mon Sep 17 00:00:00 2001 From: Taimoor Ahmed <68893403+taimoor-ahmed-1@users.noreply.github.com> Date: Fri, 7 Feb 2025 14:15:37 +0500 Subject: [PATCH] fix: delete thread throwing error (#159) close #147 Co-authored-by: Taimoor Ahmed --- forum/backends/mongodb/users.py | 3 ++- tests/test_views/test_threads.py | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/forum/backends/mongodb/users.py b/forum/backends/mongodb/users.py index aa08e71..4a0b9de 100644 --- a/forum/backends/mongodb/users.py +++ b/forum/backends/mongodb/users.py @@ -123,7 +123,8 @@ def delete_read_state_by_thread_id(self, thread_id: str) -> None: for user in list(users): updated_read_states = [] for read_state in user.get("read_states", []): - del read_state["last_read_times"][thread_id] + if read_state["last_read_times"].get(thread_id): + del read_state["last_read_times"][thread_id] updated_read_states.append(read_state) self._collection.update_one( {"_id": user["_id"]}, {"$set": {"read_states": updated_read_states}} diff --git a/tests/test_views/test_threads.py b/tests/test_views/test_threads.py index a769572..ca28d86 100644 --- a/tests/test_views/test_threads.py +++ b/tests/test_views/test_threads.py @@ -1,6 +1,7 @@ """Test threads api endpoints.""" import time +from datetime import datetime from typing import Any, Optional import pytest @@ -1114,3 +1115,26 @@ def test_read_states_deletion_on_thread_deletion_with_multiple_read_states( assert patched_mongo_backend.get_thread(thread_id_1) is None assert is_thread_id_exists_in_user_read_state(user_id_1, thread_id_1) is False assert is_thread_id_exists_in_user_read_state(user_id_2, thread_id_2) is True + + +def test_read_states_deletion_checks_thread_id_existence( + api_client: APIClient, patched_mongo_backend: MongoBackend +) -> None: + """Test that read state deletion only occurs when thread_id exists in last_read_times.""" + user_id, thread_id = setup_models(backend=patched_mongo_backend) + + other_thread_id = "other_thread_id" + read_states = [ + { + "course_id": "course1", + "last_read_times": {other_thread_id: datetime.now()}, + } + ] + patched_mongo_backend.update_user(user_id, {"read_states": read_states}) + + assert is_thread_id_exists_in_user_read_state(user_id, other_thread_id) is True + assert is_thread_id_exists_in_user_read_state(user_id, thread_id) is False + + response = api_client.delete_json(f"/api/v2/threads/{thread_id}") + assert response.status_code == 200 + assert is_thread_id_exists_in_user_read_state(user_id, other_thread_id) is True