Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make patch route #10 #60

Open
wants to merge 16 commits into
base: main
Choose a base branch
from
18 changes: 6 additions & 12 deletions rating_api/routes/comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
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 rating_api.schemas.models import CommentGet, CommentGetAll, CommentPost
from rating_api.schemas.models import CommentGet, CommentGetAll, CommentPost, CommentUpdate
from rating_api.settings import Settings, get_settings


Expand Down Expand Up @@ -156,25 +156,19 @@ async def review_comment(


@comment.patch("/{uuid}", response_model=CommentGet)
async def update_comment(uuid: UUID, comment_update: CommentPost = None, user=Depends(UnionAuth())) -> CommentGet:
"""
Изменить комментарий только свой неанонимный.
Должны быть переданы все поля в теле запроса: оценки, предмет, текст. Их можно получить из GET и изменить нужное, остальное оставить
"""
async def update_comment(uuid: UUID, comment_update: CommentUpdate, user=Depends(UnionAuth())) -> CommentGet:
"""Позволяет изменить свой неанонимный комментарий. любое поле опционально,"""
DR0P-database marked this conversation as resolved.
Show resolved Hide resolved
comment: Comment = Comment.get(session=db.session, id=uuid) # Ошибка, если не найден

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

# Обрабатываем анонимность комментария, и удаляем этот флаг чтобы добавить запись в БД
user_id = None if comment_update.is_anonymous else comment.user_id

return CommentGet.model_validate(
Comment.update(
session=db.session,
id=uuid,
**comment_update.model_dump(exclude={"is_anonymous"}),
user_id=user_id,
# Исключаем атрибуты, котрые не переданы
**comment_update.model_dump(exclude_unset=True),
update_ts=datetime.datetime.utcnow(),
parfenovma marked this conversation as resolved.
Show resolved Hide resolved
review_status=ReviewStatus.PENDING,
parfenovma marked this conversation as resolved.
Show resolved Hide resolved
)
Expand Down
15 changes: 15 additions & 0 deletions rating_api/schemas/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,21 @@ def validate_mark(cls, value):
return 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

@field_validator('mark_kindness', 'mark_freebie', 'mark_clarity')
@classmethod
def validate_mark(cls, value):
if value not in [-2, -1, 0, 1, 2]:
raise WrongMark()
return value


class CommentGetAll(Base):
comments: list[CommentGet] = []
limit: int
Expand Down
6 changes: 3 additions & 3 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ def unreviewed_comment(dbsession, lecturer):


@pytest.fixture
def comment_update(dbsession, lecturer):
def nonanonymous_comment(dbsession, lecturer):
_comment = Comment(
subject="update_subject",
text="update_comment",
subject="subject",
text="omment",
mark_kindness=1,
mark_clarity=1,
mark_freebie=1,
Expand Down
45 changes: 23 additions & 22 deletions tests/test_routes/test_comment.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,15 @@
status.HTTP_200_OK,
),
(
{ # Not provided anonymity
{
"subject": "test_subject",
"text": "test_text",
"update_ts": "2077-11-16T19:15:27.306Z",
"mark_kindness": 1,
"mark_freebie": -2,
"mark_clarity": 0,
},
1,
0,
status.HTTP_200_OK,
),
( # NotAnonymous comment
Expand Down Expand Up @@ -146,6 +147,18 @@
status.HTTP_422_UNPROCESSABLE_ENTITY,
),
( # Bad anonymity
{
"subject": "test_subject",
"text": "test_text",
"create_ts": "wasd",
"mark_kindness": 1,
"mark_freebie": -2,
"mark_clarity": 0,
},
0,
status.HTTP_422_UNPROCESSABLE_ENTITY,
),
( # Not provided anonymity
{
"subject": "test_subject",
"text": "test_text",
Expand Down Expand Up @@ -270,14 +283,14 @@ def test_review_comment(client, dbsession, unreviewed_comment, comment, review_s
},
status.HTTP_422_UNPROCESSABLE_ENTITY,
),
(
( # Отсутсвует одно поле
{
"subject": "test_subject",
"mark_kindness": 0,
"mark_freebie": -2,
"mark_clarity": 0,
},
status.HTTP_422_UNPROCESSABLE_ENTITY,
status.HTTP_200_OK,
),
(
{
Expand All @@ -289,30 +302,18 @@ def test_review_comment(client, dbsession, unreviewed_comment, comment, review_s
},
status.HTTP_400_BAD_REQUEST,
),
( # Ошибка для анонимных комментариев
{
"subject": "test_subject",
"text": "test_text",
"mark_kindness": 0,
"mark_freebie": -2,
"mark_clarity": 0,
"is_anonymous": True,
},
( # Отсутсвует все поля
{},
DR0P-database marked this conversation as resolved.
Show resolved Hide resolved
status.HTTP_200_OK,
),
],
)
def test_update_comment(client, dbsession, comment_update, body, response_status):
response = client.patch(f"{url}/{comment_update.uuid}", json=body)
def test_update_comment(client, dbsession, nonanonymous_comment, body, response_status):
response = client.patch(f"{url}/{nonanonymous_comment.uuid}", json=body)
assert response.status_code == response_status
if response.status_code == status.HTTP_200_OK:
DR0P-database marked this conversation as resolved.
Show resolved Hide resolved
dbsession.refresh(comment_update)
assert comment_update.review_status == ReviewStatus.PENDING

# Проверям, что мы изменяем только те комментарии, у которых user_id пользователя и не null
if "is_anonymous" in body and body['is_anonymous']:
response = client.patch(f"{url}/{comment_update.uuid}", json=body)
assert response.status_code == 403
dbsession.refresh(nonanonymous_comment)
assert nonanonymous_comment.review_status == ReviewStatus.PENDING


def test_delete_comment(client, dbsession, comment):
Expand Down