Skip to content

Commit

Permalink
Add validation
Browse files Browse the repository at this point in the history
- Validation if given attribute is still not changed
- Validation if no attributes given
- Add tests
  • Loading branch information
DR0P-database committed Dec 6, 2024
1 parent 6c13bf8 commit b44aab3
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 10 deletions.
16 changes: 13 additions & 3 deletions rating_api/routes/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@
from uuid import UUID

from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends, Query
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi_sqlalchemy import db

from rating_api.exceptions import ForbiddenAction, ObjectNotFound, TooManyCommentRequests
from rating_api.models import Comment, Lecturer, LecturerUserComment, ReviewStatus
from rating_api.schemas.base import StatusResponseModel
from starlette import status
from rating_api.schemas.models import CommentGet, CommentGetAll, CommentPost, CommentUpdate
from rating_api.settings import Settings, get_settings

Expand Down Expand Up @@ -157,12 +158,21 @@ async def review_comment(

@comment.patch("/{uuid}", response_model=CommentGet)
async def update_comment(uuid: UUID, comment_update: CommentUpdate, user=Depends(UnionAuth())) -> CommentGet:
"""Позволяет изменить свой неанонимный комментарий. любое поле опционально,"""
"""Позволяет изменить свой неанонимный комментарий"""
comment: Comment = Comment.get(session=db.session, id=uuid) # Ошибка, если не найден

if comment.user_id != user.get("id") or comment.user_id is None:
raise ForbiddenAction(Comment)


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

# Если хоть одно поле было передано неизменным
if set(comment.__dict__.items()).intersection(set(comment_update.model_dump(exclude_unset=True).items())):
raise HTTPException(status_code=426, detail="No changes detected") # 426

# Проверить поле update_ts create comment на null
return CommentGet.model_validate(
Comment.update(
session=db.session,
Expand Down
10 changes: 5 additions & 5 deletions rating_api/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ def validate_mark(cls, value):


class CommentUpdate(Base):
subject: str | None = None
text: str | None = None
mark_kindness: int | None = None
mark_freebie: int | None = None
mark_clarity: int | None = None
subject: str = None
text: str = None
mark_kindness: int = None
mark_freebie: int = None
mark_clarity: int = None

@field_validator('mark_kindness', 'mark_freebie', 'mark_clarity')
@classmethod
Expand Down
2 changes: 1 addition & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def unreviewed_comment(dbsession, lecturer):
def nonanonymous_comment(dbsession, lecturer):
_comment = Comment(
subject="subject",
text="omment",
text="comment",
mark_kindness=1,
mark_clarity=1,
mark_freebie=1,
Expand Down
23 changes: 22 additions & 1 deletion tests/test_routes/test_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,8 +304,29 @@ def test_review_comment(client, dbsession, unreviewed_comment, comment, review_s
),
( # Отсутсвует все поля
{},
status.HTTP_200_OK,
status.HTTP_409_CONFLICT,
),
( # Переданы НЕизмененные поля
{
"subject":"subject",
"text":"comment",
"mark_kindness":1,
"mark_clarity":1,
"mark_freebie":1,
},
status.HTTP_426_UPGRADE_REQUIRED,
),
( # НЕизмененным перелано одно поле
{
"subject":"asf",
"text":"asf",
"mark_kindness":2,
"mark_clarity":2,
"mark_freebie":1,
},
status.HTTP_426_UPGRADE_REQUIRED,
),
],
)
def test_update_comment(client, dbsession, nonanonymous_comment, body, response_status):
Expand Down

0 comments on commit b44aab3

Please sign in to comment.