From 41554c31579fe455f18d2b86f70f0a1a529f930c Mon Sep 17 00:00:00 2001 From: gitfresnel <151745312+gitfresnel@users.noreply.github.com> Date: Sat, 2 Nov 2024 22:16:34 +0300 Subject: [PATCH 1/2] f --- rating_api/routes/comment.py | 4 ++-- rating_api/routes/lecturer.py | 4 +++- rating_api/schemas/models.py | 9 +++++++++ tests/test_routes/test_comment.py | 20 ++++++++++++++++++++ 4 files changed, 34 insertions(+), 3 deletions(-) diff --git a/rating_api/routes/comment.py b/rating_api/routes/comment.py index 678a691..c0cbcf4 100644 --- a/rating_api/routes/comment.py +++ b/rating_api/routes/comment.py @@ -98,9 +98,9 @@ async def get_comments( raise ForbiddenAction(Comment) else: result.comments = [comment for comment in result.comments if comment.review_status is ReviewStatus.APPROVED] - + result.comments = result.comments[offset : limit + offset] - + if "create_ts" in order_by: result.comments.sort(key=lambda comment: comment.create_ts) result.total = len(result.comments) diff --git a/rating_api/routes/lecturer.py b/rating_api/routes/lecturer.py index eb3b770..26422d6 100644 --- a/rating_api/routes/lecturer.py +++ b/rating_api/routes/lecturer.py @@ -138,7 +138,9 @@ async def get_lecturers( if "general" in order_by: result.lecturers.sort(key=lambda item: (item.mark_general is None, item.mark_general)) if subject: - result.lecturers = [lecturer for lecturer in result.lecturers if lecturer.subjects and subject in lecturer.subjects] + result.lecturers = [ + lecturer for lecturer in result.lecturers if lecturer.subjects and subject in lecturer.subjects + ] result.total = len(result.lecturers) return result diff --git a/rating_api/schemas/models.py b/rating_api/schemas/models.py index 35d5ae2..77f3491 100644 --- a/rating_api/schemas/models.py +++ b/rating_api/schemas/models.py @@ -1,6 +1,8 @@ import datetime from uuid import UUID +from pydantic import field_validator + from rating_api.schemas.base import Base @@ -23,6 +25,13 @@ class CommentPost(Base): mark_freebie: int mark_clarity: int + @field_validator('mark_kindness', 'mark_freebie', 'mark_clarity') + @classmethod + def validate_mark(cls, value): + if value not in [-2, -1, 0, 1, 2]: + raise ValueError('оценка может принимать только значения: -2, -1, 0, 1, 2') + return value + class CommentGetAll(Base): comments: list[CommentGet] = [] diff --git a/tests/test_routes/test_comment.py b/tests/test_routes/test_comment.py index 8361450..62cf2f5 100644 --- a/tests/test_routes/test_comment.py +++ b/tests/test_routes/test_comment.py @@ -47,6 +47,26 @@ def test_create_comment(client, dbsession): assert post_response.status_code == status.HTTP_404_NOT_FOUND +def test_post_bad_mark(client, dbsession): + body = {"first_name": 'Иван', "last_name": 'Иванов', "middle_name": 'Иванович', "timetable_id": 0} + lecturer: Lecturer = Lecturer(**body) + dbsession.add(lecturer) + dbsession.commit() + + body = { + "subject": "Физика", + "text": "Хороший препод", + "mark_kindness": 4, + "mark_freebie": -2, + "mark_clarity": 0, + } + params = {"lecturer_id": lecturer.id} + post_response = client.post(url, json=body, params=params) + assert post_response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY + dbsession.delete(lecturer) + dbsession.commit() + + def test_get_comment(client, dbsession): body = { "first_name": 'Иван', From 6cdeaef3e44102bb86b9f50b053dd7d893b52fed Mon Sep 17 00:00:00 2001 From: gitfresnel <151745312+gitfresnel@users.noreply.github.com> Date: Tue, 5 Nov 2024 13:54:14 +0300 Subject: [PATCH 2/2] f --- rating_api/exceptions.py | 7 +++++++ rating_api/routes/exc_handlers.py | 9 ++++++++- rating_api/schemas/models.py | 3 ++- tests/test_routes/test_comment.py | 2 +- 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/rating_api/exceptions.py b/rating_api/exceptions.py index 5b3615e..f575f96 100644 --- a/rating_api/exceptions.py +++ b/rating_api/exceptions.py @@ -42,3 +42,10 @@ def __init__(self, dtime: datetime.timedelta): class ForbiddenAction(RatingAPIError): def __init__(self, type: Type): super().__init__(f"Forbidden action with {type.__name__}", f"Запрещенное действие с объектом {type.__name__}") + + +class WrongMark(RatingAPIError): + def __init__(self): + super().__init__( + f"Ratings can only take values: -2, -1, 0, 1, 2", f"Оценки могут принимать только значения: -2, -1, 0, 1, 2" + ) diff --git a/rating_api/routes/exc_handlers.py b/rating_api/routes/exc_handlers.py index 25df7b3..3dcb940 100644 --- a/rating_api/routes/exc_handlers.py +++ b/rating_api/routes/exc_handlers.py @@ -1,7 +1,7 @@ import starlette.requests from starlette.responses import JSONResponse -from rating_api.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound, TooManyCommentRequests +from rating_api.exceptions import AlreadyExists, ForbiddenAction, ObjectNotFound, TooManyCommentRequests, WrongMark from rating_api.schemas.base import StatusResponseModel from .base import app @@ -33,3 +33,10 @@ async def forbidden_action_handler(req: starlette.requests.Request, exc: Already return JSONResponse( content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=403 ) + + +@app.exception_handler(WrongMark) +async def wrong_mark_handler(req: starlette.requests.Request, exc: WrongMark): + return JSONResponse( + content=StatusResponseModel(status="Error", message=exc.eng, ru=exc.ru).model_dump(), status_code=400 + ) diff --git a/rating_api/schemas/models.py b/rating_api/schemas/models.py index 77f3491..0793081 100644 --- a/rating_api/schemas/models.py +++ b/rating_api/schemas/models.py @@ -3,6 +3,7 @@ from pydantic import field_validator +from rating_api.exceptions import WrongMark from rating_api.schemas.base import Base @@ -29,7 +30,7 @@ class CommentPost(Base): @classmethod def validate_mark(cls, value): if value not in [-2, -1, 0, 1, 2]: - raise ValueError('оценка может принимать только значения: -2, -1, 0, 1, 2') + raise WrongMark() return value diff --git a/tests/test_routes/test_comment.py b/tests/test_routes/test_comment.py index 62cf2f5..e933026 100644 --- a/tests/test_routes/test_comment.py +++ b/tests/test_routes/test_comment.py @@ -62,7 +62,7 @@ def test_post_bad_mark(client, dbsession): } params = {"lecturer_id": lecturer.id} post_response = client.post(url, json=body, params=params) - assert post_response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY + assert post_response.status_code == status.HTTP_400_BAD_REQUEST dbsession.delete(lecturer) dbsession.commit()