-
Notifications
You must be signed in to change notification settings - Fork 16
feat: add system events for conferences #493
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
Conversation
64fa430 to
3d12faa
Compare
Codecov ReportAll modified and coverable lines are covered by tests ✅
Additional details and impacted files@@ Coverage Diff @@
## master #493 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 122 125 +3
Lines 4281 4412 +131
Branches 367 370 +3
==========================================
+ Hits 4281 4412 +131
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Для payload стоит использовать фабрику или фикстуру
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
добавил фабрику
| nonlocal conference_changed | ||
| conference_changed = event | ||
| # Drop `raw_command` from asserting | ||
| conference_changed.raw_command = None |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Мутировать объект, который пришел от системы - плохая практика. Лучше работать с ним как с неизменяемым. Вместо того чтобы менять объект, используй dict из pydantic и exclude внутри него, это позволит создать сериализованное представление без лишних полей.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
История дублируется, стоит вынести в утилиту. Что-то в духе:
def assert_events_equal_ignoring_fields(actual, expected, ignore_fields):
assert actual.dict(exclude=set(ignore_fields)) == expected.dict(exclude=set(ignore_fields))
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
там dataclass, из-за этого немного по-другому сделал
| nonlocal conference_created | ||
| conference_created = event | ||
| # Drop `raw_command` from asserting | ||
| conference_created.raw_command = None |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично
| datetime_formatter: Callable[[str], datetime], | ||
| ) -> None: | ||
| # - Arrange - | ||
| payload = { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Для payload стоит использовать фабрику или фикстуру
| bot_account: BotAccountWithSecret, | ||
| ) -> None: | ||
| # - Arrange - | ||
| payload = { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
- Для payload стоит использовать фабрику или фикстуру
| nonlocal conference_deleted | ||
| conference_deleted = event | ||
| # Drop `raw_command` from asserting | ||
| conference_deleted.raw_command = None |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Аналогично
| """Event `system:conference_changed`. | ||
| Attributes: | ||
| call_id: id conference. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Стоит описать все параметры в доксринге, а не только часть
3d12faa to
6b944fa
Compare
| bot.async_execute_raw_bot_command(payload, verify_request=False) | ||
|
|
||
| # - Assert - | ||
| assert conference_changed == ConferenceChangedEvent( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
В целом ОК, но я бы глянул в сторону factory-boy.
Плюс для сравнения deepdiff
9a7e77e to
cd3907c
Compare
| payload = api_incoming_message_factory( | ||
| body="system:conference_changed", | ||
| command_type="system", | ||
| data=json.loads(conference_change_data.json()), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
как будто бы не очень хорошо тестовый пайлоад, который ждешь в запросе создавать из внутренней модели
Я имею ввиду вот здесь:
payload = api_incoming_message_factory(
body="system:conference_changed",
command_type="system",
data=json.loads(conference_change_data.json()),
bot_id=bot_id,
host=host,
)
ты по сути используешь
class ConferenceChangedDataFactory(factory.Factory[BotAPIConferenceChangedData]):
class Meta:
model = BotAPIConferenceChangedData
BotAPIConferenceChangedData - внутренняя модель, не факт вообще что она правильно написана и соответствует приходящим данным.
И если ты ее поменяешь, то данные в тесте тоже могут поменяться, тест будет проходить, но по факту ломаться на реальных данных
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поменял на DictFactory
| payload = api_incoming_message_factory( | ||
| body="system:conference_changed", | ||
| command_type="system", | ||
| data=json.loads(conference_change_data.json()), |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
conference_change_data.dict() - должен дать тот же результат, но быстрее
| ), | ||
| ) | ||
|
|
||
| assert bool(diff) is False |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
assert diff == {}, diff
Так diff напечатает, что именно не совпало. А assert bool(diff) is False даст непонятный бинарный результат.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
поправил
| ] | ||
|
|
||
|
|
||
| async def test__conference_changed_succeed( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А зачем двойное подчеркивание после test?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
общий стиль названия тестов такой
tests/conftest.py
Outdated
|
|
||
|
|
||
| @pytest.fixture | ||
| def conference_change_data() -> BotAPIConferenceChangedData: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Если говорить о дистанции, то возвращать фабрику, а не объект из фикстуры будет лучшим вариантом. Что даст тебе возможность в специфичных тестах менять только нужные поля, без переписывания всего объекта.
cd3907c to
662f3bb
Compare
662f3bb to
28b3142
Compare
PR checklist
pyproject.tomlpybotxinbot-template