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
20 changes: 19 additions & 1 deletion rating_api/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from sqlalchemy.exc import NoResultFound
from sqlalchemy.orm import Query, Session, as_declarative, declared_attr

from rating_api.exceptions import ObjectNotFound
from rating_api.exceptions import ObjectNotFound, UpdateError


@as_declarative()
Expand Down Expand Up @@ -61,8 +61,26 @@ def get(cls, id: int | str, *, with_deleted=False, session: Session) -> BaseDbMo
@classmethod
def update(cls, id: int | str, *, session: Session, **kwargs) -> BaseDbModel:
obj = cls.get(id, session=session)

# Технические поля не проверяются при update комментария
technical_fields = {'update_ts', 'review_status'}

# Проверка на изменение полей
changed_fields = False
for field, new_value in kwargs.items():

old_value = getattr(obj, field)
if old_value != new_value and not field in technical_fields:
changed_fields = True
break

if not changed_fields:
raise UpdateError(msg=f"No changes detected in fields")
# raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=f"No changes detected in fields")

for k, v in kwargs.items():
setattr(obj, k, v)

session.flush()
return obj

Expand Down
15 changes: 1 addition & 14 deletions rating_api/routes/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,20 +268,7 @@ async def update_comment(uuid: UUID, comment_update: CommentUpdate, user=Depends
# Получаем только переданные для обновления поля
update_data = comment_update.model_dump(exclude_unset=True)

# Если не передано ни одного параметра
if not update_data:
raise UpdateError(msg="Provide any parametr.")
# raise HTTPException(status_code=409, detail="Provide any parametr") # 409

# Проверяем, есть ли неизмененные поля
current_data = {key: getattr(comment, key) for key in update_data} # Берем текущие значения из БД
unchanged_fields = {k for k, v in update_data.items() if current_data.get(k) == v}

if unchanged_fields:
raise UpdateError(msg=f"No changes detected in fields: {', '.join(unchanged_fields)}.")
# raise HTTPException(status_code=409, detail=f"No changes detected in fields: {', '.join(unchanged_fields)}")

# Обновление комментария
# Обновляем комментарий
updated_comment = Comment.update(
session=db.session,
id=uuid,
Expand Down
12 changes: 6 additions & 6 deletions tests/test_routes/test_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,13 +254,13 @@ def test_comments_by_user_id(client, lecturers_with_comments, user_id, response_
],
)
def test_review_comment(client, dbsession, unreviewed_comment, comment, review_status, response_status, is_reviewed):
commment_to_reivew = comment if is_reviewed else unreviewed_comment
commment_to_review = comment if is_reviewed else unreviewed_comment
query = {"review_status": review_status}
response = client.patch(f"{url}/{commment_to_reivew.uuid}/review", params=query)
response = client.patch(f"{url}/{commment_to_review.uuid}/review", params=query)
assert response.status_code == response_status
if response.status_code == status.HTTP_200_OK:
dbsession.refresh(commment_to_reivew)
assert commment_to_reivew.review_status == ReviewStatus(review_status)
dbsession.refresh(commment_to_review)
assert commment_to_review.review_status == ReviewStatus(review_status)


@pytest.mark.parametrize(
Expand Down Expand Up @@ -319,15 +319,15 @@ def test_review_comment(client, dbsession, unreviewed_comment, comment, review_s
},
status.HTTP_409_CONFLICT,
),
( # НЕизмененным перелано одно поле
( # НЕизмененным передано одно поле
{
"subject": "asf",
"text": "asf",
"mark_kindness": 2,
"mark_clarity": 2,
"mark_freebie": 1,
},
status.HTTP_409_CONFLICT,
status.HTTP_200_OK,
),
],
)
Expand Down
Loading