Skip to content

Conversation

@dmitriichmil
Copy link
Contributor

@dmitriichmil dmitriichmil commented Apr 29, 2025

PR checklist

  • I've written good commit message for all commits
  • I've split changes into separate commits where it's appropriate
  • I've added the description of function to documentation
  • I've updated project version in pyproject.toml
  • I'll make a release when PR is merged
  • I'll bump pybotx in bot-template

@dmitriichmil dmitriichmil self-assigned this Apr 29, 2025
@osovskiyalexandr osovskiyalexandr self-requested a review April 29, 2025 12:39
@dmitriichmil dmitriichmil force-pushed the feature/cd/system-events-conferences branch from 64fa430 to 3d12faa Compare April 29, 2025 12:43
@codecov
Copy link

codecov bot commented Apr 29, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 100.00%. Comparing base (e2a3e66) to head (28b3142).
Report is 1 commits behind head on master.

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     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Contributor

Choose a reason for hiding this comment

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

  • Для payload стоит использовать фабрику или фикстуру

Copy link
Contributor Author

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
Copy link
Contributor

@osovskiyalexandr osovskiyalexandr Apr 29, 2025

Choose a reason for hiding this comment

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

  • Мутировать объект, который пришел от системы - плохая практика. Лучше работать с ним как с неизменяемым. Вместо того чтобы менять объект, используй dict из pydantic и exclude внутри него, это позволит создать сериализованное представление без лишних полей.

Copy link
Contributor

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))

Copy link
Contributor Author

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
Copy link
Contributor

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 = {
Copy link
Contributor

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 = {
Copy link
Contributor

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
Copy link
Contributor

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.
Copy link
Contributor

Choose a reason for hiding this comment

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

Стоит описать все параметры в доксринге, а не только часть

@dmitriichmil dmitriichmil force-pushed the feature/cd/system-events-conferences branch from 3d12faa to 6b944fa Compare April 30, 2025 08:47
bot.async_execute_raw_bot_command(payload, verify_request=False)

# - Assert -
assert conference_changed == ConferenceChangedEvent(
Copy link
Contributor

@osovskiyalexandr osovskiyalexandr May 4, 2025

Choose a reason for hiding this comment

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

В целом ОК, но я бы глянул в сторону factory-boy.
Плюс для сравнения deepdiff

@dmitriichmil dmitriichmil force-pushed the feature/cd/system-events-conferences branch 3 times, most recently from 9a7e77e to cd3907c Compare May 6, 2025 15:30
payload = api_incoming_message_factory(
body="system:conference_changed",
command_type="system",
data=json.loads(conference_change_data.json()),
Copy link
Contributor

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 - внутренняя модель, не факт вообще что она правильно написана и соответствует приходящим данным.
И если ты ее поменяешь, то данные в тесте тоже могут поменяться, тест будет проходить, но по факту ломаться на реальных данных

Copy link
Contributor Author

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()),
Copy link
Contributor

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
Copy link
Contributor

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 даст непонятный бинарный результат.

Copy link
Contributor Author

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(
Copy link
Contributor

Choose a reason for hiding this comment

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

А зачем двойное подчеркивание после test?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

общий стиль названия тестов такой



@pytest.fixture
def conference_change_data() -> BotAPIConferenceChangedData:
Copy link
Contributor

Choose a reason for hiding this comment

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

Если говорить о дистанции, то возвращать фабрику, а не объект из фикстуры будет лучшим вариантом. Что даст тебе возможность в специфичных тестах менять только нужные поля, без переписывания всего объекта.

@dmitriichmil dmitriichmil force-pushed the feature/cd/system-events-conferences branch from cd3907c to 662f3bb Compare May 7, 2025 10:31
@dmitriichmil dmitriichmil force-pushed the feature/cd/system-events-conferences branch from 662f3bb to 28b3142 Compare May 7, 2025 11:58
@dmitriichmil dmitriichmil merged commit ea3498d into master May 7, 2025
9 checks passed
@dmitriichmil dmitriichmil deleted the feature/cd/system-events-conferences branch May 7, 2025 12:01
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.

4 participants