Skip to content

added validation when create - #41

Open
petrCher wants to merge 2 commits into
mainfrom
validation_when_create
Open

petrCher wants to merge 2 commits into
mainfrom
validation_when_create

Conversation

@petrCher

@petrCher petrCher commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Изменения

Валидация модалок при создании в зависимости от типа

Детали реализации

Check-List

  • Вы проверили свой код перед отправкой запроса?
  • Вы написали тесты к реализованным функциям?
  • Вы не забыли применить форматирование black и isort для Back-End или Prettier для Front-End?

@petrCher petrCher self-assigned this Aug 27, 2026
@github-actions

github-actions Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Code Coverage

Coverage Report
FileStmtsMissCoverMissing
modal_backend
   __main__.py440%1–6
modal_backend/models
   base.py62789%22, 25–28, 57, 87
modal_backend/routes
   notes.py66198%251
modal_backend/schemas
   base.py12467%6–9
modal_backend/utils
   user_logic.py22291%22, 26
TOTAL6101897% 

Summary

Tests Skipped Failures Errors Time
110 0 💤 0 ❌ 0 🔥 8.006s ⏱️

@Aiz0r

Aiz0r commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

Вроде все поправил, жду ревью @petrCher.

@Aiz0r

Aiz0r commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

ну или от @Georgon тоже жду ревью

@petrCher

Copy link
Copy Markdown
Member Author

git rebase сделай, так как залил твой прошлый пр
ревью этого скоро будет

@petrCher

Copy link
Copy Markdown
Member Author

если что только надо меня и Гошу не в assigners добавлять, а в reviews)
ты же ревью просишь
а на assigners себя

@Aiz0r

Aiz0r commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

если что только надо меня и Гошу не в assigners добавлять, а в reviews)
ты же ревью просишь
а на assigners себя

Ой, сорри, поправлю завтра

@Aiz0r

Aiz0r commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

git rebase сделай, так как залил твой прошлый пр
ревью этого скоро будет

Ок, поправлю

@Aiz0r
Aiz0r force-pushed the validation_when_create branch from bce5048 to 17ef578 Compare September 20, 2026 17:51
@Aiz0r

Aiz0r commented Sep 20, 2026

Copy link
Copy Markdown
Contributor

@petrCher @Georgon rebase сделал, жду ревью

@petrCher

Copy link
Copy Markdown
Member Author

если ревью ждешь, не забывай просить ревью во вкладке reviewers)

@Aiz0r

Aiz0r commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

если ревью ждешь, не забывай просить ревью во вкладке reviewers)

Мне не дает вас выбрать в ревьюверы, если что

@Aiz0r

Aiz0r commented Sep 23, 2026

Copy link
Copy Markdown
Contributor

если ревью ждешь, не забывай просить ревью во вкладке reviewers)

Могу на рандомного кого-то повесить. Но на тебя или Georgon не могу. Тупо в списке нет

@petrCher petrCher left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/profcomff/modal-service-api/blob/main/modal_backend/exceptions.py#L35
ValueError у тебя используется кастомный и получается что ты в него передаешь не совсем то, что было ранее запланировано для него и получается бред)
поэтому надо бы создать свое новое исключение и в него передавать данные

type_id: int
header: str
end_ts: datetime.datetime
end_ts: datetime.datetime | None # по тз может быть null, если is_always = true

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

коммент можно удалить
если для меня пр коммент нужен, то его лучше оставлять прям в гитхабе, как я оставляю текущий коммент тебе

dbsession.delete(note)


VALID_NOTE_BODIES: dict[str, dict] = {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

все тесты не то что нужно, ты делаешь тесты ради тестов
а надо тесты ради понимания кода
есть предложение исправить все проблемы этого пр по фалидации и потом отдельным сделаешь норм тестики (на созваны объясню что хочу увидеть)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если что тесты ниже этого коммента удалить надо, те небольшие правки выше правильные

):
"""Валидация полей при создании note"""
if note.is_always:
note.end_ts = None

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

а зачем такая проверка если в схеме прописано что дефолт none

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

и тогда сразу вопрос почему start_ts не делал?) только для конца

"""Валидация полей при создании note"""
if note.is_always:
note.end_ts = None
elif note.end_ts is None or (note.start_ts is not None and note.start_ts >= note.end_ts):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

лучше просто or все сделать

note.end_ts = None
elif note.end_ts is None or (note.start_ts is not None and note.start_ts >= note.end_ts):
raise ValueError("Invalid end_ts value")

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

нужна кстати проверка что start и end_ts>now иначе я могу сейчас создать модалку которая просрочена

raise ValueError("Service ids must not be empty")

if isinstance(note, NoteRatingPost):
if note.rating_max is None or not (2 <= note.rating_max <= 10):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

https://github.com/profcomff/modal-service-api/blob/main/modal_backend/settings.py#L11
хардкор с числом 10 это плохо
надо сделать отдельной переменной для variables в settings и оттуда использовать здесь и в будущих тестах
также как сделаешь переменную надо в github/build_and_publish.yml прописать в джобе эту переменную как ту, которую надо взять из github secrets(с ними я сам разберусь, тебе только желательно в описании жирным пометить что мне надо это сделать)

elif isinstance(note, NoteImagePost):
if not note.images:
raise ValueError("Images must not be empty")
elif isinstance(note, NoteTextPost):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хочется в порядке следования type_id прописать валидацию каждого объекта

if not note.images:
raise ValueError("Images must not be empty")
elif isinstance(note, NoteTextPost):
if note.max_length is None or not (1 <= note.max_length <= 5000):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давай для 5000 тоже сделаем как с максимальным рейтингом

raise ValueError("Choice options must have unique ids")
if not all(
opt.text for opt in note.choice_options
): # я так понял, что текст из пробелов это тоже текст. Поправьте если нет

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

opt.text.strip()
коммент всегда в гитхабе писать, не в коде

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

пробелы в тексте лишние убрать


if note.frequency < 1:
raise ValueError("Frequency must be greater than 0")
if not note.group_ids:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

хочется для групп и сервисов сделать проверку на их существование реальное, надо в бд здесь будет обращаться

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

добавить валидацию полей при создании note

3 participants