From dd50a9b13ec22d7871fbd9a6dd6e8eb68803f2de Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2020 21:48:49 +0000 Subject: [PATCH 1/2] Remove assert statement from non-test files --- aiogram/dispatcher/dispatcher.py | 7 +- tests/conftest.py | 3 +- tests/contrib/fsm_storage/test_redis.py | 15 +- tests/test_bot.py | 207 ++++++++++++------ tests/test_bot/test_api.py | 3 +- tests/test_bot/test_session.py | 45 ++-- tests/test_dispatcher.py | 3 +- .../test_filters/test_builtin.py | 12 +- .../test_filters/test_state.py | 3 +- tests/test_dispatcher/test_handler.py | 15 +- tests/test_filters.py | 24 +- tests/test_states_group.py | 82 ++++--- tests/test_utils/test_auth_widget.py | 15 +- tests/test_utils/test_deep_linking.py | 12 +- tests/test_utils/test_deprecated.py | 6 +- tests/test_utils/test_helper.py | 6 +- tests/test_utils/test_markdown.py | 6 +- tests/test_utils/test_text_decorations.py | 10 +- tests/types/test_animation.py | 45 ++-- tests/types/test_chat.py | 93 +++++--- tests/types/test_chat_member.py | 117 ++++++---- tests/types/test_document.py | 33 ++- tests/types/test_game.py | 30 ++- tests/types/test_input_media.py | 30 ++- tests/types/test_message.py | 39 ++-- tests/types/test_photo.py | 30 ++- tests/types/test_reply_keyboard.py | 6 +- tests/types/test_update.py | 15 +- tests/types/test_user.py | 48 ++-- 29 files changed, 637 insertions(+), 323 deletions(-) diff --git a/aiogram/dispatcher/dispatcher.py b/aiogram/dispatcher/dispatcher.py index 978c4426..b074d60e 100644 --- a/aiogram/dispatcher/dispatcher.py +++ b/aiogram/dispatcher/dispatcher.py @@ -31,10 +31,11 @@ DEFAULT_RATE_LIMIT = .1 def _ensure_loop(x: "asyncio.AbstractEventLoop"): - assert isinstance( + if not isinstance( x, asyncio.AbstractEventLoop - ), f"Loop must be the implementation of {asyncio.AbstractEventLoop!r}, " \ - f"not {type(x)!r}" + ): + raise AssertionError(f"Loop must be the implementation of {asyncio.AbstractEventLoop!r}, " \ + f"not {type(x)!r}") class Dispatcher(DataMixin, ContextInstanceMixin): diff --git a/tests/conftest.py b/tests/conftest.py index 297fbd28..466e9490 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -22,7 +22,8 @@ def pytest_collection_modifyitems(config, items): return try: address, options = aioredis.util.parse_url(redis_uri) - assert isinstance(address, tuple), "Only redis and rediss schemas are supported, eg redis://foo." + if not isinstance(address, tuple): + raise AssertionError("Only redis and rediss schemas are supported, eg redis://foo.") except AssertionError as e: raise UsageError(f"Invalid redis URI {redis_uri!r}: {e}") diff --git a/tests/contrib/fsm_storage/test_redis.py b/tests/contrib/fsm_storage/test_redis.py index 527c905e..40f18cad 100644 --- a/tests/contrib/fsm_storage/test_redis.py +++ b/tests/contrib/fsm_storage/test_redis.py @@ -19,15 +19,20 @@ async def store(redis_options): class TestRedisStorage2: @pytest.mark.asyncio async def test_set_get(self, store): - assert await store.get_data(chat='1234') == {} + if await store.get_data(chat='1234') != {}: + raise AssertionError await store.set_data(chat='1234', data={'foo': 'bar'}) - assert await store.get_data(chat='1234') == {'foo': 'bar'} + if await store.get_data(chat='1234') != {'foo': 'bar'}: + raise AssertionError @pytest.mark.asyncio async def test_close_and_open_connection(self, store): await store.set_data(chat='1234', data={'foo': 'bar'}) - assert await store.get_data(chat='1234') == {'foo': 'bar'} + if await store.get_data(chat='1234') != {'foo': 'bar'}: + raise AssertionError pool_id = id(store._redis) await store.close() - assert await store.get_data(chat='1234') == {'foo': 'bar'} # new pool was opened at this point - assert id(store._redis) != pool_id + if await store.get_data(chat='1234') != {'foo': 'bar'}: + raise AssertionError + if id(store._redis) == pool_id: + raise AssertionError diff --git a/tests/test_bot.py b/tests/test_bot.py index 54cd0c47..462bd48e 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -22,7 +22,8 @@ async def test_get_me(bot: Bot, event_loop): async with FakeTelegram(message_data=USER, loop=event_loop): result = await bot.me - assert result == user + if result != user: + raise AssertionError async def test_log_out(bot: Bot, event_loop): @@ -30,7 +31,8 @@ async def test_log_out(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.log_out() - assert result is True + if result is not True: + raise AssertionError async def test_close_bot(bot: Bot, event_loop): @@ -38,7 +40,8 @@ async def test_close_bot(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.close_bot() - assert result is True + if result is not True: + raise AssertionError async def test_send_message(bot: Bot, event_loop): @@ -48,7 +51,8 @@ async def test_send_message(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE, loop=event_loop): result = await bot.send_message(chat_id=msg.chat.id, text=msg.text) - assert result == msg + if result != msg: + raise AssertionError async def test_forward_message(bot: Bot, event_loop): @@ -59,7 +63,8 @@ async def test_forward_message(bot: Bot, event_loop): async with FakeTelegram(message_data=FORWARDED_MESSAGE, loop=event_loop): result = await bot.forward_message(chat_id=msg.chat.id, from_chat_id=msg.forward_from_chat.id, message_id=msg.forward_from_message_id) - assert result == msg + if result != msg: + raise AssertionError async def test_send_photo(bot: Bot, event_loop): @@ -71,7 +76,8 @@ async def test_send_photo(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_PHOTO, loop=event_loop): result = await bot.send_photo(msg.chat.id, photo=photo.file_id, caption=msg.caption, parse_mode=types.ParseMode.HTML, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_audio(bot: Bot, event_loop): @@ -83,7 +89,8 @@ async def test_send_audio(bot: Bot, event_loop): result = await bot.send_audio(chat_id=msg.chat.id, audio=msg.audio.file_id, caption=msg.caption, parse_mode=types.ParseMode.HTML, duration=msg.audio.duration, performer=msg.audio.performer, title=msg.audio.title, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_document(bot: Bot, event_loop): @@ -94,7 +101,8 @@ async def test_send_document(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_DOCUMENT, loop=event_loop): result = await bot.send_document(chat_id=msg.chat.id, document=msg.document.file_id, caption=msg.caption, parse_mode=types.ParseMode.HTML, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_video(bot: Bot, event_loop): @@ -108,7 +116,8 @@ async def test_send_video(bot: Bot, event_loop): width=video.width, height=video.height, caption=msg.caption, parse_mode=types.ParseMode.HTML, supports_streaming=True, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_voice(bot: Bot, event_loop): @@ -121,7 +130,8 @@ async def test_send_voice(bot: Bot, event_loop): result = await bot.send_voice(chat_id=msg.chat.id, voice=voice.file_id, caption=msg.caption, parse_mode=types.ParseMode.HTML, duration=voice.duration, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_video_note(bot: Bot, event_loop): @@ -134,7 +144,8 @@ async def test_send_video_note(bot: Bot, event_loop): result = await bot.send_video_note(chat_id=msg.chat.id, video_note=video_note.file_id, duration=video_note.duration, length=video_note.length, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_media_group(bot: Bot, event_loop): @@ -146,8 +157,10 @@ async def test_send_media_group(bot: Bot, event_loop): async with FakeTelegram(message_data=[MESSAGE_WITH_MEDIA_GROUP, MESSAGE_WITH_MEDIA_GROUP], loop=event_loop): result = await bot.send_media_group(msg.chat.id, media=media, disable_notification=False) - assert len(result) == len(media) - assert result.pop().media_group_id + if len(result) != len(media): + raise AssertionError + if not result.pop().media_group_id: + raise AssertionError async def test_send_location(bot: Bot, event_loop): @@ -159,7 +172,8 @@ async def test_send_location(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): result = await bot.send_location(msg.chat.id, latitude=location.latitude, longitude=location.longitude, live_period=10, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_edit_message_live_location_by_bot(bot: Bot, event_loop): @@ -172,7 +186,8 @@ async def test_edit_message_live_location_by_bot(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): result = await bot.edit_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id, latitude=location.latitude, longitude=location.longitude) - assert result == msg + if result != msg: + raise AssertionError async def test_edit_message_live_location_by_user(bot: Bot, event_loop): @@ -185,7 +200,8 @@ async def test_edit_message_live_location_by_user(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.edit_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id, latitude=location.latitude, longitude=location.longitude) - assert isinstance(result, bool) and result is True + if not (isinstance(result, bool) and result is True): + raise AssertionError async def test_stop_message_live_location_by_bot(bot: Bot, event_loop): @@ -196,7 +212,8 @@ async def test_stop_message_live_location_by_bot(bot: Bot, event_loop): # stopping bot message async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): result = await bot.stop_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id) - assert result == msg + if result != msg: + raise AssertionError async def test_stop_message_live_location_by_user(bot: Bot, event_loop): @@ -207,8 +224,10 @@ async def test_stop_message_live_location_by_user(bot: Bot, event_loop): # stopping user's message async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.stop_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_send_venue(bot: Bot, event_loop): @@ -222,7 +241,8 @@ async def test_send_venue(bot: Bot, event_loop): result = await bot.send_venue(msg.chat.id, latitude=location.latitude, longitude=location.longitude, title=venue.title, address=venue.address, foursquare_id=venue.foursquare_id, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_contact(bot: Bot, event_loop): @@ -234,7 +254,8 @@ async def test_send_contact(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_CONTACT, loop=event_loop): result = await bot.send_contact(msg.chat.id, phone_number=contact.phone_number, first_name=contact.first_name, last_name=contact.last_name, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_dice(bot: Bot, event_loop): @@ -244,7 +265,8 @@ async def test_send_dice(bot: Bot, event_loop): async with FakeTelegram(message_data=MESSAGE_WITH_DICE, loop=event_loop): result = await bot.send_dice(msg.chat.id, disable_notification=False) - assert result == msg + if result != msg: + raise AssertionError async def test_send_chat_action(bot: Bot, event_loop): @@ -254,8 +276,10 @@ async def test_send_chat_action(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.send_chat_action(chat_id=chat.id, action=types.ChatActions.TYPING) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_get_user_profile_photo(bot: Bot, event_loop): @@ -265,7 +289,8 @@ async def test_get_user_profile_photo(bot: Bot, event_loop): async with FakeTelegram(message_data=USER_PROFILE_PHOTOS, loop=event_loop): result = await bot.get_user_profile_photos(user_id=user.id, offset=1, limit=1) - assert isinstance(result, types.UserProfilePhotos) + if not isinstance(result, types.UserProfilePhotos): + raise AssertionError async def test_get_file(bot: Bot, event_loop): @@ -275,7 +300,8 @@ async def test_get_file(bot: Bot, event_loop): async with FakeTelegram(message_data=FILE, loop=event_loop): result = await bot.get_file(file_id=file.file_id) - assert isinstance(result, types.File) + if not isinstance(result, types.File): + raise AssertionError async def test_kick_chat_member(bot: Bot, event_loop): @@ -286,8 +312,10 @@ async def test_kick_chat_member(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.kick_chat_member(chat_id=chat.id, user_id=user.id, until_date=123) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_unban_chat_member(bot: Bot, event_loop): @@ -298,8 +326,10 @@ async def test_unban_chat_member(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.unban_chat_member(chat_id=chat.id, user_id=user.id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_restrict_chat_member(bot: Bot, event_loop): @@ -318,8 +348,10 @@ async def test_restrict_chat_member(bot: Bot, event_loop): can_send_messages=False, can_send_other_messages=False ), until_date=123) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_promote_chat_member(bot: Bot, event_loop): @@ -333,8 +365,10 @@ async def test_promote_chat_member(bot: Bot, event_loop): can_delete_messages=True, can_edit_messages=True, can_invite_users=True, can_pin_messages=True, can_post_messages=True, can_promote_members=True, can_restrict_members=True) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_export_chat_invite_link(bot: Bot, event_loop): @@ -344,7 +378,8 @@ async def test_export_chat_invite_link(bot: Bot, event_loop): async with FakeTelegram(message_data=INVITE_LINK, loop=event_loop): result = await bot.export_chat_invite_link(chat_id=chat.id) - assert result == INVITE_LINK + if result != INVITE_LINK: + raise AssertionError async def test_delete_chat_photo(bot: Bot, event_loop): @@ -354,8 +389,10 @@ async def test_delete_chat_photo(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.delete_chat_photo(chat_id=chat.id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_set_chat_title(bot: Bot, event_loop): @@ -365,8 +402,10 @@ async def test_set_chat_title(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.set_chat_title(chat_id=chat.id, title='Test title') - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_set_chat_description(bot: Bot, event_loop): @@ -376,8 +415,10 @@ async def test_set_chat_description(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.set_chat_description(chat_id=chat.id, description='Test description') - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_pin_chat_message(bot: Bot, event_loop): @@ -388,8 +429,10 @@ async def test_pin_chat_message(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.pin_chat_message(chat_id=message.chat.id, message_id=message.message_id, disable_notification=False) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_unpin_chat_message(bot: Bot, event_loop): @@ -399,8 +442,10 @@ async def test_unpin_chat_message(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.unpin_chat_message(chat_id=chat.id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_leave_chat(bot: Bot, event_loop): @@ -410,8 +455,10 @@ async def test_leave_chat(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.leave_chat(chat_id=chat.id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_get_chat(bot: Bot, event_loop): @@ -421,7 +468,8 @@ async def test_get_chat(bot: Bot, event_loop): async with FakeTelegram(message_data=CHAT, loop=event_loop): result = await bot.get_chat(chat_id=chat.id) - assert result == chat + if result != chat: + raise AssertionError async def test_get_chat_administrators(bot: Bot, event_loop): @@ -432,8 +480,10 @@ async def test_get_chat_administrators(bot: Bot, event_loop): async with FakeTelegram(message_data=[CHAT_MEMBER, CHAT_MEMBER], loop=event_loop): result = await bot.get_chat_administrators(chat_id=chat.id) - assert result[0] == member - assert len(result) == 2 + if result[0] != member: + raise AssertionError + if len(result) != 2: + raise AssertionError async def test_get_chat_members_count(bot: Bot, event_loop): @@ -444,7 +494,8 @@ async def test_get_chat_members_count(bot: Bot, event_loop): async with FakeTelegram(message_data=count, loop=event_loop): result = await bot.get_chat_members_count(chat_id=chat.id) - assert result == count + if result != count: + raise AssertionError async def test_get_chat_member(bot: Bot, event_loop): @@ -455,8 +506,10 @@ async def test_get_chat_member(bot: Bot, event_loop): async with FakeTelegram(message_data=CHAT_MEMBER, loop=event_loop): result = await bot.get_chat_member(chat_id=chat.id, user_id=member.user.id) - assert isinstance(result, types.ChatMember) - assert result == member + if not isinstance(result, types.ChatMember): + raise AssertionError + if result != member: + raise AssertionError async def test_set_chat_sticker_set(bot: Bot, event_loop): @@ -466,8 +519,10 @@ async def test_set_chat_sticker_set(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.set_chat_sticker_set(chat_id=chat.id, sticker_set_name='aiogram_stickers') - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_delete_chat_sticker_set(bot: Bot, event_loop): @@ -477,8 +532,10 @@ async def test_delete_chat_sticker_set(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.delete_chat_sticker_set(chat_id=chat.id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_answer_callback_query(bot: Bot, event_loop): @@ -486,8 +543,10 @@ async def test_answer_callback_query(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.answer_callback_query(callback_query_id='QuERyId', text='Test Answer') - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_set_my_commands(bot: Bot, event_loop): @@ -497,8 +556,10 @@ async def test_set_my_commands(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): commands = [types.BotCommand(**BOT_COMMAND), types.BotCommand(**BOT_COMMAND)] result = await bot.set_my_commands(commands) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_get_my_commands(bot: Bot, event_loop): @@ -508,8 +569,10 @@ async def test_get_my_commands(bot: Bot, event_loop): commands = [command, command] async with FakeTelegram(message_data=commands, loop=event_loop): result = await bot.get_my_commands() - assert isinstance(result, list) - assert all(isinstance(command, types.BotCommand) for command in result) + if not isinstance(result, list): + raise AssertionError + if not all(isinstance(command, types.BotCommand) for command in result): + raise AssertionError async def test_edit_message_text_by_bot(bot: Bot, event_loop): @@ -520,7 +583,8 @@ async def test_edit_message_text_by_bot(bot: Bot, event_loop): # message by bot async with FakeTelegram(message_data=EDITED_MESSAGE, loop=event_loop): result = await bot.edit_message_text(text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id) - assert result == msg + if result != msg: + raise AssertionError async def test_edit_message_text_by_user(bot: Bot, event_loop): @@ -531,8 +595,10 @@ async def test_edit_message_text_by_user(bot: Bot, event_loop): # message by user async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.edit_message_text(text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id) - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_set_sticker_set_thumb(bot: Bot, event_loop): @@ -540,11 +606,14 @@ async def test_set_sticker_set_thumb(bot: Bot, event_loop): async with FakeTelegram(message_data=True, loop=event_loop): result = await bot.set_sticker_set_thumb(name='test', user_id=123456789, thumb='file_id') - assert isinstance(result, bool) - assert result is True + if not isinstance(result, bool): + raise AssertionError + if result is not True: + raise AssertionError async def test_bot_id(bot: Bot): """ Check getting id from token. """ bot = Bot(TOKEN) - assert bot.id == BOT_ID # BOT_ID is a correct id from TOKEN + if bot.id != BOT_ID: + raise AssertionError diff --git a/tests/test_bot/test_api.py b/tests/test_bot/test_api.py index 29418169..9b494154 100644 --- a/tests/test_bot/test_api.py +++ b/tests/test_bot/test_api.py @@ -25,7 +25,8 @@ def invalid_token_fixture(request): class TestCheckToken: def test_valid(self): - assert check_token(VALID_TOKEN) is True + if check_token(VALID_TOKEN) is not True: + raise AssertionError def test_invalid_token(self, invalid_token): with pytest.raises(ValidationError): diff --git a/tests/test_bot/test_session.py b/tests/test_bot/test_session.py index 5458e3c8..9115daa3 100644 --- a/tests/test_bot/test_session.py +++ b/tests/test_bot/test_session.py @@ -16,16 +16,24 @@ class TestAiohttpSession: async def test_create_bot(self): bot = BaseBot(token="42:correct") - assert bot._session is None - assert isinstance(bot._connector_init, dict) - assert all(key in {"limit", "ssl", "loop"} for key in bot._connector_init) - assert isinstance(bot._connector_class, type) - assert issubclass(bot._connector_class, aiohttp.TCPConnector) + if bot._session is not None: + raise AssertionError + if not isinstance(bot._connector_init, dict): + raise AssertionError + if not all(key in {"limit", "ssl", "loop"} for key in bot._connector_init): + raise AssertionError + if not isinstance(bot._connector_class, type): + raise AssertionError + if not issubclass(bot._connector_class, aiohttp.TCPConnector): + raise AssertionError - assert bot._session is None + if bot._session is not None: + raise AssertionError - assert isinstance(bot.session, aiohttp.ClientSession) - assert bot.session == bot._session + if not isinstance(bot.session, aiohttp.ClientSession): + raise AssertionError + if bot.session != bot._session: + raise AssertionError @pytest.mark.asyncio async def test_create_proxy_bot(self): @@ -39,15 +47,21 @@ class TestAiohttpSession: proxy_auth=aiohttp.BasicAuth(username, password, "encoding"), ) - assert bot._connector_class == aiohttp_socks.SocksConnector + if bot._connector_class != aiohttp_socks.SocksConnector: + raise AssertionError - assert isinstance(bot._connector_init, dict) + if not isinstance(bot._connector_init, dict): + raise AssertionError init_kwargs = bot._connector_init - assert init_kwargs["username"] == username - assert init_kwargs["password"] == password - assert init_kwargs["host"] == host - assert init_kwargs["port"] == port + if init_kwargs["username"] != username: + raise AssertionError + if init_kwargs["password"] != password: + raise AssertionError + if init_kwargs["host"] != host: + raise AssertionError + if init_kwargs["port"] != port: + raise AssertionError @pytest.mark.asyncio async def test_close_session(self): @@ -59,4 +73,5 @@ class TestAiohttpSession: mocked_close.assert_called_once() await aiohttp_client_0.close() - assert aiohttp_client_0 != bot.session # will create new session + if aiohttp_client_0 == bot.session: + raise AssertionError diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index 700bda2d..9e146220 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -23,7 +23,8 @@ class TestDispatcherInit: :type bot: Bot """ dp = Dispatcher(bot=bot) - assert isinstance(dp, Dispatcher) + if not isinstance(dp, Dispatcher): + raise AssertionError @pytest.mark.parametrize("bot_instance", [None, Bot, 123, 'abc']) async def test_wrong_bot_instance(self, bot_instance): diff --git a/tests/test_dispatcher/test_filters/test_builtin.py b/tests/test_dispatcher/test_filters/test_builtin.py index edfc9291..88b3f754 100644 --- a/tests/test_dispatcher/test_filters/test_builtin.py +++ b/tests/test_dispatcher/test_filters/test_builtin.py @@ -23,7 +23,8 @@ class TestText: value = 'spam and eggs' config = {param: value} res = Text.validate(config) - assert res == {key: value} + if res != {key: value}: + raise AssertionError @pytest.mark.parametrize( @@ -70,7 +71,8 @@ class TestText: ), ) def test_extract_chat_ids(chat_id: ChatIDArgumentType, expected: Set[int]): - assert extract_chat_ids(chat_id) == expected + if extract_chat_ids(chat_id) != expected: + raise AssertionError class TestForwardedMessageFilter: @@ -84,7 +86,8 @@ class TestForwardedMessageFilter: not_forwarded_message = Message(**MESSAGE) assert await filter.check(forwarded_message) - assert not await filter.check(not_forwarded_message) + if await filter.check(not_forwarded_message): + raise AssertionError @pytest.mark.asyncio async def test_filter_not_forwarded_messages(self): @@ -95,7 +98,8 @@ class TestForwardedMessageFilter: not_forwarded_message = Message(**MESSAGE) assert await filter.check(not_forwarded_message) - assert not await filter.check(forwarded_message) + if await filter.check(forwarded_message): + raise AssertionError class TestIDFilter: diff --git a/tests/test_dispatcher/test_filters/test_state.py b/tests/test_dispatcher/test_filters/test_state.py index f7ca6d12..78bebe01 100644 --- a/tests/test_dispatcher/test_filters/test_state.py +++ b/tests/test_dispatcher/test_filters/test_state.py @@ -16,4 +16,5 @@ class TestStatesGroup: inner2 = InnerState2 form_childs = Form.all_childs - assert form_childs == (InnerState1, InnerState2) + if form_childs != (InnerState1, InnerState2): + raise AssertionError diff --git a/tests/test_dispatcher/test_handler.py b/tests/test_dispatcher/test_handler.py index b823c8f8..993176af 100644 --- a/tests/test_dispatcher/test_handler.py +++ b/tests/test_dispatcher/test_handler.py @@ -38,10 +38,14 @@ class TestHandlerObj: obj1 = Handler.HandlerObj(callback1, _get_spec(callback1)) obj2 = Handler.HandlerObj(callback2, _get_spec(callback2)) - assert set(obj1.spec.args) == {"foo", "bar", "baz"} - assert obj1.handler == callback1 - assert set(obj2.spec.args) == {"foo", "bar", "baz"} - assert obj2.handler == callback2 + if set(obj1.spec.args) != {"foo", "bar", "baz"}: + raise AssertionError + if obj1.handler != callback1: + raise AssertionError + if set(obj2.spec.args) != {"foo", "bar", "baz"}: + raise AssertionError + if obj2.handler != callback2: + raise AssertionError @pytest.mark.parametrize( "callback,kwargs,result", @@ -63,4 +67,5 @@ class TestHandlerObj: ) def test__check_spec(self, callback, kwargs, result): spec = _get_spec(callback) - assert _check_spec(spec, kwargs) == result + if _check_spec(spec, kwargs) != result: + raise AssertionError diff --git a/tests/test_filters.py b/tests/test_filters.py index 90693529..940b166e 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -256,7 +256,8 @@ class TestTextFilter: else: _test_filter_list = test_filter_list _test_text = test_text - assert result is (_test_text in _test_filter_list) + if result is not (_test_text in _test_filter_list): + raise AssertionError await check(Message(text=test_text)) await check(CallbackQuery(data=test_text)) @@ -276,36 +277,43 @@ class TestCommandStart: test_filter = CommandStart() # empty filter message = Message(text=self.START) result = await test_filter.check(message) - assert result + if not result: + raise AssertionError async def test_start_command_payload_is_matched(self): test_filter = CommandStart(deep_link=self.GOOD) message = Message(text=f'{self.START} {self.GOOD}') result = await test_filter.check(message) - assert result == {'deep_link': self.GOOD} + if result != {'deep_link': self.GOOD}: + raise AssertionError async def test_start_command_payload_is_not_matched(self): test_filter = CommandStart(deep_link=self.GOOD) message = Message(text=f'{self.START} {self.BAD}') result = await test_filter.check(message) - assert result is False + if result is not False: + raise AssertionError async def test_start_command_payload_pattern_is_matched(self): test_filter = CommandStart(deep_link=self.GOOD_PATTERN) message = Message(text=f'{self.START} {self.GOOD}') result = await test_filter.check(message) - assert isinstance(result, dict) + if not isinstance(result, dict): + raise AssertionError match = result.get('deep_link') - assert isinstance(match, Match) + if not isinstance(match, Match): + raise AssertionError async def test_start_command_payload_pattern_is_not_matched(self): test_filter = CommandStart(deep_link=self.BAD_PATTERN) message = Message(text=f'{self.START} {self.GOOD}') result = await test_filter.check(message) - assert result is False + if result is not False: + raise AssertionError async def test_start_command_payload_is_encoded(self): test_filter = CommandStart(deep_link=self.GOOD, encoded=True) message = Message(text=f'{self.START} {self.ENCODED}') result = await test_filter.check(message) - assert result == {'deep_link': self.GOOD} + if result != {'deep_link': self.GOOD}: + raise AssertionError diff --git a/tests/test_states_group.py b/tests/test_states_group.py index 47e49ce1..ebec1f64 100644 --- a/tests/test_states_group.py +++ b/tests/test_states_group.py @@ -26,78 +26,102 @@ alone_in_group = State('alone', group_name='home') def test_default_state(): - assert default_state.state is None + if default_state.state is not None: + raise AssertionError def test_any_state(): - assert any_state.state == '*' + if any_state.state != '*': + raise AssertionError def test_alone_state(): - assert alone_state.state == '@:alone' - assert alone_in_group.state == 'home:alone' + if alone_state.state != '@:alone': + raise AssertionError + if alone_in_group.state != 'home:alone': + raise AssertionError def test_group_names(): - assert MyGroup.__group_name__ == 'MyGroup' - assert MyGroup.__full_group_name__ == 'MyGroup' + if MyGroup.__group_name__ != 'MyGroup': + raise AssertionError + if MyGroup.__full_group_name__ != 'MyGroup': + raise AssertionError - assert MyGroup.MySubGroup.__group_name__ == 'MySubGroup' - assert MyGroup.MySubGroup.__full_group_name__ == 'MyGroup.MySubGroup' + if MyGroup.MySubGroup.__group_name__ != 'MySubGroup': + raise AssertionError + if MyGroup.MySubGroup.__full_group_name__ != 'MyGroup.MySubGroup': + raise AssertionError - assert MyGroup.MySubGroup.NewGroup.__group_name__ == 'NewGroup' - assert MyGroup.MySubGroup.NewGroup.__full_group_name__ == 'MyGroup.MySubGroup.NewGroup' + if MyGroup.MySubGroup.NewGroup.__group_name__ != 'NewGroup': + raise AssertionError + if MyGroup.MySubGroup.NewGroup.__full_group_name__ != 'MyGroup.MySubGroup.NewGroup': + raise AssertionError def test_custom_group_in_group(): - assert MyGroup.MySubGroup.in_custom_group.state == 'custom_group:in_custom_group' + if MyGroup.MySubGroup.in_custom_group.state != 'custom_group:in_custom_group': + raise AssertionError def test_custom_state_name_in_group(): - assert MyGroup.MySubGroup.NewGroup.renamed_state.state == 'MyGroup.MySubGroup.NewGroup:spam_state' + if MyGroup.MySubGroup.NewGroup.renamed_state.state != 'MyGroup.MySubGroup.NewGroup:spam_state': + raise AssertionError def test_group_states_names(): - assert len(MyGroup.states) == 3 - assert len(MyGroup.all_states) == 9 + if len(MyGroup.states) != 3: + raise AssertionError + if len(MyGroup.all_states) != 9: + raise AssertionError - assert MyGroup.states_names == ('MyGroup:state', 'MyGroup:state_1', 'MyGroup:state_2') - assert MyGroup.MySubGroup.states_names == ( + if MyGroup.states_names != ('MyGroup:state', 'MyGroup:state_1', 'MyGroup:state_2'): + raise AssertionError + if MyGroup.MySubGroup.states_names != ( 'MyGroup.MySubGroup:sub_state', 'MyGroup.MySubGroup:sub_state_1', 'MyGroup.MySubGroup:sub_state_2', - 'custom_group:in_custom_group') - assert MyGroup.MySubGroup.NewGroup.states_names == ( - 'MyGroup.MySubGroup.NewGroup:spam', 'MyGroup.MySubGroup.NewGroup:spam_state') + 'custom_group:in_custom_group'): + raise AssertionError + if MyGroup.MySubGroup.NewGroup.states_names != ( + 'MyGroup.MySubGroup.NewGroup:spam', 'MyGroup.MySubGroup.NewGroup:spam_state'): + raise AssertionError - assert MyGroup.all_states_names == ( + if MyGroup.all_states_names != ( 'MyGroup:state', 'MyGroup:state_1', 'MyGroup:state_2', 'MyGroup.MySubGroup:sub_state', 'MyGroup.MySubGroup:sub_state_1', 'MyGroup.MySubGroup:sub_state_2', 'custom_group:in_custom_group', 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state') + 'MyGroup.MySubGroup.NewGroup:spam_state'): + raise AssertionError - assert MyGroup.MySubGroup.all_states_names == ( + if MyGroup.MySubGroup.all_states_names != ( 'MyGroup.MySubGroup:sub_state', 'MyGroup.MySubGroup:sub_state_1', 'MyGroup.MySubGroup:sub_state_2', 'custom_group:in_custom_group', 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state') + 'MyGroup.MySubGroup.NewGroup:spam_state'): + raise AssertionError - assert MyGroup.MySubGroup.NewGroup.all_states_names == ( + if MyGroup.MySubGroup.NewGroup.all_states_names != ( 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state') + 'MyGroup.MySubGroup.NewGroup:spam_state'): + raise AssertionError def test_root_element(): root = MyGroup.MySubGroup.NewGroup.spam.get_root() - assert issubclass(root, StatesGroup) - assert root == MyGroup + if not issubclass(root, StatesGroup): + raise AssertionError + if root != MyGroup: + raise AssertionError - assert root == MyGroup.state.get_root() - assert root == MyGroup.MySubGroup.get_root() + if root != MyGroup.state.get_root(): + raise AssertionError + if root != MyGroup.MySubGroup.get_root(): + raise AssertionError with pytest.raises(RuntimeError): any_state.get_root() diff --git a/tests/test_utils/test_auth_widget.py b/tests/test_utils/test_auth_widget.py index 0f9d3542..c8bdd394 100644 --- a/tests/test_utils/test_auth_widget.py +++ b/tests/test_utils/test_auth_widget.py @@ -21,7 +21,8 @@ def data(): def test_generate_hash(data): res = generate_hash(data, TOKEN) - assert res == data['hash'] + if res != data['hash']: + raise AssertionError class Test_check_token: @@ -29,18 +30,22 @@ class Test_check_token: This case gonna be deleted """ def test_ok(self, data): - assert check_token(data, TOKEN) is True + if check_token(data, TOKEN) is not True: + raise AssertionError def test_fail(self, data): data.pop('username') - assert check_token(data, TOKEN) is False + if check_token(data, TOKEN) is not False: + raise AssertionError class Test_check_integrity: def test_ok(self, data): - assert check_integrity(TOKEN, data) is True + if check_integrity(TOKEN, data) is not True: + raise AssertionError def test_fail(self, data): data.pop('username') - assert check_integrity(TOKEN, data) is False + if check_integrity(TOKEN, data) is not False: + raise AssertionError diff --git a/tests/test_utils/test_deep_linking.py b/tests/test_utils/test_deep_linking.py index 18ec0235..69821c70 100644 --- a/tests/test_utils/test_deep_linking.py +++ b/tests/test_utils/test_deep_linking.py @@ -48,7 +48,8 @@ def get_bot_user_fixture(monkeypatch): class TestDeepLinking: async def test_get_start_link(self, payload): link = await get_start_link(payload) - assert link == f'https://t.me/{dataset.USER["username"]}?start={payload}' + if link != f'https://t.me/{dataset.USER["username"]}?start={payload}': + raise AssertionError async def test_wrong_symbols(self, wrong_payload): with pytest.raises(ValueError): @@ -56,13 +57,15 @@ class TestDeepLinking: async def test_get_startgroup_link(self, payload): link = await get_startgroup_link(payload) - assert link == f'https://t.me/{dataset.USER["username"]}?startgroup={payload}' + if link != f'https://t.me/{dataset.USER["username"]}?startgroup={payload}': + raise AssertionError async def test_filter_encode_and_decode(self, payload): _payload = filter_payload(payload) encoded = encode_payload(_payload) decoded = decode_payload(encoded) - assert decoded == str(payload) + if decoded != str(payload): + raise AssertionError async def test_get_start_link_with_encoding(self, payload): # define link @@ -72,4 +75,5 @@ class TestDeepLinking: payload = filter_payload(payload) encoded_payload = encode_payload(payload) - assert link == f'https://t.me/{dataset.USER["username"]}?start={encoded_payload}' + if link != f'https://t.me/{dataset.USER["username"]}?start={encoded_payload}': + raise AssertionError diff --git a/tests/test_utils/test_deprecated.py b/tests/test_utils/test_deprecated.py index e40189c1..f7178e0e 100644 --- a/tests/test_utils/test_deprecated.py +++ b/tests/test_utils/test_deprecated.py @@ -4,11 +4,13 @@ from aiogram.utils.deprecated import DeprecatedReadOnlyClassVar def test_DeprecatedReadOnlyClassVarCD(): - assert DeprecatedReadOnlyClassVar.__slots__ == ("_new_value_getter", "_warning_message") + if DeprecatedReadOnlyClassVar.__slots__ != ("_new_value_getter", "_warning_message"): + raise AssertionError new_value_of_deprecated_cls_cd = "mpa" deprecated_cd = DeprecatedReadOnlyClassVar("mopekaa", lambda owner: new_value_of_deprecated_cls_cd) with pytest.warns(DeprecationWarning): pseudo_owner_cls = type("OpekaCla$$", (), {}) - assert deprecated_cd.__get__(None, pseudo_owner_cls) == new_value_of_deprecated_cls_cd + if deprecated_cd.__get__(None, pseudo_owner_cls) != new_value_of_deprecated_cls_cd: + raise AssertionError diff --git a/tests/test_utils/test_helper.py b/tests/test_utils/test_helper.py index f90dacf1..4950dd7e 100644 --- a/tests/test_utils/test_helper.py +++ b/tests/test_utils/test_helper.py @@ -10,7 +10,8 @@ class TestOrderedHelper: C = Item() B = Item() - assert Helper.all() == ['A', 'D', 'C', 'B'] + if Helper.all() != ['A', 'D', 'C', 'B']: + raise AssertionError def test_list_items_are_ordered(self): class Helper(OrderedHelper): @@ -19,4 +20,5 @@ class TestOrderedHelper: C = ListItem() B = ListItem() - assert Helper.all() == ['A', 'D', 'C', 'B'] + if Helper.all() != ['A', 'D', 'C', 'B']: + raise AssertionError diff --git a/tests/test_utils/test_markdown.py b/tests/test_utils/test_markdown.py index 02faea2a..2a006dd1 100644 --- a/tests/test_utils/test_markdown.py +++ b/tests/test_utils/test_markdown.py @@ -5,7 +5,9 @@ from aiogram.utils import markdown class TestMarkdownEscape: def test_equality_sign_is_escaped(self): - assert markdown.escape_md(r"e = mc2") == r"e \= mc2" + if markdown.escape_md(r"e = mc2") != r"e \= mc2": + raise AssertionError def test_pre_escaped(self): - assert markdown.escape_md(r"hello\.") == r"hello\\\." + if markdown.escape_md(r"hello\.") != r"hello\\\.": + raise AssertionError diff --git a/tests/test_utils/test_text_decorations.py b/tests/test_utils/test_text_decorations.py index cc724dd7..2ebf77c5 100644 --- a/tests/test_utils/test_text_decorations.py +++ b/tests/test_utils/test_text_decorations.py @@ -4,22 +4,24 @@ from aiogram.utils import text_decorations class TestTextDecorations: def test_unparse_entities_normal_text(self): - assert text_decorations.markdown_decoration.unparse( + if text_decorations.markdown_decoration.unparse( "hi i'm bold and italic and still bold", entities=[ MessageEntity(offset=3, length=34, type=MessageEntityType.BOLD), MessageEntity(offset=12, length=10, type=MessageEntityType.ITALIC), ] - ) == "hi *i'm bold _\rand italic_\r and still bold*" + ) != "hi *i'm bold _\rand italic_\r and still bold*": + raise AssertionError def test_unparse_entities_emoji_text(self): """ emoji is encoded as two chars in json """ - assert text_decorations.markdown_decoration.unparse( + if text_decorations.markdown_decoration.unparse( "🚀 i'm bold and italic and still bold", entities=[ MessageEntity(offset=3, length=34, type=MessageEntityType.BOLD), MessageEntity(offset=12, length=10, type=MessageEntityType.ITALIC), ] - ) == "🚀 *i'm bold _\rand italic_\r and still bold*" + ) != "🚀 *i'm bold _\rand italic_\r and still bold*": + raise AssertionError diff --git a/tests/types/test_animation.py b/tests/types/test_animation.py index 29adeab4..3e8a075d 100644 --- a/tests/types/test_animation.py +++ b/tests/types/test_animation.py @@ -7,34 +7,49 @@ animation = types.Animation(**ANIMATION) def test_export(): exported = animation.to_python() - assert isinstance(exported, dict) - assert exported == ANIMATION + if not isinstance(exported, dict): + raise AssertionError + if exported != ANIMATION: + raise AssertionError def test_file_name(): - assert isinstance(animation.file_name, str) - assert animation.file_name == ANIMATION['file_name'] + if not isinstance(animation.file_name, str): + raise AssertionError + if animation.file_name != ANIMATION['file_name']: + raise AssertionError def test_mime_type(): - assert isinstance(animation.mime_type, str) - assert animation.mime_type == ANIMATION['mime_type'] + if not isinstance(animation.mime_type, str): + raise AssertionError + if animation.mime_type != ANIMATION['mime_type']: + raise AssertionError def test_file_id(): - assert isinstance(animation.file_id, str) + if not isinstance(animation.file_id, str): + raise AssertionError # assert hash(animation) == ANIMATION['file_id'] - assert animation.file_id == ANIMATION['file_id'] + if animation.file_id != ANIMATION['file_id']: + raise AssertionError def test_file_size(): - assert isinstance(animation.file_size, int) - assert animation.file_size == ANIMATION['file_size'] + if not isinstance(animation.file_size, int): + raise AssertionError + if animation.file_size != ANIMATION['file_size']: + raise AssertionError def test_thumb(): - assert isinstance(animation.thumb, types.PhotoSize) - assert animation.thumb.file_id == ANIMATION['thumb']['file_id'] - assert animation.thumb.width == ANIMATION['thumb']['width'] - assert animation.thumb.height == ANIMATION['thumb']['height'] - assert animation.thumb.file_size == ANIMATION['thumb']['file_size'] + if not isinstance(animation.thumb, types.PhotoSize): + raise AssertionError + if animation.thumb.file_id != ANIMATION['thumb']['file_id']: + raise AssertionError + if animation.thumb.width != ANIMATION['thumb']['width']: + raise AssertionError + if animation.thumb.height != ANIMATION['thumb']['height']: + raise AssertionError + if animation.thumb.file_size != ANIMATION['thumb']['file_size']: + raise AssertionError diff --git a/tests/types/test_chat.py b/tests/types/test_chat.py index a8b50764..a01447b6 100644 --- a/tests/types/test_chat.py +++ b/tests/types/test_chat.py @@ -7,56 +7,87 @@ chat = types.Chat(**CHAT) def test_export(): exported = chat.to_python() - assert isinstance(exported, dict) - assert exported == CHAT + if not isinstance(exported, dict): + raise AssertionError + if exported != CHAT: + raise AssertionError def test_id(): - assert isinstance(chat.id, int) - assert chat.id == CHAT['id'] + if not isinstance(chat.id, int): + raise AssertionError + if chat.id != CHAT['id']: + raise AssertionError # assert hash(chat) == CHAT['id'] def test_name(): - assert isinstance(chat.first_name, str) - assert chat.first_name == CHAT['first_name'] + if not isinstance(chat.first_name, str): + raise AssertionError + if chat.first_name != CHAT['first_name']: + raise AssertionError - assert isinstance(chat.last_name, str) - assert chat.last_name == CHAT['last_name'] + if not isinstance(chat.last_name, str): + raise AssertionError + if chat.last_name != CHAT['last_name']: + raise AssertionError - assert isinstance(chat.username, str) - assert chat.username == CHAT['username'] + if not isinstance(chat.username, str): + raise AssertionError + if chat.username != CHAT['username']: + raise AssertionError def test_type(): - assert isinstance(chat.type, str) - assert chat.type == CHAT['type'] + if not isinstance(chat.type, str): + raise AssertionError + if chat.type != CHAT['type']: + raise AssertionError def test_chat_types(): - assert types.ChatType.PRIVATE == 'private' - assert types.ChatType.GROUP == 'group' - assert types.ChatType.SUPER_GROUP == 'supergroup' - assert types.ChatType.CHANNEL == 'channel' + if types.ChatType.PRIVATE != 'private': + raise AssertionError + if types.ChatType.GROUP != 'group': + raise AssertionError + if types.ChatType.SUPER_GROUP != 'supergroup': + raise AssertionError + if types.ChatType.CHANNEL != 'channel': + raise AssertionError def test_chat_type_filters(): from . import test_message - assert types.ChatType.is_private(test_message.message) - assert not types.ChatType.is_group(test_message.message) - assert not types.ChatType.is_super_group(test_message.message) - assert not types.ChatType.is_group_or_super_group(test_message.message) - assert not types.ChatType.is_channel(test_message.message) + if not types.ChatType.is_private(test_message.message): + raise AssertionError + if types.ChatType.is_group(test_message.message): + raise AssertionError + if types.ChatType.is_super_group(test_message.message): + raise AssertionError + if types.ChatType.is_group_or_super_group(test_message.message): + raise AssertionError + if types.ChatType.is_channel(test_message.message): + raise AssertionError def test_chat_actions(): - assert types.ChatActions.TYPING == 'typing' - assert types.ChatActions.UPLOAD_PHOTO == 'upload_photo' - assert types.ChatActions.RECORD_VIDEO == 'record_video' - assert types.ChatActions.UPLOAD_VIDEO == 'upload_video' - assert types.ChatActions.RECORD_AUDIO == 'record_audio' - assert types.ChatActions.UPLOAD_AUDIO == 'upload_audio' - assert types.ChatActions.UPLOAD_DOCUMENT == 'upload_document' - assert types.ChatActions.FIND_LOCATION == 'find_location' - assert types.ChatActions.RECORD_VIDEO_NOTE == 'record_video_note' - assert types.ChatActions.UPLOAD_VIDEO_NOTE == 'upload_video_note' + if types.ChatActions.TYPING != 'typing': + raise AssertionError + if types.ChatActions.UPLOAD_PHOTO != 'upload_photo': + raise AssertionError + if types.ChatActions.RECORD_VIDEO != 'record_video': + raise AssertionError + if types.ChatActions.UPLOAD_VIDEO != 'upload_video': + raise AssertionError + if types.ChatActions.RECORD_AUDIO != 'record_audio': + raise AssertionError + if types.ChatActions.UPLOAD_AUDIO != 'upload_audio': + raise AssertionError + if types.ChatActions.UPLOAD_DOCUMENT != 'upload_document': + raise AssertionError + if types.ChatActions.FIND_LOCATION != 'find_location': + raise AssertionError + if types.ChatActions.RECORD_VIDEO_NOTE != 'record_video_note': + raise AssertionError + if types.ChatActions.UPLOAD_VIDEO_NOTE != 'upload_video_note': + raise AssertionError diff --git a/tests/types/test_chat_member.py b/tests/types/test_chat_member.py index 8e8d2cfe..d8cbac10 100644 --- a/tests/types/test_chat_member.py +++ b/tests/types/test_chat_member.py @@ -7,72 +7,111 @@ chat_member = types.ChatMember(**CHAT_MEMBER) def test_export(): exported = chat_member.to_python() - assert isinstance(exported, dict) - assert exported == CHAT_MEMBER + if not isinstance(exported, dict): + raise AssertionError + if exported != CHAT_MEMBER: + raise AssertionError def test_user(): - assert isinstance(chat_member.user, types.User) + if not isinstance(chat_member.user, types.User): + raise AssertionError def test_status(): - assert isinstance(chat_member.status, str) - assert chat_member.status == CHAT_MEMBER['status'] + if not isinstance(chat_member.status, str): + raise AssertionError + if chat_member.status != CHAT_MEMBER['status']: + raise AssertionError def test_privileges(): - assert isinstance(chat_member.can_be_edited, bool) - assert chat_member.can_be_edited == CHAT_MEMBER['can_be_edited'] + if not isinstance(chat_member.can_be_edited, bool): + raise AssertionError + if chat_member.can_be_edited != CHAT_MEMBER['can_be_edited']: + raise AssertionError - assert isinstance(chat_member.can_change_info, bool) - assert chat_member.can_change_info == CHAT_MEMBER['can_change_info'] + if not isinstance(chat_member.can_change_info, bool): + raise AssertionError + if chat_member.can_change_info != CHAT_MEMBER['can_change_info']: + raise AssertionError - assert isinstance(chat_member.can_delete_messages, bool) - assert chat_member.can_delete_messages == CHAT_MEMBER['can_delete_messages'] + if not isinstance(chat_member.can_delete_messages, bool): + raise AssertionError + if chat_member.can_delete_messages != CHAT_MEMBER['can_delete_messages']: + raise AssertionError - assert isinstance(chat_member.can_invite_users, bool) - assert chat_member.can_invite_users == CHAT_MEMBER['can_invite_users'] + if not isinstance(chat_member.can_invite_users, bool): + raise AssertionError + if chat_member.can_invite_users != CHAT_MEMBER['can_invite_users']: + raise AssertionError - assert isinstance(chat_member.can_restrict_members, bool) - assert chat_member.can_restrict_members == CHAT_MEMBER['can_restrict_members'] + if not isinstance(chat_member.can_restrict_members, bool): + raise AssertionError + if chat_member.can_restrict_members != CHAT_MEMBER['can_restrict_members']: + raise AssertionError - assert isinstance(chat_member.can_pin_messages, bool) - assert chat_member.can_pin_messages == CHAT_MEMBER['can_pin_messages'] + if not isinstance(chat_member.can_pin_messages, bool): + raise AssertionError + if chat_member.can_pin_messages != CHAT_MEMBER['can_pin_messages']: + raise AssertionError - assert isinstance(chat_member.can_promote_members, bool) - assert chat_member.can_promote_members == CHAT_MEMBER['can_promote_members'] + if not isinstance(chat_member.can_promote_members, bool): + raise AssertionError + if chat_member.can_promote_members != CHAT_MEMBER['can_promote_members']: + raise AssertionError def test_int(): - assert int(chat_member) == chat_member.user.id - assert isinstance(int(chat_member), int) + if int(chat_member) != chat_member.user.id: + raise AssertionError + if not isinstance(int(chat_member), int): + raise AssertionError def test_chat_member_status(): - assert types.ChatMemberStatus.CREATOR == 'creator' - assert types.ChatMemberStatus.ADMINISTRATOR == 'administrator' - assert types.ChatMemberStatus.MEMBER == 'member' - assert types.ChatMemberStatus.RESTRICTED == 'restricted' - assert types.ChatMemberStatus.LEFT == 'left' - assert types.ChatMemberStatus.KICKED == 'kicked' + if types.ChatMemberStatus.CREATOR != 'creator': + raise AssertionError + if types.ChatMemberStatus.ADMINISTRATOR != 'administrator': + raise AssertionError + if types.ChatMemberStatus.MEMBER != 'member': + raise AssertionError + if types.ChatMemberStatus.RESTRICTED != 'restricted': + raise AssertionError + if types.ChatMemberStatus.LEFT != 'left': + raise AssertionError + if types.ChatMemberStatus.KICKED != 'kicked': + raise AssertionError def test_chat_member_status_filters(): - assert types.ChatMemberStatus.is_chat_admin(chat_member.status) - assert types.ChatMemberStatus.is_chat_member(chat_member.status) + if not types.ChatMemberStatus.is_chat_admin(chat_member.status): + raise AssertionError + if not types.ChatMemberStatus.is_chat_member(chat_member.status): + raise AssertionError - assert types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.CREATOR) - assert types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.ADMINISTRATOR) + if not types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.CREATOR): + raise AssertionError + if not types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.ADMINISTRATOR): + raise AssertionError - assert types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.CREATOR) - assert types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.ADMINISTRATOR) - assert types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.MEMBER) - assert types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.RESTRICTED) + if not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.CREATOR): + raise AssertionError + if not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.ADMINISTRATOR): + raise AssertionError + if not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.MEMBER): + raise AssertionError + if not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.RESTRICTED): + raise AssertionError - assert not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.LEFT) - assert not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.KICKED) + if types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.LEFT): + raise AssertionError + if types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.KICKED): + raise AssertionError def test_chat_member_filters(): - assert chat_member.is_chat_admin() - assert chat_member.is_chat_member() + if not chat_member.is_chat_admin(): + raise AssertionError + if not chat_member.is_chat_member(): + raise AssertionError diff --git a/tests/types/test_document.py b/tests/types/test_document.py index eb353ae6..4a76975a 100644 --- a/tests/types/test_document.py +++ b/tests/types/test_document.py @@ -7,30 +7,41 @@ document = types.Document(**DOCUMENT) def test_export(): exported = document.to_python() - assert isinstance(exported, dict) - assert exported == DOCUMENT + if not isinstance(exported, dict): + raise AssertionError + if exported != DOCUMENT: + raise AssertionError def test_file_name(): - assert isinstance(document.file_name, str) - assert document.file_name == DOCUMENT['file_name'] + if not isinstance(document.file_name, str): + raise AssertionError + if document.file_name != DOCUMENT['file_name']: + raise AssertionError def test_mime_type(): - assert isinstance(document.mime_type, str) - assert document.mime_type == DOCUMENT['mime_type'] + if not isinstance(document.mime_type, str): + raise AssertionError + if document.mime_type != DOCUMENT['mime_type']: + raise AssertionError def test_file_id(): - assert isinstance(document.file_id, str) + if not isinstance(document.file_id, str): + raise AssertionError # assert hash(document) == DOCUMENT['file_id'] - assert document.file_id == DOCUMENT['file_id'] + if document.file_id != DOCUMENT['file_id']: + raise AssertionError def test_file_size(): - assert isinstance(document.file_size, int) - assert document.file_size == DOCUMENT['file_size'] + if not isinstance(document.file_size, int): + raise AssertionError + if document.file_size != DOCUMENT['file_size']: + raise AssertionError def test_thumb(): - assert document.thumb is None + if document.thumb is not None: + raise AssertionError diff --git a/tests/types/test_game.py b/tests/types/test_game.py index 8350d858..484cc258 100644 --- a/tests/types/test_game.py +++ b/tests/types/test_game.py @@ -7,25 +7,35 @@ game = types.Game(**GAME) def test_export(): exported = game.to_python() - assert isinstance(exported, dict) - assert exported == GAME + if not isinstance(exported, dict): + raise AssertionError + if exported != GAME: + raise AssertionError def test_title(): - assert isinstance(game.title, str) - assert game.title == GAME['title'] + if not isinstance(game.title, str): + raise AssertionError + if game.title != GAME['title']: + raise AssertionError def test_description(): - assert isinstance(game.description, str) - assert game.description == GAME['description'] + if not isinstance(game.description, str): + raise AssertionError + if game.description != GAME['description']: + raise AssertionError def test_photo(): - assert isinstance(game.photo, list) - assert len(game.photo) == len(GAME['photo']) - assert all(map(lambda t: isinstance(t, types.PhotoSize), game.photo)) + if not isinstance(game.photo, list): + raise AssertionError + if len(game.photo) != len(GAME['photo']): + raise AssertionError + if not all(map(lambda t: isinstance(t, types.PhotoSize), game.photo)): + raise AssertionError def test_animation(): - assert isinstance(game.animation, types.Animation) + if not isinstance(game.animation, types.Animation): + raise AssertionError diff --git a/tests/types/test_input_media.py b/tests/types/test_input_media.py index f867e1f6..ca250a9e 100644 --- a/tests/types/test_input_media.py +++ b/tests/types/test_input_media.py @@ -21,21 +21,31 @@ def test_field_width(): """ https://core.telegram.org/bots/api#inputmedia """ - assert not hasattr(input_media_audio, WIDTH) - assert not hasattr(input_media_document, WIDTH) - assert not hasattr(input_media_photo, WIDTH) + if hasattr(input_media_audio, WIDTH): + raise AssertionError + if hasattr(input_media_document, WIDTH): + raise AssertionError + if hasattr(input_media_photo, WIDTH): + raise AssertionError - assert hasattr(input_media_animation, WIDTH) - assert hasattr(input_media_video, WIDTH) + if not hasattr(input_media_animation, WIDTH): + raise AssertionError + if not hasattr(input_media_video, WIDTH): + raise AssertionError def test_field_height(): """ https://core.telegram.org/bots/api#inputmedia """ - assert not hasattr(input_media_audio, HEIGHT) - assert not hasattr(input_media_document, HEIGHT) - assert not hasattr(input_media_photo, HEIGHT) + if hasattr(input_media_audio, HEIGHT): + raise AssertionError + if hasattr(input_media_document, HEIGHT): + raise AssertionError + if hasattr(input_media_photo, HEIGHT): + raise AssertionError - assert hasattr(input_media_animation, HEIGHT) - assert hasattr(input_media_video, HEIGHT) + if not hasattr(input_media_animation, HEIGHT): + raise AssertionError + if not hasattr(input_media_video, HEIGHT): + raise AssertionError diff --git a/tests/types/test_message.py b/tests/types/test_message.py index d68650ac..a668c204 100644 --- a/tests/types/test_message.py +++ b/tests/types/test_message.py @@ -9,32 +9,45 @@ message = types.Message(**MESSAGE) def test_export(): exported_chat = message.to_python() - assert isinstance(exported_chat, dict) - assert exported_chat == MESSAGE + if not isinstance(exported_chat, dict): + raise AssertionError + if exported_chat != MESSAGE: + raise AssertionError def test_message_id(): # assert hash(message) == MESSAGE['message_id'] - assert message.message_id == MESSAGE['message_id'] - assert message['message_id'] == MESSAGE['message_id'] + if message.message_id != MESSAGE['message_id']: + raise AssertionError + if message['message_id'] != MESSAGE['message_id']: + raise AssertionError def test_from(): - assert isinstance(message.from_user, types.User) - assert message.from_user == message['from'] + if not isinstance(message.from_user, types.User): + raise AssertionError + if message.from_user != message['from']: + raise AssertionError def test_chat(): - assert isinstance(message.chat, types.Chat) - assert message.chat == message['chat'] + if not isinstance(message.chat, types.Chat): + raise AssertionError + if message.chat != message['chat']: + raise AssertionError def test_date(): - assert isinstance(message.date, datetime.datetime) - assert int(message.date.timestamp()) == MESSAGE['date'] - assert message.date == message['date'] + if not isinstance(message.date, datetime.datetime): + raise AssertionError + if int(message.date.timestamp()) != MESSAGE['date']: + raise AssertionError + if message.date != message['date']: + raise AssertionError def test_text(): - assert message.text == MESSAGE['text'] - assert message['text'] == MESSAGE['text'] + if message.text != MESSAGE['text']: + raise AssertionError + if message['text'] != MESSAGE['text']: + raise AssertionError diff --git a/tests/types/test_photo.py b/tests/types/test_photo.py index d81a13a4..f2ed4915 100644 --- a/tests/types/test_photo.py +++ b/tests/types/test_photo.py @@ -7,22 +7,32 @@ photo = types.PhotoSize(**PHOTO) def test_export(): exported = photo.to_python() - assert isinstance(exported, dict) - assert exported == PHOTO + if not isinstance(exported, dict): + raise AssertionError + if exported != PHOTO: + raise AssertionError def test_file_id(): - assert isinstance(photo.file_id, str) - assert photo.file_id == PHOTO['file_id'] + if not isinstance(photo.file_id, str): + raise AssertionError + if photo.file_id != PHOTO['file_id']: + raise AssertionError def test_file_size(): - assert isinstance(photo.file_size, int) - assert photo.file_size == PHOTO['file_size'] + if not isinstance(photo.file_size, int): + raise AssertionError + if photo.file_size != PHOTO['file_size']: + raise AssertionError def test_size(): - assert isinstance(photo.width, int) - assert isinstance(photo.height, int) - assert photo.width == PHOTO['width'] - assert photo.height == PHOTO['height'] + if not isinstance(photo.width, int): + raise AssertionError + if not isinstance(photo.height, int): + raise AssertionError + if photo.width != PHOTO['width']: + raise AssertionError + if photo.height != PHOTO['height']: + raise AssertionError diff --git a/tests/types/test_reply_keyboard.py b/tests/types/test_reply_keyboard.py index ee6da29c..385f5fd1 100644 --- a/tests/types/test_reply_keyboard.py +++ b/tests/types/test_reply_keyboard.py @@ -6,8 +6,10 @@ reply_keyboard = types.ReplyKeyboardMarkup(**REPLY_KEYBOARD_MARKUP) def test_serialize(): - assert reply_keyboard.to_python() == REPLY_KEYBOARD_MARKUP + if reply_keyboard.to_python() != REPLY_KEYBOARD_MARKUP: + raise AssertionError def test_deserialize(): - assert reply_keyboard.to_object(reply_keyboard.to_python()) == reply_keyboard + if reply_keyboard.to_object(reply_keyboard.to_python()) != reply_keyboard: + raise AssertionError diff --git a/tests/types/test_update.py b/tests/types/test_update.py index 6309c315..d82d45fa 100644 --- a/tests/types/test_update.py +++ b/tests/types/test_update.py @@ -7,15 +7,20 @@ update = types.Update(**UPDATE) def test_export(): exported = update.to_python() - assert isinstance(exported, dict) - assert exported == UPDATE + if not isinstance(exported, dict): + raise AssertionError + if exported != UPDATE: + raise AssertionError def test_update_id(): - assert isinstance(update.update_id, int) + if not isinstance(update.update_id, int): + raise AssertionError # assert hash(update) == UPDATE['update_id'] - assert update.update_id == UPDATE['update_id'] + if update.update_id != UPDATE['update_id']: + raise AssertionError def test_message(): - assert isinstance(update.message, types.Message) + if not isinstance(update.message, types.Message): + raise AssertionError diff --git a/tests/types/test_user.py b/tests/types/test_user.py index 24b76f58..c1ca2f88 100644 --- a/tests/types/test_user.py +++ b/tests/types/test_user.py @@ -9,41 +9,57 @@ user = types.User(**USER) def test_export(): exported = user.to_python() - assert isinstance(exported, dict) - assert exported == USER + if not isinstance(exported, dict): + raise AssertionError + if exported != USER: + raise AssertionError def test_id(): - assert isinstance(user.id, int) - assert user.id == USER['id'] + if not isinstance(user.id, int): + raise AssertionError + if user.id != USER['id']: + raise AssertionError # assert hash(user) == USER['id'] def test_bot(): - assert isinstance(user.is_bot, bool) - assert user.is_bot == USER['is_bot'] + if not isinstance(user.is_bot, bool): + raise AssertionError + if user.is_bot != USER['is_bot']: + raise AssertionError def test_name(): - assert user.first_name == USER['first_name'] - assert user.last_name == USER['last_name'] - assert user.username == USER['username'] + if user.first_name != USER['first_name']: + raise AssertionError + if user.last_name != USER['last_name']: + raise AssertionError + if user.username != USER['username']: + raise AssertionError def test_language_code(): - assert user.language_code == USER['language_code'] - assert user.locale == Locale.parse(USER['language_code'], sep='-') + if user.language_code != USER['language_code']: + raise AssertionError + if user.locale != Locale.parse(USER['language_code'], sep='-'): + raise AssertionError def test_full_name(): - assert user.full_name == f"{USER['first_name']} {USER['last_name']}" + if user.full_name != f"{USER['first_name']} {USER['last_name']}": + raise AssertionError def test_mention(): - assert user.mention == f"@{USER['username']}" - assert user.get_mention('foo', as_html=False) == f"[foo](tg://user?id={USER['id']})" - assert user.get_mention('foo', as_html=True) == f"foo" + if user.mention != f"@{USER['username']}": + raise AssertionError + if user.get_mention('foo', as_html=False) != f"[foo](tg://user?id={USER['id']})": + raise AssertionError + if user.get_mention('foo', as_html=True) != f"foo": + raise AssertionError def test_url(): - assert user.url == f"tg://user?id={USER['id']}" + if user.url != f"tg://user?id={USER['id']}": + raise AssertionError From af4ceef1531c3750c4dd51a3fea3fedb6a801a1b Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Sun, 8 Nov 2020 21:49:34 +0000 Subject: [PATCH 2/2] Format code with black, autopep8 and isort This commit fixes the style issues introduced in dd50a9b according to the output from black, autopep8 and isort. Details: https://deepsource.io/gh/muhammedfurkan/aiogram/transform/4e472085-2e87-4f61-b7a1-ed208506962f/ --- aiogram/dispatcher/dispatcher.py | 877 ++++++++++++------ tests/conftest.py | 21 +- tests/contrib/fsm_storage/test_redis.py | 12 +- tests/test_bot.py | 251 +++-- tests/test_bot/test_api.py | 15 +- tests/test_bot/test_session.py | 10 +- tests/test_dispatcher.py | 4 +- .../test_filters/test_builtin.py | 122 ++- .../test_filters/test_state.py | 2 - tests/test_dispatcher/test_handler.py | 4 +- tests/test_filters.py | 248 ++--- tests/test_states_group.py | 81 +- tests/test_utils/test_auth_widget.py | 24 +- tests/test_utils/test_deep_linking.py | 17 +- tests/test_utils/test_deprecated.py | 14 +- tests/test_utils/test_helper.py | 5 +- tests/test_utils/test_markdown.py | 12 +- tests/test_utils/test_text_decorations.py | 52 +- tests/types/test_animation.py | 16 +- tests/types/test_chat.py | 39 +- tests/types/test_chat_member.py | 28 +- tests/types/test_document.py | 8 +- tests/types/test_game.py | 6 +- tests/types/test_input_media.py | 19 +- tests/types/test_message.py | 16 +- tests/types/test_photo.py | 8 +- tests/types/test_update.py | 2 +- tests/types/test_user.py | 21 +- 28 files changed, 1214 insertions(+), 720 deletions(-) diff --git a/aiogram/dispatcher/dispatcher.py b/aiogram/dispatcher/dispatcher.py index b074d60e..356cc104 100644 --- a/aiogram/dispatcher/dispatcher.py +++ b/aiogram/dispatcher/dispatcher.py @@ -14,11 +14,11 @@ from .. import types from ..bot import Bot from ..utils.exceptions import TelegramAPIError, Throttled from ..utils.mixins import ContextInstanceMixin, DataMixin -from .filters import ( - AbstractFilter, AdminFilter, ChatTypeFilter, Command, ContentTypeFilter, - ExceptionsFilter, FiltersFactory, ForwardedMessageFilter, HashTag, - IDFilter, IsReplyFilter, IsSenderContact, Regexp, RegexpCommandsFilter, - StateFilter, Text) +from .filters import (AbstractFilter, AdminFilter, ChatTypeFilter, Command, + ContentTypeFilter, ExceptionsFilter, FiltersFactory, + ForwardedMessageFilter, HashTag, IDFilter, IsReplyFilter, + IsSenderContact, Regexp, RegexpCommandsFilter, + StateFilter, Text) from .handler import Handler from .middlewares import MiddlewareManager from .storage import (DELTA, EXCEEDED_COUNT, LAST_CALL, RATE_LIMIT, RESULT, @@ -27,15 +27,15 @@ from .webhook import BaseResponse log = logging.getLogger(__name__) -DEFAULT_RATE_LIMIT = .1 +DEFAULT_RATE_LIMIT = 0.1 def _ensure_loop(x: "asyncio.AbstractEventLoop"): - if not isinstance( - x, asyncio.AbstractEventLoop - ): - raise AssertionError(f"Loop must be the implementation of {asyncio.AbstractEventLoop!r}, " \ - f"not {type(x)!r}") + if not isinstance(x, asyncio.AbstractEventLoop): + raise AssertionError( + f"Loop must be the implementation of {asyncio.AbstractEventLoop!r}, " + f"not {type(x)!r}" + ) class Dispatcher(DataMixin, ContextInstanceMixin): @@ -46,13 +46,21 @@ class Dispatcher(DataMixin, ContextInstanceMixin): inline queries, chosen inline results, callback queries, shipping queries, pre-checkout queries. """ - def __init__(self, bot, loop=None, storage: typing.Optional[BaseStorage] = None, - run_tasks_by_default: bool = False, - throttling_rate_limit=DEFAULT_RATE_LIMIT, no_throttle_error=False, - filters_factory=None): + def __init__( + self, + bot, + loop=None, + storage: typing.Optional[BaseStorage] = None, + run_tasks_by_default: bool = False, + throttling_rate_limit=DEFAULT_RATE_LIMIT, + no_throttle_error=False, + filters_factory=None, + ): if not isinstance(bot, Bot): - raise TypeError(f"Argument 'bot' must be an instance of Bot, not '{type(bot).__name__}'") + raise TypeError( + f"Argument 'bot' must be an instance of Bot, not '{type(bot).__name__}'" + ) if storage is None: storage = DisabledStorage() @@ -70,19 +78,31 @@ class Dispatcher(DataMixin, ContextInstanceMixin): self.no_throttle_error = no_throttle_error self.filters_factory: FiltersFactory = filters_factory - self.updates_handler = Handler(self, middleware_key='update') - self.message_handlers = Handler(self, middleware_key='message') - self.edited_message_handlers = Handler(self, middleware_key='edited_message') - self.channel_post_handlers = Handler(self, middleware_key='channel_post') - self.edited_channel_post_handlers = Handler(self, middleware_key='edited_channel_post') - self.inline_query_handlers = Handler(self, middleware_key='inline_query') - self.chosen_inline_result_handlers = Handler(self, middleware_key='chosen_inline_result') - self.callback_query_handlers = Handler(self, middleware_key='callback_query') - self.shipping_query_handlers = Handler(self, middleware_key='shipping_query') - self.pre_checkout_query_handlers = Handler(self, middleware_key='pre_checkout_query') - self.poll_handlers = Handler(self, middleware_key='poll') - self.poll_answer_handlers = Handler(self, middleware_key='poll_answer') - self.errors_handlers = Handler(self, once=False, middleware_key='error') + self.updates_handler = Handler(self, middleware_key="update") + self.message_handlers = Handler(self, middleware_key="message") + self.edited_message_handlers = Handler( + self, middleware_key="edited_message") + self.channel_post_handlers = Handler( + self, middleware_key="channel_post") + self.edited_channel_post_handlers = Handler( + self, middleware_key="edited_channel_post" + ) + self.inline_query_handlers = Handler( + self, middleware_key="inline_query") + self.chosen_inline_result_handlers = Handler( + self, middleware_key="chosen_inline_result" + ) + self.callback_query_handlers = Handler( + self, middleware_key="callback_query") + self.shipping_query_handlers = Handler( + self, middleware_key="shipping_query") + self.pre_checkout_query_handlers = Handler( + self, middleware_key="pre_checkout_query" + ) + self.poll_handlers = Handler(self, middleware_key="poll") + self.poll_answer_handlers = Handler(self, middleware_key="poll_answer") + self.errors_handlers = Handler( + self, once=False, middleware_key="error") self.middleware = MiddlewareManager(self) @@ -114,93 +134,133 @@ class Dispatcher(DataMixin, ContextInstanceMixin): def _setup_filters(self): filters_factory = self.filters_factory - filters_factory.bind(StateFilter, exclude_event_handlers=[ - self.errors_handlers, - self.poll_handlers, - self.poll_answer_handlers, - ]) - filters_factory.bind(ContentTypeFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - ]), - filters_factory.bind(Command, event_handlers=[ - self.message_handlers, - self.edited_message_handlers - ]) - filters_factory.bind(Text, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - self.callback_query_handlers, - self.poll_handlers, - self.inline_query_handlers, - ]) - filters_factory.bind(HashTag, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - ]) - filters_factory.bind(Regexp, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - self.callback_query_handlers, - self.poll_handlers, - self.inline_query_handlers, - ]) - filters_factory.bind(RegexpCommandsFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - ]) - filters_factory.bind(ExceptionsFilter, event_handlers=[ - self.errors_handlers, - ]) - filters_factory.bind(AdminFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - self.callback_query_handlers, - self.inline_query_handlers, - ]) - filters_factory.bind(IDFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - self.callback_query_handlers, - self.inline_query_handlers, - ]) - filters_factory.bind(IsReplyFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - ]) - filters_factory.bind(IsSenderContact, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - ]) - filters_factory.bind(ForwardedMessageFilter, event_handlers=[ - self.message_handlers, - self.edited_channel_post_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers - ]) - filters_factory.bind(ChatTypeFilter, event_handlers=[ - self.message_handlers, - self.edited_message_handlers, - self.channel_post_handlers, - self.edited_channel_post_handlers, - self.callback_query_handlers, - ]) + filters_factory.bind( + StateFilter, + exclude_event_handlers=[ + self.errors_handlers, + self.poll_handlers, + self.poll_answer_handlers, + ], + ) + filters_factory.bind( + ContentTypeFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + ], + ), + filters_factory.bind( + Command, + event_handlers=[self.message_handlers, + self.edited_message_handlers], + ) + filters_factory.bind( + Text, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + self.callback_query_handlers, + self.poll_handlers, + self.inline_query_handlers, + ], + ) + filters_factory.bind( + HashTag, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + ], + ) + filters_factory.bind( + Regexp, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + self.callback_query_handlers, + self.poll_handlers, + self.inline_query_handlers, + ], + ) + filters_factory.bind( + RegexpCommandsFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + ], + ) + filters_factory.bind( + ExceptionsFilter, + event_handlers=[ + self.errors_handlers, + ], + ) + filters_factory.bind( + AdminFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + self.callback_query_handlers, + self.inline_query_handlers, + ], + ) + filters_factory.bind( + IDFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + self.callback_query_handlers, + self.inline_query_handlers, + ], + ) + filters_factory.bind( + IsReplyFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + ], + ) + filters_factory.bind( + IsSenderContact, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + ], + ) + filters_factory.bind( + ForwardedMessageFilter, + event_handlers=[ + self.message_handlers, + self.edited_channel_post_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + ], + ) + filters_factory.bind( + ChatTypeFilter, + event_handlers=[ + self.message_handlers, + self.edited_message_handlers, + self.channel_post_handlers, + self.edited_channel_post_handlers, + self.callback_query_handlers, + ], + ) def __del__(self): self.stop_polling() @@ -255,15 +315,20 @@ class Dispatcher(DataMixin, ContextInstanceMixin): if update.edited_channel_post: types.Message.set_current(update.edited_channel_post) types.Chat.set_current(update.edited_channel_post.chat) - return await self.edited_channel_post_handlers.notify(update.edited_channel_post) + return await self.edited_channel_post_handlers.notify( + update.edited_channel_post + ) if update.inline_query: types.InlineQuery.set_current(update.inline_query) types.User.set_current(update.inline_query.from_user) return await self.inline_query_handlers.notify(update.inline_query) if update.chosen_inline_result: - types.ChosenInlineResult.set_current(update.chosen_inline_result) + types.ChosenInlineResult.set_current( + update.chosen_inline_result) types.User.set_current(update.chosen_inline_result.from_user) - return await self.chosen_inline_result_handlers.notify(update.chosen_inline_result) + return await self.chosen_inline_result_handlers.notify( + update.chosen_inline_result + ) if update.callback_query: types.CallbackQuery.set_current(update.callback_query) if update.callback_query.message: @@ -277,7 +342,9 @@ class Dispatcher(DataMixin, ContextInstanceMixin): if update.pre_checkout_query: types.PreCheckoutQuery.set_current(update.pre_checkout_query) types.User.set_current(update.pre_checkout_query.from_user) - return await self.pre_checkout_query_handlers.notify(update.pre_checkout_query) + return await self.pre_checkout_query_handlers.notify( + update.pre_checkout_query + ) if update.poll: types.Poll.set_current(update.poll) return await self.poll_handlers.notify(update.poll) @@ -311,13 +378,15 @@ class Dispatcher(DataMixin, ContextInstanceMixin): _ensure_loop(self._main_loop) return self._main_loop.create_task(coro) - async def start_polling(self, - timeout=20, - relax=0.1, - limit=None, - reset_webhook=None, - fast: typing.Optional[bool] = True, - error_sleep: int = 5): + async def start_polling( + self, + timeout=20, + relax=0.1, + limit=None, + reset_webhook=None, + fast: typing.Optional[bool] = True, + error_sleep: int = 5, + ): """ Start long-polling @@ -329,9 +398,9 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :return: """ if self._polling: - raise RuntimeError('Polling already started') + raise RuntimeError("Polling already started") - log.info('Start polling.') + log.info("Start polling.") # context.set_value(MODE, LONG_POLLING) Dispatcher.set_current(self) @@ -347,18 +416,22 @@ class Dispatcher(DataMixin, ContextInstanceMixin): try: current_request_timeout = self.bot.timeout if current_request_timeout is not sentinel and timeout is not None: - request_timeout = aiohttp.ClientTimeout(total=current_request_timeout.total + timeout or 1) + request_timeout = aiohttp.ClientTimeout( + total=current_request_timeout.total + timeout or 1 + ) else: request_timeout = None while self._polling: try: with self.bot.request_timeout(request_timeout): - updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout) + updates = await self.bot.get_updates( + limit=limit, offset=offset, timeout=timeout + ) except asyncio.CancelledError: break except: - log.exception('Cause exception while getting updates.') + log.exception("Cause exception while getting updates.") await asyncio.sleep(error_sleep) continue @@ -366,16 +439,19 @@ class Dispatcher(DataMixin, ContextInstanceMixin): log.debug(f"Received {len(updates)} updates.") offset = updates[-1].update_id + 1 - self._loop_create_task(self._process_polling_updates(updates, fast)) + self._loop_create_task( + self._process_polling_updates(updates, fast)) if relax: await asyncio.sleep(relax) finally: self._close_waiter.set_result(None) - log.warning('Polling is stopped.') + log.warning("Polling is stopped.") - async def _process_polling_updates(self, updates, fast: typing.Optional[bool] = True): + async def _process_polling_updates( + self, updates, fast: typing.Optional[bool] = True + ): """ Process updates received from long-polling. @@ -383,7 +459,9 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param fast: """ need_to_call = [] - for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)): + for responses in itertools.chain.from_iterable( + await self.process_updates(updates, fast) + ): for response in responses: if not isinstance(response, BaseResponse): continue @@ -392,7 +470,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): try: asyncio.gather(*need_to_call) except TelegramAPIError: - log.exception('Cause exception while processing updates.') + log.exception("Cause exception while processing updates.") def stop_polling(self): """ @@ -400,8 +478,8 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :return: """ - if hasattr(self, '_polling') and self._polling: - log.info('Stop polling...') + if hasattr(self, "_polling") and self._polling: + log.info("Stop polling...") self._polling = False async def wait_closed(self): @@ -420,8 +498,17 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ return self._polling - def register_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def register_message_handler( + self, + callback, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Register handler for message @@ -447,17 +534,29 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param state: :return: decorated function """ - filters_set = self.filters_factory.resolve(self.message_handlers, - *custom_filters, - commands=commands, - regexp=regexp, - content_types=content_types, - state=state, - **kwargs) - self.message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.message_handlers, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + **kwargs, + ) + self.message_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, state=None, - run_task=None, **kwargs): + def message_handler( + self, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Decorator for message handler @@ -528,15 +627,31 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_message_handler(callback, *custom_filters, - commands=commands, regexp=regexp, content_types=content_types, - state=state, run_task=run_task, **kwargs) + self.register_message_handler( + callback, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + run_task=run_task, + **kwargs, + ) return callback return decorator - def register_edited_message_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def register_edited_message_handler( + self, + callback, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Register handler for edited message @@ -550,17 +665,29 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param kwargs: :return: decorated function """ - filters_set = self.filters_factory.resolve(self.edited_message_handlers, - *custom_filters, - commands=commands, - regexp=regexp, - content_types=content_types, - state=state, - **kwargs) - self.edited_message_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.edited_message_handlers, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + **kwargs, + ) + self.edited_message_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def edited_message_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def edited_message_handler( + self, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Decorator for edited message handler @@ -583,14 +710,31 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_edited_message_handler(callback, *custom_filters, commands=commands, regexp=regexp, - content_types=content_types, state=state, run_task=run_task, **kwargs) + self.register_edited_message_handler( + callback, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + run_task=run_task, + **kwargs, + ) return callback return decorator - def register_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def register_channel_post_handler( + self, + callback, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Register handler for channel post @@ -604,17 +748,29 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param kwargs: :return: decorated function """ - filters_set = self.filters_factory.resolve(self.channel_post_handlers, - *custom_filters, - commands=commands, - regexp=regexp, - content_types=content_types, - state=state, - **kwargs) - self.channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.channel_post_handlers, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + **kwargs, + ) + self.channel_post_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def channel_post_handler( + self, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Decorator for channel post handler @@ -629,14 +785,31 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp, - content_types=content_types, state=state, run_task=run_task, **kwargs) + self.register_channel_post_handler( + callback, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + run_task=run_task, + **kwargs, + ) return callback return decorator - def register_edited_channel_post_handler(self, callback, *custom_filters, commands=None, regexp=None, - content_types=None, state=None, run_task=None, **kwargs): + def register_edited_channel_post_handler( + self, + callback, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Register handler for edited channel post @@ -650,17 +823,29 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param kwargs: :return: decorated function """ - filters_set = self.filters_factory.resolve(self.edited_message_handlers, - *custom_filters, - commands=commands, - regexp=regexp, - content_types=content_types, - state=state, - **kwargs) - self.edited_channel_post_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.edited_message_handlers, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + **kwargs, + ) + self.edited_channel_post_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def edited_channel_post_handler(self, *custom_filters, commands=None, regexp=None, content_types=None, - state=None, run_task=None, **kwargs): + def edited_channel_post_handler( + self, + *custom_filters, + commands=None, + regexp=None, + content_types=None, + state=None, + run_task=None, + **kwargs, + ): """ Decorator for edited channel post handler @@ -675,14 +860,23 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_edited_channel_post_handler(callback, *custom_filters, commands=commands, regexp=regexp, - content_types=content_types, state=state, run_task=run_task, - **kwargs) + self.register_edited_channel_post_handler( + callback, + *custom_filters, + commands=commands, + regexp=regexp, + content_types=content_types, + state=state, + run_task=run_task, + **kwargs, + ) return callback return decorator - def register_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs): + def register_inline_handler( + self, callback, *custom_filters, state=None, run_task=None, **kwargs + ): """ Register handler for inline query @@ -701,11 +895,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ if custom_filters is None: custom_filters = [] - filters_set = self.filters_factory.resolve(self.inline_query_handlers, - *custom_filters, - state=state, - **kwargs) - self.inline_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.inline_query_handlers, *custom_filters, state=state, **kwargs + ) + self.inline_query_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) def inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs): """ @@ -726,12 +921,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs) + self.register_inline_handler( + callback, *custom_filters, state=state, run_task=run_task, **kwargs + ) return callback return decorator - def register_chosen_inline_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs): + def register_chosen_inline_handler( + self, callback, *custom_filters, state=None, run_task=None, **kwargs + ): """ Register handler for chosen inline query @@ -750,13 +949,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ if custom_filters is None: custom_filters = [] - filters_set = self.filters_factory.resolve(self.chosen_inline_result_handlers, - *custom_filters, - state=state, - **kwargs) - self.chosen_inline_result_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.chosen_inline_result_handlers, *custom_filters, state=state, **kwargs + ) + self.chosen_inline_result_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def chosen_inline_handler(self, *custom_filters, state=None, run_task=None, **kwargs): + def chosen_inline_handler( + self, *custom_filters, state=None, run_task=None, **kwargs + ): """ Decorator for chosen inline query handler @@ -775,12 +977,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_chosen_inline_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs) + self.register_chosen_inline_handler( + callback, *custom_filters, state=state, run_task=run_task, **kwargs + ) return callback return decorator - def register_callback_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs): + def register_callback_query_handler( + self, callback, *custom_filters, state=None, run_task=None, **kwargs + ): """ Register handler for callback query @@ -796,13 +1002,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - filters_set = self.filters_factory.resolve(self.callback_query_handlers, - *custom_filters, - state=state, - **kwargs) - self.callback_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.callback_query_handlers, *custom_filters, state=state, **kwargs + ) + self.callback_query_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def callback_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs): + def callback_query_handler( + self, *custom_filters, state=None, run_task=None, **kwargs + ): """ Decorator for callback query handler @@ -820,13 +1029,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_callback_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs) + self.register_callback_query_handler( + callback, *custom_filters, state=state, run_task=run_task, **kwargs + ) return callback return decorator - def register_shipping_query_handler(self, callback, *custom_filters, state=None, run_task=None, - **kwargs): + def register_shipping_query_handler( + self, callback, *custom_filters, state=None, run_task=None, **kwargs + ): """ Register handler for shipping query @@ -842,13 +1054,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - filters_set = self.filters_factory.resolve(self.shipping_query_handlers, - *custom_filters, - state=state, - **kwargs) - self.shipping_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.shipping_query_handlers, *custom_filters, state=state, **kwargs + ) + self.shipping_query_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def shipping_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs): + def shipping_query_handler( + self, *custom_filters, state=None, run_task=None, **kwargs + ): """ Decorator for shipping query handler @@ -866,12 +1081,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_shipping_query_handler(callback, *custom_filters, state=state, run_task=run_task, **kwargs) + self.register_shipping_query_handler( + callback, *custom_filters, state=state, run_task=run_task, **kwargs + ) return callback return decorator - def register_pre_checkout_query_handler(self, callback, *custom_filters, state=None, run_task=None, **kwargs): + def register_pre_checkout_query_handler( + self, callback, *custom_filters, state=None, run_task=None, **kwargs + ): """ Register handler for pre-checkout query @@ -887,13 +1106,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - filters_set = self.filters_factory.resolve(self.pre_checkout_query_handlers, - *custom_filters, - state=state, - **kwargs) - self.pre_checkout_query_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.pre_checkout_query_handlers, *custom_filters, state=state, **kwargs + ) + self.pre_checkout_query_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) - def pre_checkout_query_handler(self, *custom_filters, state=None, run_task=None, **kwargs): + def pre_checkout_query_handler( + self, *custom_filters, state=None, run_task=None, **kwargs + ): """ Decorator for pre-checkout query handler @@ -911,8 +1133,9 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_pre_checkout_query_handler(callback, *custom_filters, state=state, run_task=run_task, - **kwargs) + self.register_pre_checkout_query_handler( + callback, *custom_filters, state=state, run_task=run_task, **kwargs + ) return callback return decorator @@ -920,7 +1143,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): def register_poll_handler(self, callback, *custom_filters, run_task=None, **kwargs): """ Register handler for poll - + Example: .. code-block:: python3 @@ -932,10 +1155,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - filters_set = self.filters_factory.resolve(self.poll_handlers, - *custom_filters, - **kwargs) - self.poll_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.poll_handlers, *custom_filters, **kwargs + ) + self.poll_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) def poll_handler(self, *custom_filters, run_task=None, **kwargs): """ @@ -952,18 +1177,21 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - + def decorator(callback): - self.register_poll_handler(callback, *custom_filters, run_task=run_task, - **kwargs) + self.register_poll_handler( + callback, *custom_filters, run_task=run_task, **kwargs + ) return callback return decorator - - def register_poll_answer_handler(self, callback, *custom_filters, run_task=None, **kwargs): + + def register_poll_answer_handler( + self, callback, *custom_filters, run_task=None, **kwargs + ): """ Register handler for poll_answer - + Example: .. code-block:: python3 @@ -975,11 +1203,13 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param run_task: run callback in task (no wait results) :param kwargs: """ - filters_set = self.filters_factory.resolve(self.poll_answer_handlers, - *custom_filters, - **kwargs) - self.poll_answer_handlers.register(self._wrap_async_task(callback, run_task), filters_set) - + filters_set = self.filters_factory.resolve( + self.poll_answer_handlers, *custom_filters, **kwargs + ) + self.poll_answer_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) + def poll_answer_handler(self, *custom_filters, run_task=None, **kwargs): """ Decorator for poll_answer handler @@ -997,13 +1227,16 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_poll_answer_handler(callback, *custom_filters, run_task=run_task, - **kwargs) + self.register_poll_answer_handler( + callback, *custom_filters, run_task=run_task, **kwargs + ) return callback return decorator - def register_errors_handler(self, callback, *custom_filters, exception=None, run_task=None, **kwargs): + def register_errors_handler( + self, callback, *custom_filters, exception=None, run_task=None, **kwargs + ): """ Register handler for errors @@ -1011,11 +1244,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param exception: you can make handler for specific errors type :param run_task: run callback in task (no wait results) """ - filters_set = self.filters_factory.resolve(self.errors_handlers, - *custom_filters, - exception=exception, - **kwargs) - self.errors_handlers.register(self._wrap_async_task(callback, run_task), filters_set) + filters_set = self.filters_factory.resolve( + self.errors_handlers, *custom_filters, exception=exception, **kwargs + ) + self.errors_handlers.register( + self._wrap_async_task(callback, run_task), filters_set + ) def errors_handler(self, *custom_filters, exception=None, run_task=None, **kwargs): """ @@ -1027,15 +1261,22 @@ class Dispatcher(DataMixin, ContextInstanceMixin): """ def decorator(callback): - self.register_errors_handler(self._wrap_async_task(callback, run_task), - *custom_filters, exception=exception, **kwargs) + self.register_errors_handler( + self._wrap_async_task(callback, run_task), + *custom_filters, + exception=exception, + **kwargs, + ) return callback return decorator - def current_state(self, *, - chat: typing.Union[str, int, None] = None, - user: typing.Union[str, int, None] = None) -> FSMContext: + def current_state( + self, + *, + chat: typing.Union[str, int, None] = None, + user: typing.Union[str, int, None] = None, + ) -> FSMContext: """ Get current state for user in chat as context @@ -1060,9 +1301,15 @@ class Dispatcher(DataMixin, ContextInstanceMixin): return FSMContext(storage=self.storage, chat=chat, user=user) - @renamed_argument(old_name='user', new_name='user_id', until_version='3.0', stacklevel=3) - @renamed_argument(old_name='chat', new_name='chat_id', until_version='3.0', stacklevel=4) - async def throttle(self, key, *, rate=None, user_id=None, chat_id=None, no_error=None) -> bool: + @renamed_argument( + old_name="user", new_name="user_id", until_version="3.0", stacklevel=3 + ) + @renamed_argument( + old_name="chat", new_name="chat_id", until_version="3.0", stacklevel=4 + ) + async def throttle( + self, key, *, rate=None, user_id=None, chat_id=None, no_error=None + ) -> bool: """ Execute throttling manager. Returns True if limit has not exceeded otherwise raises ThrottleError or returns False @@ -1075,7 +1322,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :return: bool """ if not self.storage.has_bucket(): - raise RuntimeError('This storage does not provide Leaky Bucket') + raise RuntimeError("This storage does not provide Leaky Bucket") if no_error is None: no_error = self.no_throttle_error @@ -1119,8 +1366,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): raise Throttled(key=key, chat=chat_id, user=user_id, **data) return result - @renamed_argument(old_name='user', new_name='user_id', until_version='3.0', stacklevel=3) - @renamed_argument(old_name='chat', new_name='chat_id', until_version='3.0', stacklevel=4) + @renamed_argument( + old_name="user", new_name="user_id", until_version="3.0", stacklevel=3 + ) + @renamed_argument( + old_name="chat", new_name="chat_id", until_version="3.0", stacklevel=4 + ) async def check_key(self, key, chat_id=None, user_id=None): """ Get information about key in bucket @@ -1131,7 +1382,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :return: """ if not self.storage.has_bucket(): - raise RuntimeError('This storage does not provide Leaky Bucket') + raise RuntimeError("This storage does not provide Leaky Bucket") if user_id is None and chat_id is None: user_id = types.User.get_current() @@ -1141,8 +1392,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): data = bucket.get(key, {}) return Throttled(key=key, chat=chat_id, user=user_id, **data) - @renamed_argument(old_name='user', new_name='user_id', until_version='3.0', stacklevel=3) - @renamed_argument(old_name='chat', new_name='chat_id', until_version='3.0', stacklevel=4) + @renamed_argument( + old_name="user", new_name="user_id", until_version="3.0", stacklevel=3 + ) + @renamed_argument( + old_name="chat", new_name="chat_id", until_version="3.0", stacklevel=4 + ) async def release_key(self, key, chat_id=None, user_id=None): """ Release blocked key @@ -1153,7 +1408,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :return: """ if not self.storage.has_bucket(): - raise RuntimeError('This storage does not provide Leaky Bucket') + raise RuntimeError("This storage does not provide Leaky Bucket") if user_id is None and chat_id is None: user_id = types.User.get_current() @@ -1161,7 +1416,7 @@ class Dispatcher(DataMixin, ContextInstanceMixin): bucket = await self.storage.get_bucket(chat=chat_id, user=user_id) if bucket and key in bucket: - del bucket['key'] + del bucket["key"] await self.storage.set_bucket(chat=chat_id, user=user_id, bucket=bucket) return True return False @@ -1188,7 +1443,8 @@ class Dispatcher(DataMixin, ContextInstanceMixin): response = task.result() except Exception as e: self._loop_create_task( - self.errors_handlers.notify(types.Update.get_current(), e)) + self.errors_handlers.notify(types.Update.get_current(), e) + ) else: if isinstance(response, BaseResponse): self._loop_create_task(response.execute_response(self.bot)) @@ -1208,9 +1464,14 @@ class Dispatcher(DataMixin, ContextInstanceMixin): return self.async_task(callback) return callback - def throttled(self, on_throttled: typing.Optional[typing.Callable] = None, - key=None, rate=None, - user_id=None, chat_id=None): + def throttled( + self, + on_throttled: typing.Optional[typing.Callable] = None, + key=None, + rate=None, + user_id=None, + chat_id=None, + ): """ Meta-decorator for throttling. Invokes on_throttled if the handler was throttled. @@ -1233,45 +1494,43 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param chat_id: chat id :return: decorator """ + def decorator(func): @functools.wraps(func) async def wrapped(*args, **kwargs): - is_not_throttled = await self.throttle(key if key is not None else func.__name__, - rate=rate, - user_id=user_id, chat_id=chat_id, - no_error=True) + is_not_throttled = await self.throttle( + key if key is not None else func.__name__, + rate=rate, + user_id=user_id, + chat_id=chat_id, + no_error=True, + ) if is_not_throttled: return await func(*args, **kwargs) kwargs.update( - { - 'rate': rate, - 'key': key, - 'user_id': user_id, - 'chat_id': chat_id - } + {"rate": rate, "key": key, "user_id": user_id, "chat_id": chat_id} ) # update kwargs with parameters which were given to throttled if on_throttled: if asyncio.iscoroutinefunction(on_throttled): await on_throttled(*args, **kwargs) else: - kwargs.update( - { - 'loop': asyncio.get_running_loop() - } - ) - partial_func = functools.partial(on_throttled, *args, **kwargs) - asyncio.get_running_loop().run_in_executor(None, - partial_func - ) + kwargs.update({"loop": asyncio.get_running_loop()}) + partial_func = functools.partial( + on_throttled, *args, **kwargs) + asyncio.get_running_loop().run_in_executor(None, partial_func) + return wrapped return decorator - def bind_filter(self, callback: typing.Union[typing.Callable, AbstractFilter], - validator: typing.Optional[typing.Callable] = None, - event_handlers: typing.Optional[typing.List[Handler]] = None, - exclude_event_handlers: typing.Optional[typing.Iterable[Handler]] = None): + def bind_filter( + self, + callback: typing.Union[typing.Callable, AbstractFilter], + validator: typing.Optional[typing.Callable] = None, + event_handlers: typing.Optional[typing.List[Handler]] = None, + exclude_event_handlers: typing.Optional[typing.Iterable[Handler]] = None, + ): """ Register filter @@ -1280,8 +1539,12 @@ class Dispatcher(DataMixin, ContextInstanceMixin): :param event_handlers: list of instances of :obj:`Handler` :param exclude_event_handlers: list of excluded event handlers (:obj:`Handler`) """ - self.filters_factory.bind(callback=callback, validator=validator, event_handlers=event_handlers, - exclude_event_handlers=exclude_event_handlers) + self.filters_factory.bind( + callback=callback, + validator=validator, + event_handlers=event_handlers, + exclude_event_handlers=exclude_event_handlers, + ) def unbind_filter(self, callback: typing.Union[typing.Callable, AbstractFilter]): """ diff --git a/tests/conftest.py b/tests/conftest.py index 466e9490..9cff5b92 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,18 +4,23 @@ from _pytest.config import UsageError def pytest_addoption(parser): - parser.addoption("--redis", default=None, - help="run tests which require redis connection") + parser.addoption( + "--redis", default=None, help="run tests which require redis connection" + ) def pytest_configure(config): - config.addinivalue_line("markers", "redis: marked tests require redis connection to run") + config.addinivalue_line( + "markers", "redis: marked tests require redis connection to run" + ) def pytest_collection_modifyitems(config, items): redis_uri = config.getoption("--redis") if redis_uri is None: - skip_redis = pytest.mark.skip(reason="need --redis option with redis URI to run") + skip_redis = pytest.mark.skip( + reason="need --redis option with redis URI to run" + ) for item in items: if "redis" in item.keywords: item.add_marker(skip_redis) @@ -23,14 +28,16 @@ def pytest_collection_modifyitems(config, items): try: address, options = aioredis.util.parse_url(redis_uri) if not isinstance(address, tuple): - raise AssertionError("Only redis and rediss schemas are supported, eg redis://foo.") + raise AssertionError( + "Only redis and rediss schemas are supported, eg redis://foo." + ) except AssertionError as e: raise UsageError(f"Invalid redis URI {redis_uri!r}: {e}") -@pytest.fixture(scope='session') +@pytest.fixture(scope="session") def redis_options(request): redis_uri = request.config.getoption("--redis") (host, port), options = aioredis.util.parse_url(redis_uri) - options.update({'host': host, 'port': port}) + options.update({"host": host, "port": port}) return options diff --git a/tests/contrib/fsm_storage/test_redis.py b/tests/contrib/fsm_storage/test_redis.py index 40f18cad..5f960324 100644 --- a/tests/contrib/fsm_storage/test_redis.py +++ b/tests/contrib/fsm_storage/test_redis.py @@ -19,20 +19,20 @@ async def store(redis_options): class TestRedisStorage2: @pytest.mark.asyncio async def test_set_get(self, store): - if await store.get_data(chat='1234') != {}: + if await store.get_data(chat="1234") != {}: raise AssertionError - await store.set_data(chat='1234', data={'foo': 'bar'}) - if await store.get_data(chat='1234') != {'foo': 'bar'}: + await store.set_data(chat="1234", data={"foo": "bar"}) + if await store.get_data(chat="1234") != {"foo": "bar"}: raise AssertionError @pytest.mark.asyncio async def test_close_and_open_connection(self, store): - await store.set_data(chat='1234', data={'foo': 'bar'}) - if await store.get_data(chat='1234') != {'foo': 'bar'}: + await store.set_data(chat="1234", data={"foo": "bar"}) + if await store.get_data(chat="1234") != {"foo": "bar"}: raise AssertionError pool_id = id(store._redis) await store.close() - if await store.get_data(chat='1234') != {'foo': 'bar'}: + if await store.get_data(chat="1234") != {"foo": "bar"}: raise AssertionError if id(store._redis) == pool_id: raise AssertionError diff --git a/tests/test_bot.py b/tests/test_bot.py index 462bd48e..a08f5dd6 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -7,7 +7,7 @@ from . import BOT_ID, TOKEN, FakeTelegram pytestmark = pytest.mark.asyncio -@pytest.yield_fixture(name='bot') +@pytest.yield_fixture(name="bot") async def bot_fixture(event_loop): """ Bot fixture """ _bot = Bot(TOKEN, loop=event_loop, parse_mode=types.ParseMode.MARKDOWN) @@ -18,6 +18,7 @@ async def bot_fixture(event_loop): async def test_get_me(bot: Bot, event_loop): """ getMe method test """ from .types.dataset import USER + user = types.User(**USER) async with FakeTelegram(message_data=USER, loop=event_loop): @@ -47,6 +48,7 @@ async def test_close_bot(bot: Bot, event_loop): async def test_send_message(bot: Bot, event_loop): """ sendMessage method test """ from .types.dataset import MESSAGE + msg = types.Message(**MESSAGE) async with FakeTelegram(message_data=MESSAGE, loop=event_loop): @@ -58,11 +60,15 @@ async def test_send_message(bot: Bot, event_loop): async def test_forward_message(bot: Bot, event_loop): """ forwardMessage method test """ from .types.dataset import FORWARDED_MESSAGE + msg = types.Message(**FORWARDED_MESSAGE) async with FakeTelegram(message_data=FORWARDED_MESSAGE, loop=event_loop): - result = await bot.forward_message(chat_id=msg.chat.id, from_chat_id=msg.forward_from_chat.id, - message_id=msg.forward_from_message_id) + result = await bot.forward_message( + chat_id=msg.chat.id, + from_chat_id=msg.forward_from_chat.id, + message_id=msg.forward_from_message_id, + ) if result != msg: raise AssertionError @@ -70,12 +76,18 @@ async def test_forward_message(bot: Bot, event_loop): async def test_send_photo(bot: Bot, event_loop): """ sendPhoto method test with file_id """ from .types.dataset import MESSAGE_WITH_PHOTO, PHOTO + msg = types.Message(**MESSAGE_WITH_PHOTO) photo = types.PhotoSize(**PHOTO) async with FakeTelegram(message_data=MESSAGE_WITH_PHOTO, loop=event_loop): - result = await bot.send_photo(msg.chat.id, photo=photo.file_id, caption=msg.caption, - parse_mode=types.ParseMode.HTML, disable_notification=False) + result = await bot.send_photo( + msg.chat.id, + photo=photo.file_id, + caption=msg.caption, + parse_mode=types.ParseMode.HTML, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -83,12 +95,20 @@ async def test_send_photo(bot: Bot, event_loop): async def test_send_audio(bot: Bot, event_loop): """ sendAudio method test with file_id """ from .types.dataset import MESSAGE_WITH_AUDIO + msg = types.Message(**MESSAGE_WITH_AUDIO) async with FakeTelegram(message_data=MESSAGE_WITH_AUDIO, loop=event_loop): - result = await bot.send_audio(chat_id=msg.chat.id, audio=msg.audio.file_id, caption=msg.caption, - parse_mode=types.ParseMode.HTML, duration=msg.audio.duration, - performer=msg.audio.performer, title=msg.audio.title, disable_notification=False) + result = await bot.send_audio( + chat_id=msg.chat.id, + audio=msg.audio.file_id, + caption=msg.caption, + parse_mode=types.ParseMode.HTML, + duration=msg.audio.duration, + performer=msg.audio.performer, + title=msg.audio.title, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -96,11 +116,17 @@ async def test_send_audio(bot: Bot, event_loop): async def test_send_document(bot: Bot, event_loop): """ sendDocument method test with file_id """ from .types.dataset import MESSAGE_WITH_DOCUMENT + msg = types.Message(**MESSAGE_WITH_DOCUMENT) async with FakeTelegram(message_data=MESSAGE_WITH_DOCUMENT, loop=event_loop): - result = await bot.send_document(chat_id=msg.chat.id, document=msg.document.file_id, caption=msg.caption, - parse_mode=types.ParseMode.HTML, disable_notification=False) + result = await bot.send_document( + chat_id=msg.chat.id, + document=msg.document.file_id, + caption=msg.caption, + parse_mode=types.ParseMode.HTML, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -108,14 +134,22 @@ async def test_send_document(bot: Bot, event_loop): async def test_send_video(bot: Bot, event_loop): """ sendVideo method test with file_id """ from .types.dataset import MESSAGE_WITH_VIDEO, VIDEO + msg = types.Message(**MESSAGE_WITH_VIDEO) video = types.Video(**VIDEO) async with FakeTelegram(message_data=MESSAGE_WITH_VIDEO, loop=event_loop): - result = await bot.send_video(chat_id=msg.chat.id, video=video.file_id, duration=video.duration, - width=video.width, height=video.height, caption=msg.caption, - parse_mode=types.ParseMode.HTML, supports_streaming=True, - disable_notification=False) + result = await bot.send_video( + chat_id=msg.chat.id, + video=video.file_id, + duration=video.duration, + width=video.width, + height=video.height, + caption=msg.caption, + parse_mode=types.ParseMode.HTML, + supports_streaming=True, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -123,13 +157,19 @@ async def test_send_video(bot: Bot, event_loop): async def test_send_voice(bot: Bot, event_loop): """ sendVoice method test with file_id """ from .types.dataset import MESSAGE_WITH_VOICE, VOICE + msg = types.Message(**MESSAGE_WITH_VOICE) voice = types.Voice(**VOICE) async with FakeTelegram(message_data=MESSAGE_WITH_VOICE, loop=event_loop): - result = await bot.send_voice(chat_id=msg.chat.id, voice=voice.file_id, caption=msg.caption, - parse_mode=types.ParseMode.HTML, duration=voice.duration, - disable_notification=False) + result = await bot.send_voice( + chat_id=msg.chat.id, + voice=voice.file_id, + caption=msg.caption, + parse_mode=types.ParseMode.HTML, + duration=voice.duration, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -137,13 +177,18 @@ async def test_send_voice(bot: Bot, event_loop): async def test_send_video_note(bot: Bot, event_loop): """ sendVideoNote method test with file_id """ from .types.dataset import MESSAGE_WITH_VIDEO_NOTE, VIDEO_NOTE + msg = types.Message(**MESSAGE_WITH_VIDEO_NOTE) video_note = types.VideoNote(**VIDEO_NOTE) async with FakeTelegram(message_data=MESSAGE_WITH_VIDEO_NOTE, loop=event_loop): - result = await bot.send_video_note(chat_id=msg.chat.id, video_note=video_note.file_id, - duration=video_note.duration, length=video_note.length, - disable_notification=False) + result = await bot.send_video_note( + chat_id=msg.chat.id, + video_note=video_note.file_id, + duration=video_note.duration, + length=video_note.length, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -151,12 +196,21 @@ async def test_send_video_note(bot: Bot, event_loop): async def test_send_media_group(bot: Bot, event_loop): """ sendMediaGroup method test with file_id """ from .types.dataset import MESSAGE_WITH_MEDIA_GROUP, PHOTO + msg = types.Message(**MESSAGE_WITH_MEDIA_GROUP) photo = types.PhotoSize(**PHOTO) - media = [types.InputMediaPhoto(media=photo.file_id), types.InputMediaPhoto(media=photo.file_id)] + media = [ + types.InputMediaPhoto(media=photo.file_id), + types.InputMediaPhoto(media=photo.file_id), + ] - async with FakeTelegram(message_data=[MESSAGE_WITH_MEDIA_GROUP, MESSAGE_WITH_MEDIA_GROUP], loop=event_loop): - result = await bot.send_media_group(msg.chat.id, media=media, disable_notification=False) + async with FakeTelegram( + message_data=[MESSAGE_WITH_MEDIA_GROUP, MESSAGE_WITH_MEDIA_GROUP], + loop=event_loop, + ): + result = await bot.send_media_group( + msg.chat.id, media=media, disable_notification=False + ) if len(result) != len(media): raise AssertionError if not result.pop().media_group_id: @@ -166,12 +220,18 @@ async def test_send_media_group(bot: Bot, event_loop): async def test_send_location(bot: Bot, event_loop): """ sendLocation method test """ from .types.dataset import LOCATION, MESSAGE_WITH_LOCATION + msg = types.Message(**MESSAGE_WITH_LOCATION) location = types.Location(**LOCATION) async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): - result = await bot.send_location(msg.chat.id, latitude=location.latitude, longitude=location.longitude, - live_period=10, disable_notification=False) + result = await bot.send_location( + msg.chat.id, + latitude=location.latitude, + longitude=location.longitude, + live_period=10, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -179,13 +239,18 @@ async def test_send_location(bot: Bot, event_loop): async def test_edit_message_live_location_by_bot(bot: Bot, event_loop): """ editMessageLiveLocation method test """ from .types.dataset import LOCATION, MESSAGE_WITH_LOCATION + msg = types.Message(**MESSAGE_WITH_LOCATION) location = types.Location(**LOCATION) # editing bot message async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): - result = await bot.edit_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id, - latitude=location.latitude, longitude=location.longitude) + result = await bot.edit_message_live_location( + chat_id=msg.chat.id, + message_id=msg.message_id, + latitude=location.latitude, + longitude=location.longitude, + ) if result != msg: raise AssertionError @@ -193,13 +258,18 @@ async def test_edit_message_live_location_by_bot(bot: Bot, event_loop): async def test_edit_message_live_location_by_user(bot: Bot, event_loop): """ editMessageLiveLocation method test """ from .types.dataset import LOCATION, MESSAGE_WITH_LOCATION + msg = types.Message(**MESSAGE_WITH_LOCATION) location = types.Location(**LOCATION) # editing user's message async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.edit_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id, - latitude=location.latitude, longitude=location.longitude) + result = await bot.edit_message_live_location( + chat_id=msg.chat.id, + message_id=msg.message_id, + latitude=location.latitude, + longitude=location.longitude, + ) if not (isinstance(result, bool) and result is True): raise AssertionError @@ -207,11 +277,14 @@ async def test_edit_message_live_location_by_user(bot: Bot, event_loop): async def test_stop_message_live_location_by_bot(bot: Bot, event_loop): """ stopMessageLiveLocation method test """ from .types.dataset import MESSAGE_WITH_LOCATION + msg = types.Message(**MESSAGE_WITH_LOCATION) # stopping bot message async with FakeTelegram(message_data=MESSAGE_WITH_LOCATION, loop=event_loop): - result = await bot.stop_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id) + result = await bot.stop_message_live_location( + chat_id=msg.chat.id, message_id=msg.message_id + ) if result != msg: raise AssertionError @@ -219,11 +292,14 @@ async def test_stop_message_live_location_by_bot(bot: Bot, event_loop): async def test_stop_message_live_location_by_user(bot: Bot, event_loop): """ stopMessageLiveLocation method test """ from .types.dataset import MESSAGE_WITH_LOCATION + msg = types.Message(**MESSAGE_WITH_LOCATION) # stopping user's message async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.stop_message_live_location(chat_id=msg.chat.id, message_id=msg.message_id) + result = await bot.stop_message_live_location( + chat_id=msg.chat.id, message_id=msg.message_id + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -233,14 +309,21 @@ async def test_stop_message_live_location_by_user(bot: Bot, event_loop): async def test_send_venue(bot: Bot, event_loop): """ sendVenue method test """ from .types.dataset import LOCATION, MESSAGE_WITH_VENUE, VENUE + msg = types.Message(**MESSAGE_WITH_VENUE) location = types.Location(**LOCATION) venue = types.Venue(**VENUE) async with FakeTelegram(message_data=MESSAGE_WITH_VENUE, loop=event_loop): - result = await bot.send_venue(msg.chat.id, latitude=location.latitude, longitude=location.longitude, - title=venue.title, address=venue.address, foursquare_id=venue.foursquare_id, - disable_notification=False) + result = await bot.send_venue( + msg.chat.id, + latitude=location.latitude, + longitude=location.longitude, + title=venue.title, + address=venue.address, + foursquare_id=venue.foursquare_id, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -248,12 +331,18 @@ async def test_send_venue(bot: Bot, event_loop): async def test_send_contact(bot: Bot, event_loop): """ sendContact method test """ from .types.dataset import CONTACT, MESSAGE_WITH_CONTACT + msg = types.Message(**MESSAGE_WITH_CONTACT) contact = types.Contact(**CONTACT) async with FakeTelegram(message_data=MESSAGE_WITH_CONTACT, loop=event_loop): - result = await bot.send_contact(msg.chat.id, phone_number=contact.phone_number, first_name=contact.first_name, - last_name=contact.last_name, disable_notification=False) + result = await bot.send_contact( + msg.chat.id, + phone_number=contact.phone_number, + first_name=contact.first_name, + last_name=contact.last_name, + disable_notification=False, + ) if result != msg: raise AssertionError @@ -261,6 +350,7 @@ async def test_send_contact(bot: Bot, event_loop): async def test_send_dice(bot: Bot, event_loop): """ sendDice method test """ from .types.dataset import MESSAGE_WITH_DICE + msg = types.Message(**MESSAGE_WITH_DICE) async with FakeTelegram(message_data=MESSAGE_WITH_DICE, loop=event_loop): @@ -272,10 +362,13 @@ async def test_send_dice(bot: Bot, event_loop): async def test_send_chat_action(bot: Bot, event_loop): """ sendChatAction method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.send_chat_action(chat_id=chat.id, action=types.ChatActions.TYPING) + result = await bot.send_chat_action( + chat_id=chat.id, action=types.ChatActions.TYPING + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -285,6 +378,7 @@ async def test_send_chat_action(bot: Bot, event_loop): async def test_get_user_profile_photo(bot: Bot, event_loop): """ getUserProfilePhotos method test """ from .types.dataset import USER, USER_PROFILE_PHOTOS + user = types.User(**USER) async with FakeTelegram(message_data=USER_PROFILE_PHOTOS, loop=event_loop): @@ -296,6 +390,7 @@ async def test_get_user_profile_photo(bot: Bot, event_loop): async def test_get_file(bot: Bot, event_loop): """ getFile method test """ from .types.dataset import FILE + file = types.File(**FILE) async with FakeTelegram(message_data=FILE, loop=event_loop): @@ -307,11 +402,14 @@ async def test_get_file(bot: Bot, event_loop): async def test_kick_chat_member(bot: Bot, event_loop): """ kickChatMember method test """ from .types.dataset import CHAT, USER + user = types.User(**USER) chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.kick_chat_member(chat_id=chat.id, user_id=user.id, until_date=123) + result = await bot.kick_chat_member( + chat_id=chat.id, user_id=user.id, until_date=123 + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -321,6 +419,7 @@ async def test_kick_chat_member(bot: Bot, event_loop): async def test_unban_chat_member(bot: Bot, event_loop): """ unbanChatMember method test """ from .types.dataset import CHAT, USER + user = types.User(**USER) chat = types.Chat(**CHAT) @@ -335,6 +434,7 @@ async def test_unban_chat_member(bot: Bot, event_loop): async def test_restrict_chat_member(bot: Bot, event_loop): """ restrictChatMember method test """ from .types.dataset import CHAT, USER + user = types.User(**USER) chat = types.Chat(**CHAT) @@ -346,8 +446,10 @@ async def test_restrict_chat_member(bot: Bot, event_loop): can_add_web_page_previews=False, can_send_media_messages=False, can_send_messages=False, - can_send_other_messages=False - ), until_date=123) + can_send_other_messages=False, + ), + until_date=123, + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -357,14 +459,23 @@ async def test_restrict_chat_member(bot: Bot, event_loop): async def test_promote_chat_member(bot: Bot, event_loop): """ promoteChatMember method test """ from .types.dataset import CHAT, USER + user = types.User(**USER) chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.promote_chat_member(chat_id=chat.id, user_id=user.id, can_change_info=True, - can_delete_messages=True, can_edit_messages=True, - can_invite_users=True, can_pin_messages=True, can_post_messages=True, - can_promote_members=True, can_restrict_members=True) + result = await bot.promote_chat_member( + chat_id=chat.id, + user_id=user.id, + can_change_info=True, + can_delete_messages=True, + can_edit_messages=True, + can_invite_users=True, + can_pin_messages=True, + can_post_messages=True, + can_promote_members=True, + can_restrict_members=True, + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -374,6 +485,7 @@ async def test_promote_chat_member(bot: Bot, event_loop): async def test_export_chat_invite_link(bot: Bot, event_loop): """ exportChatInviteLink method test """ from .types.dataset import CHAT, INVITE_LINK + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=INVITE_LINK, loop=event_loop): @@ -385,6 +497,7 @@ async def test_export_chat_invite_link(bot: Bot, event_loop): async def test_delete_chat_photo(bot: Bot, event_loop): """ deleteChatPhoto method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): @@ -398,10 +511,11 @@ async def test_delete_chat_photo(bot: Bot, event_loop): async def test_set_chat_title(bot: Bot, event_loop): """ setChatTitle method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.set_chat_title(chat_id=chat.id, title='Test title') + result = await bot.set_chat_title(chat_id=chat.id, title="Test title") if not isinstance(result, bool): raise AssertionError if result is not True: @@ -411,10 +525,13 @@ async def test_set_chat_title(bot: Bot, event_loop): async def test_set_chat_description(bot: Bot, event_loop): """ setChatDescription method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.set_chat_description(chat_id=chat.id, description='Test description') + result = await bot.set_chat_description( + chat_id=chat.id, description="Test description" + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -424,11 +541,15 @@ async def test_set_chat_description(bot: Bot, event_loop): async def test_pin_chat_message(bot: Bot, event_loop): """ pinChatMessage method test """ from .types.dataset import MESSAGE + message = types.Message(**MESSAGE) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.pin_chat_message(chat_id=message.chat.id, message_id=message.message_id, - disable_notification=False) + result = await bot.pin_chat_message( + chat_id=message.chat.id, + message_id=message.message_id, + disable_notification=False, + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -438,6 +559,7 @@ async def test_pin_chat_message(bot: Bot, event_loop): async def test_unpin_chat_message(bot: Bot, event_loop): """ unpinChatMessage method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): @@ -451,6 +573,7 @@ async def test_unpin_chat_message(bot: Bot, event_loop): async def test_leave_chat(bot: Bot, event_loop): """ leaveChat method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): @@ -464,6 +587,7 @@ async def test_leave_chat(bot: Bot, event_loop): async def test_get_chat(bot: Bot, event_loop): """ getChat method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=CHAT, loop=event_loop): @@ -475,6 +599,7 @@ async def test_get_chat(bot: Bot, event_loop): async def test_get_chat_administrators(bot: Bot, event_loop): """ getChatAdministrators method test """ from .types.dataset import CHAT, CHAT_MEMBER + chat = types.Chat(**CHAT) member = types.ChatMember(**CHAT_MEMBER) @@ -489,6 +614,7 @@ async def test_get_chat_administrators(bot: Bot, event_loop): async def test_get_chat_members_count(bot: Bot, event_loop): """ getChatMembersCount method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) count = 5 @@ -501,6 +627,7 @@ async def test_get_chat_members_count(bot: Bot, event_loop): async def test_get_chat_member(bot: Bot, event_loop): """ getChatMember method test """ from .types.dataset import CHAT, CHAT_MEMBER + chat = types.Chat(**CHAT) member = types.ChatMember(**CHAT_MEMBER) @@ -515,10 +642,13 @@ async def test_get_chat_member(bot: Bot, event_loop): async def test_set_chat_sticker_set(bot: Bot, event_loop): """ setChatStickerSet method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.set_chat_sticker_set(chat_id=chat.id, sticker_set_name='aiogram_stickers') + result = await bot.set_chat_sticker_set( + chat_id=chat.id, sticker_set_name="aiogram_stickers" + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -528,6 +658,7 @@ async def test_set_chat_sticker_set(bot: Bot, event_loop): async def test_delete_chat_sticker_set(bot: Bot, event_loop): """ setChatStickerSet method test """ from .types.dataset import CHAT + chat = types.Chat(**CHAT) async with FakeTelegram(message_data=True, loop=event_loop): @@ -542,7 +673,9 @@ async def test_answer_callback_query(bot: Bot, event_loop): """ answerCallbackQuery method test """ async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.answer_callback_query(callback_query_id='QuERyId', text='Test Answer') + result = await bot.answer_callback_query( + callback_query_id="QuERyId", text="Test Answer" + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -554,7 +687,8 @@ async def test_set_my_commands(bot: Bot, event_loop): from .types.dataset import BOT_COMMAND async with FakeTelegram(message_data=True, loop=event_loop): - commands = [types.BotCommand(**BOT_COMMAND), types.BotCommand(**BOT_COMMAND)] + commands = [types.BotCommand( + **BOT_COMMAND), types.BotCommand(**BOT_COMMAND)] result = await bot.set_my_commands(commands) if not isinstance(result, bool): raise AssertionError @@ -565,6 +699,7 @@ async def test_set_my_commands(bot: Bot, event_loop): async def test_get_my_commands(bot: Bot, event_loop): """ getMyCommands method test """ from .types.dataset import BOT_COMMAND + command = types.BotCommand(**BOT_COMMAND) commands = [command, command] async with FakeTelegram(message_data=commands, loop=event_loop): @@ -578,11 +713,14 @@ async def test_get_my_commands(bot: Bot, event_loop): async def test_edit_message_text_by_bot(bot: Bot, event_loop): """ editMessageText method test """ from .types.dataset import EDITED_MESSAGE + msg = types.Message(**EDITED_MESSAGE) # message by bot async with FakeTelegram(message_data=EDITED_MESSAGE, loop=event_loop): - result = await bot.edit_message_text(text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id) + result = await bot.edit_message_text( + text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id + ) if result != msg: raise AssertionError @@ -590,11 +728,14 @@ async def test_edit_message_text_by_bot(bot: Bot, event_loop): async def test_edit_message_text_by_user(bot: Bot, event_loop): """ editMessageText method test """ from .types.dataset import EDITED_MESSAGE + msg = types.Message(**EDITED_MESSAGE) # message by user async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.edit_message_text(text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id) + result = await bot.edit_message_text( + text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id + ) if not isinstance(result, bool): raise AssertionError if result is not True: @@ -605,7 +746,9 @@ async def test_set_sticker_set_thumb(bot: Bot, event_loop): """ setStickerSetThumb method test """ async with FakeTelegram(message_data=True, loop=event_loop): - result = await bot.set_sticker_set_thumb(name='test', user_id=123456789, thumb='file_id') + result = await bot.set_sticker_set_thumb( + name="test", user_id=123456789, thumb="file_id" + ) if not isinstance(result, bool): raise AssertionError if result is not True: diff --git a/tests/test_bot/test_api.py b/tests/test_bot/test_api.py index 9b494154..9fc16087 100644 --- a/tests/test_bot/test_api.py +++ b/tests/test_bot/test_api.py @@ -3,13 +3,13 @@ import pytest from aiogram.bot.api import check_token from aiogram.utils.exceptions import ValidationError -VALID_TOKEN = '123456789:AABBCCDDEEFFaabbccddeeff-1234567890' +VALID_TOKEN = "123456789:AABBCCDDEEFFaabbccddeeff-1234567890" INVALID_TOKENS = [ - '123456789:AABBCCDDEEFFaabbccddeeff 123456789', # space is exists - 'ABC:AABBCCDDEEFFaabbccddeeff123456789', # left part is not digit - ':AABBCCDDEEFFaabbccddeeff123456789', # there is no left part - '123456789:', # there is no right part - 'ABC AABBCCDDEEFFaabbccddeeff123456789', # there is no ':' separator + "123456789:AABBCCDDEEFFaabbccddeeff 123456789", # space is exists + "ABC:AABBCCDDEEFFaabbccddeeff123456789", # left part is not digit + ":AABBCCDDEEFFaabbccddeeff123456789", # there is no left part + "123456789:", # there is no right part + "ABC AABBCCDDEEFFaabbccddeeff123456789", # there is no ':' separator None, # is None 12345678, # is digit {}, # is dict @@ -17,13 +17,12 @@ INVALID_TOKENS = [ ] -@pytest.fixture(params=INVALID_TOKENS, name='invalid_token') +@pytest.fixture(params=INVALID_TOKENS, name="invalid_token") def invalid_token_fixture(request): return request.param class TestCheckToken: - def test_valid(self): if check_token(VALID_TOKEN) is not True: raise AssertionError diff --git a/tests/test_bot/test_session.py b/tests/test_bot/test_session.py index 9115daa3..906d473d 100644 --- a/tests/test_bot/test_session.py +++ b/tests/test_bot/test_session.py @@ -38,7 +38,11 @@ class TestAiohttpSession: @pytest.mark.asyncio async def test_create_proxy_bot(self): socks_ver, host, port, username, password = ( - "socks5", "124.90.90.90", 9999, "login", "password" + "socks5", + "124.90.90.90", + 9999, + "login", + "password", ) bot = BaseBot( @@ -65,7 +69,9 @@ class TestAiohttpSession: @pytest.mark.asyncio async def test_close_session(self): - bot = BaseBot(token="42:correct",) + bot = BaseBot( + token="42:correct", + ) aiohttp_client_0 = bot.session with patch("aiohttp.ClientSession.close", new=CoroutineMock()) as mocked_close: diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index 9e146220..d38b4d8d 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -8,7 +8,7 @@ pytestmark = pytest.mark.asyncio @pytest.yield_fixture() async def bot(event_loop): """ Bot fixture """ - _bot = Bot(token='123456789:AABBCCDDEEFFaabbccddeeff-1234567890', + _bot = Bot(token="123456789:AABBCCDDEEFFaabbccddeeff-1234567890", loop=event_loop) yield _bot await _bot.close() @@ -26,7 +26,7 @@ class TestDispatcherInit: if not isinstance(dp, Dispatcher): raise AssertionError - @pytest.mark.parametrize("bot_instance", [None, Bot, 123, 'abc']) + @pytest.mark.parametrize("bot_instance", [None, Bot, 123, "abc"]) async def test_wrong_bot_instance(self, bot_instance): """ User provides wrong data to 'bot' argument. diff --git a/tests/test_dispatcher/test_filters/test_builtin.py b/tests/test_dispatcher/test_filters/test_builtin.py index 88b3f754..f981e9f5 100644 --- a/tests/test_dispatcher/test_filters/test_builtin.py +++ b/tests/test_dispatcher/test_filters/test_builtin.py @@ -12,15 +12,17 @@ from tests.types.dataset import MESSAGE, MESSAGE_FROM_CHANNEL class TestText: - - @pytest.mark.parametrize('param, key', [ - ('text', 'equals'), - ('text_contains', 'contains'), - ('text_startswith', 'startswith'), - ('text_endswith', 'endswith'), - ]) + @pytest.mark.parametrize( + "param, key", + [ + ("text", "equals"), + ("text_contains", "contains"), + ("text_startswith", "startswith"), + ("text_endswith", "endswith"), + ], + ) def test_validate(self, param, key): - value = 'spam and eggs' + value = "spam and eggs" config = {param: value} res = Text.validate(config) if res != {key: value}: @@ -28,45 +30,87 @@ class TestText: @pytest.mark.parametrize( - ('chat_id', 'expected'), + ("chat_id", "expected"), ( - pytest.param('-64856280', {-64856280,}, id='single negative int as string'), - pytest.param('64856280', {64856280,}, id='single positive int as string'), - pytest.param(-64856280, {-64856280,}, id='single negative int'), - pytest.param(64856280, {64856280,}, id='single positive negative int'), pytest.param( - ['-64856280'], {-64856280,}, id='list of single negative int as string' - ), - pytest.param([-64856280], {-64856280,}, id='list of single negative int'), - pytest.param( - ['-64856280', '-64856280'], - {-64856280,}, - id='list of two duplicated negative ints as strings', + "-64856280", + { + -64856280, + }, + id="single negative int as string", ), pytest.param( - ['-64856280', -64856280], - {-64856280,}, - id='list of one negative int as string and one negative int', + "64856280", + { + 64856280, + }, + id="single positive int as string", + ), + pytest.param( + -64856280, + { + -64856280, + }, + id="single negative int", + ), + pytest.param( + 64856280, + { + 64856280, + }, + id="single positive negative int", + ), + pytest.param( + ["-64856280"], + { + -64856280, + }, + id="list of single negative int as string", + ), + pytest.param( + [-64856280], + { + -64856280, + }, + id="list of single negative int", + ), + pytest.param( + ["-64856280", "-64856280"], + { + -64856280, + }, + id="list of two duplicated negative ints as strings", + ), + pytest.param( + ["-64856280", -64856280], + { + -64856280, + }, + id="list of one negative int as string and one negative int", ), pytest.param( [-64856280, -64856280], - {-64856280,}, - id='list of two duplicated negative ints', + { + -64856280, + }, + id="list of two duplicated negative ints", ), pytest.param( - iter(['-64856280']), - {-64856280,}, - id='iterator from a list of single negative int as string', + iter(["-64856280"]), + { + -64856280, + }, + id="iterator from a list of single negative int as string", ), pytest.param( [10000000, 20000000, 30000000], {10000000, 20000000, 30000000}, - id='list of several positive ints', + id="list of several positive ints", ), pytest.param( - [10000000, '20000000', -30000000], + [10000000, "20000000", -30000000], {10000000, 20000000, -30000000}, - id='list of positive int, positive int as string, negative int', + id="list of positive int, positive int as string, negative int", ), ), ) @@ -76,15 +120,16 @@ def test_extract_chat_ids(chat_id: ChatIDArgumentType, expected: Set[int]): class TestForwardedMessageFilter: - @pytest.mark.asyncio async def test_filter_forwarded_messages(self): filter = ForwardedMessageFilter(is_forwarded=True) - - forwarded_message = Message(forward_date=round(datetime(2020, 5, 21, 5, 1).timestamp()), **MESSAGE) - + + forwarded_message = Message( + forward_date=round(datetime(2020, 5, 21, 5, 1).timestamp()), **MESSAGE + ) + not_forwarded_message = Message(**MESSAGE) - + assert await filter.check(forwarded_message) if await filter.check(not_forwarded_message): raise AssertionError @@ -93,7 +138,9 @@ class TestForwardedMessageFilter: async def test_filter_not_forwarded_messages(self): filter = ForwardedMessageFilter(is_forwarded=False) - forwarded_message = Message(forward_date=round(datetime(2020, 5, 21, 5, 1).timestamp()), **MESSAGE) + forwarded_message = Message( + forward_date=round(datetime(2020, 5, 21, 5, 1).timestamp()), **MESSAGE + ) not_forwarded_message = Message(**MESSAGE) @@ -103,7 +150,6 @@ class TestForwardedMessageFilter: class TestIDFilter: - @pytest.mark.asyncio async def test_chat_id_for_channels(self): message_from_channel = Message(**MESSAGE_FROM_CHANNEL) diff --git a/tests/test_dispatcher/test_filters/test_state.py b/tests/test_dispatcher/test_filters/test_state.py index 78bebe01..5c1ac676 100644 --- a/tests/test_dispatcher/test_filters/test_state.py +++ b/tests/test_dispatcher/test_filters/test_state.py @@ -2,9 +2,7 @@ from aiogram.dispatcher.filters.state import StatesGroup class TestStatesGroup: - def test_all_childs(self): - class InnerState1(StatesGroup): pass diff --git a/tests/test_dispatcher/test_handler.py b/tests/test_dispatcher/test_handler.py index 993176af..c9d5e105 100644 --- a/tests/test_dispatcher/test_handler.py +++ b/tests/test_dispatcher/test_handler.py @@ -51,7 +51,9 @@ class TestHandlerObj: "callback,kwargs,result", [ pytest.param( - callback1, {"foo": 42, "spam": True, "baz": "fuz"}, {"foo": 42, "baz": "fuz"} + callback1, + {"foo": 42, "spam": True, "baz": "fuz"}, + {"foo": 42, "baz": "fuz"}, ), pytest.param( callback2, diff --git a/tests/test_filters.py b/tests/test_filters.py index 940b166e..ab6cf3d5 100644 --- a/tests/test_filters.py +++ b/tests/test_filters.py @@ -12,25 +12,21 @@ pytestmark = pytest.mark.asyncio def data_sample_1(): return [ - ('', ''), - ('', 'exAmple_string'), - - ('example_string', 'example_string'), - ('example_string', 'exAmple_string'), - ('exAmple_string', 'example_string'), - - ('example_string', 'example_string_dsf'), - ('example_string', 'example_striNG_dsf'), - ('example_striNG', 'example_string_dsf'), - - ('example_string', 'not_example_string'), - ('example_string', 'not_eXample_string'), - ('EXample_string', 'not_example_string'), + ("", ""), + ("", "exAmple_string"), + ("example_string", "example_string"), + ("example_string", "exAmple_string"), + ("exAmple_string", "example_string"), + ("example_string", "example_string_dsf"), + ("example_string", "example_striNG_dsf"), + ("example_striNG", "example_string_dsf"), + ("example_string", "not_example_string"), + ("example_string", "not_eXample_string"), + ("EXample_string", "not_example_string"), ] class TestTextFilter: - @staticmethod async def _run_check(check, test_text): assert await check(Message(text=test_text)) @@ -38,7 +34,7 @@ class TestTextFilter: assert await check(InlineQuery(query=test_text)) assert await check(Poll(question=test_text)) - @pytest.mark.parametrize('ignore_case', (True, False)) + @pytest.mark.parametrize("ignore_case", (True, False)) @pytest.mark.parametrize("test_prefix, test_text", data_sample_1()) async def test_startswith(self, test_prefix, test_text, ignore_case): test_filter = Text(startswith=test_prefix, ignore_case=ignore_case) @@ -56,25 +52,26 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_prefix_list, test_text", [ - (['not_example', ''], ''), - (['', 'not_example'], 'exAmple_string'), - - (['not_example', 'example_string'], 'example_string'), - (['example_string', 'not_example'], 'exAmple_string'), - (['not_example', 'exAmple_string'], 'example_string'), - - (['not_example', 'example_string'], 'example_string_dsf'), - (['example_string', 'not_example'], 'example_striNG_dsf'), - (['not_example', 'example_striNG'], 'example_string_dsf'), - - (['not_example', 'example_string'], 'not_example_string'), - (['example_string', 'not_example'], 'not_eXample_string'), - (['not_example', 'EXample_string'], 'not_example_string'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_prefix_list, test_text", + [ + (["not_example", ""], ""), + (["", "not_example"], "exAmple_string"), + (["not_example", "example_string"], "example_string"), + (["example_string", "not_example"], "exAmple_string"), + (["not_example", "exAmple_string"], "example_string"), + (["not_example", "example_string"], "example_string_dsf"), + (["example_string", "not_example"], "example_striNG_dsf"), + (["not_example", "example_striNG"], "example_string_dsf"), + (["not_example", "example_string"], "not_example_string"), + (["example_string", "not_example"], "not_eXample_string"), + (["not_example", "EXample_string"], "not_example_string"), + ], + ) async def test_startswith_list(self, test_prefix_list, test_text, ignore_case): - test_filter = Text(startswith=test_prefix_list, ignore_case=ignore_case) + test_filter = Text(startswith=test_prefix_list, + ignore_case=ignore_case) async def check(obj): result = await test_filter.check(obj) @@ -89,7 +86,7 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) + @pytest.mark.parametrize("ignore_case", (True, False)) @pytest.mark.parametrize("test_postfix, test_text", data_sample_1()) async def test_endswith(self, test_postfix, test_text, ignore_case): test_filter = Text(endswith=test_postfix, ignore_case=ignore_case) @@ -107,23 +104,23 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_postfix_list, test_text", [ - (['', 'not_example'], ''), - (['not_example', ''], 'exAmple_string'), - - (['example_string', 'not_example'], 'example_string'), - (['not_example', 'example_string'], 'exAmple_string'), - (['exAmple_string', 'not_example'], 'example_string'), - - (['not_example', 'example_string'], 'example_string_dsf'), - (['example_string', 'not_example'], 'example_striNG_dsf'), - (['not_example', 'example_striNG'], 'example_string_dsf'), - - (['not_example', 'example_string'], 'not_example_string'), - (['example_string', 'not_example'], 'not_eXample_string'), - (['not_example', 'EXample_string'], 'not_example_string'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_postfix_list, test_text", + [ + (["", "not_example"], ""), + (["not_example", ""], "exAmple_string"), + (["example_string", "not_example"], "example_string"), + (["not_example", "example_string"], "exAmple_string"), + (["exAmple_string", "not_example"], "example_string"), + (["not_example", "example_string"], "example_string_dsf"), + (["example_string", "not_example"], "example_striNG_dsf"), + (["not_example", "example_striNG"], "example_string_dsf"), + (["not_example", "example_string"], "not_example_string"), + (["example_string", "not_example"], "not_eXample_string"), + (["not_example", "EXample_string"], "not_example_string"), + ], + ) async def test_endswith_list(self, test_postfix_list, test_text, ignore_case): test_filter = Text(endswith=test_postfix_list, ignore_case=ignore_case) @@ -140,23 +137,23 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_string, test_text", [ - ('', ''), - ('', 'exAmple_string'), - - ('example_string', 'example_string'), - ('example_string', 'exAmple_string'), - ('exAmple_string', 'example_string'), - - ('example_string', 'example_string_dsf'), - ('example_string', 'example_striNG_dsf'), - ('example_striNG', 'example_string_dsf'), - - ('example_string', 'not_example_strin'), - ('example_string', 'not_eXample_strin'), - ('EXample_string', 'not_example_strin'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_string, test_text", + [ + ("", ""), + ("", "exAmple_string"), + ("example_string", "example_string"), + ("example_string", "exAmple_string"), + ("exAmple_string", "example_string"), + ("example_string", "example_string_dsf"), + ("example_string", "example_striNG_dsf"), + ("example_striNG", "example_string_dsf"), + ("example_string", "not_example_strin"), + ("example_string", "not_eXample_strin"), + ("EXample_string", "not_example_strin"), + ], + ) async def test_contains(self, test_string, test_text, ignore_case): test_filter = Text(contains=test_string, ignore_case=ignore_case) @@ -173,13 +170,16 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_filter_list, test_text", [ - (['a', 'ab', 'abc'], 'A'), - (['a', 'ab', 'abc'], 'ab'), - (['a', 'ab', 'abc'], 'aBc'), - (['a', 'ab', 'abc'], 'd'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_filter_list, test_text", + [ + (["a", "ab", "abc"], "A"), + (["a", "ab", "abc"], "ab"), + (["a", "ab", "abc"], "aBc"), + (["a", "ab", "abc"], "d"), + ], + ) async def test_contains_list(self, test_filter_list, test_text, ignore_case): test_filter = Text(contains=test_filter_list, ignore_case=ignore_case) @@ -196,19 +196,20 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_filter_text, test_text", [ - ('', ''), - ('', 'exAmple_string'), - - ('example_string', 'example_string'), - ('example_string', 'exAmple_string'), - ('exAmple_string', 'example_string'), - - ('example_string', 'not_example_string'), - ('example_string', 'not_eXample_string'), - ('EXample_string', 'not_example_string'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_filter_text, test_text", + [ + ("", ""), + ("", "exAmple_string"), + ("example_string", "example_string"), + ("example_string", "exAmple_string"), + ("exAmple_string", "example_string"), + ("example_string", "not_example_string"), + ("example_string", "not_eXample_string"), + ("EXample_string", "not_example_string"), + ], + ) async def test_equals_string(self, test_filter_text, test_text, ignore_case): test_filter = Text(equals=test_filter_text, ignore_case=ignore_case) @@ -224,27 +225,26 @@ class TestTextFilter: await self._run_check(check, test_text) - @pytest.mark.parametrize('ignore_case', (True, False)) - @pytest.mark.parametrize("test_filter_list, test_text", [ - (['new_string', ''], ''), - (['', 'new_string'], 'exAmple_string'), - - (['example_string'], 'example_string'), - (['example_string'], 'exAmple_string'), - (['exAmple_string'], 'example_string'), - - (['example_string'], 'not_example_string'), - (['example_string'], 'not_eXample_string'), - (['EXample_string'], 'not_example_string'), - - (['example_string', 'new_string'], 'example_string'), - (['new_string', 'example_string'], 'exAmple_string'), - (['exAmple_string', 'new_string'], 'example_string'), - - (['example_string', 'new_string'], 'not_example_string'), - (['new_string', 'example_string'], 'not_eXample_string'), - (['EXample_string', 'new_string'], 'not_example_string'), - ]) + @pytest.mark.parametrize("ignore_case", (True, False)) + @pytest.mark.parametrize( + "test_filter_list, test_text", + [ + (["new_string", ""], ""), + (["", "new_string"], "exAmple_string"), + (["example_string"], "example_string"), + (["example_string"], "exAmple_string"), + (["exAmple_string"], "example_string"), + (["example_string"], "not_example_string"), + (["example_string"], "not_eXample_string"), + (["EXample_string"], "not_example_string"), + (["example_string", "new_string"], "example_string"), + (["new_string", "example_string"], "exAmple_string"), + (["exAmple_string", "new_string"], "example_string"), + (["example_string", "new_string"], "not_example_string"), + (["new_string", "example_string"], "not_eXample_string"), + (["EXample_string", "new_string"], "not_example_string"), + ], + ) async def test_equals_list(self, test_filter_list, test_text, ignore_case): test_filter = Text(equals=test_filter_list, ignore_case=ignore_case) @@ -266,12 +266,12 @@ class TestTextFilter: class TestCommandStart: - START = '/start' - GOOD = 'foo' - BAD = 'bar' - GOOD_PATTERN = re.compile(r'^f..$') - BAD_PATTERN = re.compile(r'^b..$') - ENCODED = 'Zm9v' + START = "/start" + GOOD = "foo" + BAD = "bar" + GOOD_PATTERN = re.compile(r"^f..$") + BAD_PATTERN = re.compile(r"^b..$") + ENCODED = "Zm9v" async def test_start_command_without_payload(self): test_filter = CommandStart() # empty filter @@ -282,38 +282,38 @@ class TestCommandStart: async def test_start_command_payload_is_matched(self): test_filter = CommandStart(deep_link=self.GOOD) - message = Message(text=f'{self.START} {self.GOOD}') + message = Message(text=f"{self.START} {self.GOOD}") result = await test_filter.check(message) - if result != {'deep_link': self.GOOD}: + if result != {"deep_link": self.GOOD}: raise AssertionError async def test_start_command_payload_is_not_matched(self): test_filter = CommandStart(deep_link=self.GOOD) - message = Message(text=f'{self.START} {self.BAD}') + message = Message(text=f"{self.START} {self.BAD}") result = await test_filter.check(message) if result is not False: raise AssertionError async def test_start_command_payload_pattern_is_matched(self): test_filter = CommandStart(deep_link=self.GOOD_PATTERN) - message = Message(text=f'{self.START} {self.GOOD}') + message = Message(text=f"{self.START} {self.GOOD}") result = await test_filter.check(message) if not isinstance(result, dict): raise AssertionError - match = result.get('deep_link') + match = result.get("deep_link") if not isinstance(match, Match): raise AssertionError async def test_start_command_payload_pattern_is_not_matched(self): test_filter = CommandStart(deep_link=self.BAD_PATTERN) - message = Message(text=f'{self.START} {self.GOOD}') + message = Message(text=f"{self.START} {self.GOOD}") result = await test_filter.check(message) if result is not False: raise AssertionError async def test_start_command_payload_is_encoded(self): test_filter = CommandStart(deep_link=self.GOOD, encoded=True) - message = Message(text=f'{self.START} {self.ENCODED}') + message = Message(text=f"{self.START} {self.ENCODED}") result = await test_filter.check(message) - if result != {'deep_link': self.GOOD}: + if result != {"deep_link": self.GOOD}: raise AssertionError diff --git a/tests/test_states_group.py b/tests/test_states_group.py index ebec1f64..05e81eaa 100644 --- a/tests/test_states_group.py +++ b/tests/test_states_group.py @@ -14,15 +14,15 @@ class MyGroup(StatesGroup): sub_state_1 = State() sub_state_2 = State() - in_custom_group = State(group_name='custom_group') + in_custom_group = State(group_name="custom_group") class NewGroup(StatesGroup): spam = State() - renamed_state = State(state='spam_state') + renamed_state = State(state="spam_state") -alone_state = State('alone') -alone_in_group = State('alone', group_name='home') +alone_state = State("alone") +alone_in_group = State("alone", group_name="home") def test_default_state(): @@ -31,41 +31,44 @@ def test_default_state(): def test_any_state(): - if any_state.state != '*': + if any_state.state != "*": raise AssertionError def test_alone_state(): - if alone_state.state != '@:alone': + if alone_state.state != "@:alone": raise AssertionError - if alone_in_group.state != 'home:alone': + if alone_in_group.state != "home:alone": raise AssertionError def test_group_names(): - if MyGroup.__group_name__ != 'MyGroup': + if MyGroup.__group_name__ != "MyGroup": raise AssertionError - if MyGroup.__full_group_name__ != 'MyGroup': + if MyGroup.__full_group_name__ != "MyGroup": raise AssertionError - if MyGroup.MySubGroup.__group_name__ != 'MySubGroup': + if MyGroup.MySubGroup.__group_name__ != "MySubGroup": raise AssertionError - if MyGroup.MySubGroup.__full_group_name__ != 'MyGroup.MySubGroup': + if MyGroup.MySubGroup.__full_group_name__ != "MyGroup.MySubGroup": raise AssertionError - if MyGroup.MySubGroup.NewGroup.__group_name__ != 'NewGroup': + if MyGroup.MySubGroup.NewGroup.__group_name__ != "NewGroup": raise AssertionError - if MyGroup.MySubGroup.NewGroup.__full_group_name__ != 'MyGroup.MySubGroup.NewGroup': + if MyGroup.MySubGroup.NewGroup.__full_group_name__ != "MyGroup.MySubGroup.NewGroup": raise AssertionError def test_custom_group_in_group(): - if MyGroup.MySubGroup.in_custom_group.state != 'custom_group:in_custom_group': + if MyGroup.MySubGroup.in_custom_group.state != "custom_group:in_custom_group": raise AssertionError def test_custom_state_name_in_group(): - if MyGroup.MySubGroup.NewGroup.renamed_state.state != 'MyGroup.MySubGroup.NewGroup:spam_state': + if ( + MyGroup.MySubGroup.NewGroup.renamed_state.state + != "MyGroup.MySubGroup.NewGroup:spam_state" + ): raise AssertionError @@ -75,38 +78,48 @@ def test_group_states_names(): if len(MyGroup.all_states) != 9: raise AssertionError - if MyGroup.states_names != ('MyGroup:state', 'MyGroup:state_1', 'MyGroup:state_2'): + if MyGroup.states_names != ("MyGroup:state", "MyGroup:state_1", "MyGroup:state_2"): raise AssertionError if MyGroup.MySubGroup.states_names != ( - 'MyGroup.MySubGroup:sub_state', 'MyGroup.MySubGroup:sub_state_1', 'MyGroup.MySubGroup:sub_state_2', - 'custom_group:in_custom_group'): + "MyGroup.MySubGroup:sub_state", + "MyGroup.MySubGroup:sub_state_1", + "MyGroup.MySubGroup:sub_state_2", + "custom_group:in_custom_group", + ): raise AssertionError if MyGroup.MySubGroup.NewGroup.states_names != ( - 'MyGroup.MySubGroup.NewGroup:spam', 'MyGroup.MySubGroup.NewGroup:spam_state'): + "MyGroup.MySubGroup.NewGroup:spam", + "MyGroup.MySubGroup.NewGroup:spam_state", + ): raise AssertionError if MyGroup.all_states_names != ( - 'MyGroup:state', 'MyGroup:state_1', 'MyGroup:state_2', - 'MyGroup.MySubGroup:sub_state', - 'MyGroup.MySubGroup:sub_state_1', - 'MyGroup.MySubGroup:sub_state_2', - 'custom_group:in_custom_group', - 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state'): + "MyGroup:state", + "MyGroup:state_1", + "MyGroup:state_2", + "MyGroup.MySubGroup:sub_state", + "MyGroup.MySubGroup:sub_state_1", + "MyGroup.MySubGroup:sub_state_2", + "custom_group:in_custom_group", + "MyGroup.MySubGroup.NewGroup:spam", + "MyGroup.MySubGroup.NewGroup:spam_state", + ): raise AssertionError if MyGroup.MySubGroup.all_states_names != ( - 'MyGroup.MySubGroup:sub_state', - 'MyGroup.MySubGroup:sub_state_1', - 'MyGroup.MySubGroup:sub_state_2', - 'custom_group:in_custom_group', - 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state'): + "MyGroup.MySubGroup:sub_state", + "MyGroup.MySubGroup:sub_state_1", + "MyGroup.MySubGroup:sub_state_2", + "custom_group:in_custom_group", + "MyGroup.MySubGroup.NewGroup:spam", + "MyGroup.MySubGroup.NewGroup:spam_state", + ): raise AssertionError if MyGroup.MySubGroup.NewGroup.all_states_names != ( - 'MyGroup.MySubGroup.NewGroup:spam', - 'MyGroup.MySubGroup.NewGroup:spam_state'): + "MyGroup.MySubGroup.NewGroup:spam", + "MyGroup.MySubGroup.NewGroup:spam_state", + ): raise AssertionError diff --git a/tests/test_utils/test_auth_widget.py b/tests/test_utils/test_auth_widget.py index c8bdd394..dcdccf29 100644 --- a/tests/test_utils/test_auth_widget.py +++ b/tests/test_utils/test_auth_widget.py @@ -3,25 +3,25 @@ import pytest from aiogram.utils.auth_widget import (check_integrity, check_token, generate_hash) -TOKEN = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11' +TOKEN = "123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11" @pytest.fixture def data(): return { - 'id': '42', - 'first_name': 'John', - 'last_name': 'Smith', - 'username': 'username', - 'photo_url': 'https://t.me/i/userpic/320/picname.jpg', - 'auth_date': '1565810688', - 'hash': 'c303db2b5a06fe41d23a9b14f7c545cfc11dcc7473c07c9c5034ae60062461ce', + "id": "42", + "first_name": "John", + "last_name": "Smith", + "username": "username", + "photo_url": "https://t.me/i/userpic/320/picname.jpg", + "auth_date": "1565810688", + "hash": "c303db2b5a06fe41d23a9b14f7c545cfc11dcc7473c07c9c5034ae60062461ce", } def test_generate_hash(data): res = generate_hash(data, TOKEN) - if res != data['hash']: + if res != data["hash"]: raise AssertionError @@ -29,23 +29,23 @@ class Test_check_token: """ This case gonna be deleted """ + def test_ok(self, data): if check_token(data, TOKEN) is not True: raise AssertionError def test_fail(self, data): - data.pop('username') + data.pop("username") if check_token(data, TOKEN) is not False: raise AssertionError class Test_check_integrity: - def test_ok(self, data): if check_integrity(TOKEN, data) is not True: raise AssertionError def test_fail(self, data): - data.pop('username') + data.pop("username") if check_integrity(TOKEN, data) is not False: raise AssertionError diff --git a/tests/test_utils/test_deep_linking.py b/tests/test_utils/test_deep_linking.py index 69821c70..a3d730fc 100644 --- a/tests/test_utils/test_deep_linking.py +++ b/tests/test_utils/test_deep_linking.py @@ -9,26 +9,26 @@ from tests.types import dataset pytestmark = pytest.mark.asyncio PAYLOADS = [ - 'foo', - 'AAbbCCddEEff1122334455', - 'aaBBccDDeeFF5544332211', + "foo", + "AAbbCCddEEff1122334455", + "aaBBccDDeeFF5544332211", -12345678901234567890, 12345678901234567890, ] WRONG_PAYLOADS = [ - '@BotFather', - 'spaces spaces spaces', + "@BotFather", + "spaces spaces spaces", 1234567890123456789.0, ] -@pytest.fixture(params=PAYLOADS, name='payload') +@pytest.fixture(params=PAYLOADS, name="payload") def payload_fixture(request): return request.param -@pytest.fixture(params=WRONG_PAYLOADS, name='wrong_payload') +@pytest.fixture(params=WRONG_PAYLOADS, name="wrong_payload") def wrong_payload_fixture(request): return request.param @@ -40,9 +40,10 @@ def get_bot_user_fixture(monkeypatch): async def get_bot_user_mock(): from aiogram.types import User + return User(**dataset.USER) - monkeypatch.setattr(deep_linking, '_get_bot_user', get_bot_user_mock) + monkeypatch.setattr(deep_linking, "_get_bot_user", get_bot_user_mock) class TestDeepLinking: diff --git a/tests/test_utils/test_deprecated.py b/tests/test_utils/test_deprecated.py index f7178e0e..5ef92da5 100644 --- a/tests/test_utils/test_deprecated.py +++ b/tests/test_utils/test_deprecated.py @@ -4,13 +4,21 @@ from aiogram.utils.deprecated import DeprecatedReadOnlyClassVar def test_DeprecatedReadOnlyClassVarCD(): - if DeprecatedReadOnlyClassVar.__slots__ != ("_new_value_getter", "_warning_message"): + if DeprecatedReadOnlyClassVar.__slots__ != ( + "_new_value_getter", + "_warning_message", + ): raise AssertionError new_value_of_deprecated_cls_cd = "mpa" - deprecated_cd = DeprecatedReadOnlyClassVar("mopekaa", lambda owner: new_value_of_deprecated_cls_cd) + deprecated_cd = DeprecatedReadOnlyClassVar( + "mopekaa", lambda owner: new_value_of_deprecated_cls_cd + ) with pytest.warns(DeprecationWarning): pseudo_owner_cls = type("OpekaCla$$", (), {}) - if deprecated_cd.__get__(None, pseudo_owner_cls) != new_value_of_deprecated_cls_cd: + if ( + deprecated_cd.__get__(None, pseudo_owner_cls) + != new_value_of_deprecated_cls_cd + ): raise AssertionError diff --git a/tests/test_utils/test_helper.py b/tests/test_utils/test_helper.py index 4950dd7e..0faf1af5 100644 --- a/tests/test_utils/test_helper.py +++ b/tests/test_utils/test_helper.py @@ -2,7 +2,6 @@ from aiogram.utils.helper import Item, ListItem, OrderedHelper class TestOrderedHelper: - def test_items_are_ordered(self): class Helper(OrderedHelper): A = Item() @@ -10,7 +9,7 @@ class TestOrderedHelper: C = Item() B = Item() - if Helper.all() != ['A', 'D', 'C', 'B']: + if Helper.all() != ["A", "D", "C", "B"]: raise AssertionError def test_list_items_are_ordered(self): @@ -20,5 +19,5 @@ class TestOrderedHelper: C = ListItem() B = ListItem() - if Helper.all() != ['A', 'D', 'C', 'B']: + if Helper.all() != ["A", "D", "C", "B"]: raise AssertionError diff --git a/tests/test_utils/test_markdown.py b/tests/test_utils/test_markdown.py index 2a006dd1..c47d8663 100644 --- a/tests/test_utils/test_markdown.py +++ b/tests/test_utils/test_markdown.py @@ -4,10 +4,10 @@ from aiogram.utils import markdown class TestMarkdownEscape: - def test_equality_sign_is_escaped(self): - if markdown.escape_md(r"e = mc2") != r"e \= mc2": - raise AssertionError + def test_equality_sign_is_escaped(self): + if markdown.escape_md(r"e = mc2") != r"e \= mc2": + raise AssertionError - def test_pre_escaped(self): - if markdown.escape_md(r"hello\.") != r"hello\\\.": - raise AssertionError + def test_pre_escaped(self): + if markdown.escape_md(r"hello\.") != r"hello\\\.": + raise AssertionError diff --git a/tests/test_utils/test_text_decorations.py b/tests/test_utils/test_text_decorations.py index 2ebf77c5..34003a1c 100644 --- a/tests/test_utils/test_text_decorations.py +++ b/tests/test_utils/test_text_decorations.py @@ -3,25 +3,35 @@ from aiogram.utils import text_decorations class TestTextDecorations: - def test_unparse_entities_normal_text(self): - if text_decorations.markdown_decoration.unparse( - "hi i'm bold and italic and still bold", - entities=[ - MessageEntity(offset=3, length=34, type=MessageEntityType.BOLD), - MessageEntity(offset=12, length=10, type=MessageEntityType.ITALIC), - ] - ) != "hi *i'm bold _\rand italic_\r and still bold*": - raise AssertionError + def test_unparse_entities_normal_text(self): + if ( + text_decorations.markdown_decoration.unparse( + "hi i'm bold and italic and still bold", + entities=[ + MessageEntity(offset=3, length=34, + type=MessageEntityType.BOLD), + MessageEntity(offset=12, length=10, + type=MessageEntityType.ITALIC), + ], + ) + != "hi *i'm bold _\rand italic_\r and still bold*" + ): + raise AssertionError - def test_unparse_entities_emoji_text(self): - """ - emoji is encoded as two chars in json - """ - if text_decorations.markdown_decoration.unparse( - "🚀 i'm bold and italic and still bold", - entities=[ - MessageEntity(offset=3, length=34, type=MessageEntityType.BOLD), - MessageEntity(offset=12, length=10, type=MessageEntityType.ITALIC), - ] - ) != "🚀 *i'm bold _\rand italic_\r and still bold*": - raise AssertionError + def test_unparse_entities_emoji_text(self): + """ + emoji is encoded as two chars in json + """ + if ( + text_decorations.markdown_decoration.unparse( + "🚀 i'm bold and italic and still bold", + entities=[ + MessageEntity(offset=3, length=34, + type=MessageEntityType.BOLD), + MessageEntity(offset=12, length=10, + type=MessageEntityType.ITALIC), + ], + ) + != "🚀 *i'm bold _\rand italic_\r and still bold*" + ): + raise AssertionError diff --git a/tests/types/test_animation.py b/tests/types/test_animation.py index 3e8a075d..14140c70 100644 --- a/tests/types/test_animation.py +++ b/tests/types/test_animation.py @@ -16,14 +16,14 @@ def test_export(): def test_file_name(): if not isinstance(animation.file_name, str): raise AssertionError - if animation.file_name != ANIMATION['file_name']: + if animation.file_name != ANIMATION["file_name"]: raise AssertionError def test_mime_type(): if not isinstance(animation.mime_type, str): raise AssertionError - if animation.mime_type != ANIMATION['mime_type']: + if animation.mime_type != ANIMATION["mime_type"]: raise AssertionError @@ -31,25 +31,25 @@ def test_file_id(): if not isinstance(animation.file_id, str): raise AssertionError # assert hash(animation) == ANIMATION['file_id'] - if animation.file_id != ANIMATION['file_id']: + if animation.file_id != ANIMATION["file_id"]: raise AssertionError def test_file_size(): if not isinstance(animation.file_size, int): raise AssertionError - if animation.file_size != ANIMATION['file_size']: + if animation.file_size != ANIMATION["file_size"]: raise AssertionError def test_thumb(): if not isinstance(animation.thumb, types.PhotoSize): raise AssertionError - if animation.thumb.file_id != ANIMATION['thumb']['file_id']: + if animation.thumb.file_id != ANIMATION["thumb"]["file_id"]: raise AssertionError - if animation.thumb.width != ANIMATION['thumb']['width']: + if animation.thumb.width != ANIMATION["thumb"]["width"]: raise AssertionError - if animation.thumb.height != ANIMATION['thumb']['height']: + if animation.thumb.height != ANIMATION["thumb"]["height"]: raise AssertionError - if animation.thumb.file_size != ANIMATION['thumb']['file_size']: + if animation.thumb.file_size != ANIMATION["thumb"]["file_size"]: raise AssertionError diff --git a/tests/types/test_chat.py b/tests/types/test_chat.py index a01447b6..18cb0cae 100644 --- a/tests/types/test_chat.py +++ b/tests/types/test_chat.py @@ -16,7 +16,7 @@ def test_export(): def test_id(): if not isinstance(chat.id, int): raise AssertionError - if chat.id != CHAT['id']: + if chat.id != CHAT["id"]: raise AssertionError # assert hash(chat) == CHAT['id'] @@ -24,40 +24,41 @@ def test_id(): def test_name(): if not isinstance(chat.first_name, str): raise AssertionError - if chat.first_name != CHAT['first_name']: + if chat.first_name != CHAT["first_name"]: raise AssertionError if not isinstance(chat.last_name, str): raise AssertionError - if chat.last_name != CHAT['last_name']: + if chat.last_name != CHAT["last_name"]: raise AssertionError if not isinstance(chat.username, str): raise AssertionError - if chat.username != CHAT['username']: + if chat.username != CHAT["username"]: raise AssertionError def test_type(): if not isinstance(chat.type, str): raise AssertionError - if chat.type != CHAT['type']: + if chat.type != CHAT["type"]: raise AssertionError def test_chat_types(): - if types.ChatType.PRIVATE != 'private': + if types.ChatType.PRIVATE != "private": raise AssertionError - if types.ChatType.GROUP != 'group': + if types.ChatType.GROUP != "group": raise AssertionError - if types.ChatType.SUPER_GROUP != 'supergroup': + if types.ChatType.SUPER_GROUP != "supergroup": raise AssertionError - if types.ChatType.CHANNEL != 'channel': + if types.ChatType.CHANNEL != "channel": raise AssertionError def test_chat_type_filters(): from . import test_message + if not types.ChatType.is_private(test_message.message): raise AssertionError if types.ChatType.is_group(test_message.message): @@ -71,23 +72,23 @@ def test_chat_type_filters(): def test_chat_actions(): - if types.ChatActions.TYPING != 'typing': + if types.ChatActions.TYPING != "typing": raise AssertionError - if types.ChatActions.UPLOAD_PHOTO != 'upload_photo': + if types.ChatActions.UPLOAD_PHOTO != "upload_photo": raise AssertionError - if types.ChatActions.RECORD_VIDEO != 'record_video': + if types.ChatActions.RECORD_VIDEO != "record_video": raise AssertionError - if types.ChatActions.UPLOAD_VIDEO != 'upload_video': + if types.ChatActions.UPLOAD_VIDEO != "upload_video": raise AssertionError - if types.ChatActions.RECORD_AUDIO != 'record_audio': + if types.ChatActions.RECORD_AUDIO != "record_audio": raise AssertionError - if types.ChatActions.UPLOAD_AUDIO != 'upload_audio': + if types.ChatActions.UPLOAD_AUDIO != "upload_audio": raise AssertionError - if types.ChatActions.UPLOAD_DOCUMENT != 'upload_document': + if types.ChatActions.UPLOAD_DOCUMENT != "upload_document": raise AssertionError - if types.ChatActions.FIND_LOCATION != 'find_location': + if types.ChatActions.FIND_LOCATION != "find_location": raise AssertionError - if types.ChatActions.RECORD_VIDEO_NOTE != 'record_video_note': + if types.ChatActions.RECORD_VIDEO_NOTE != "record_video_note": raise AssertionError - if types.ChatActions.UPLOAD_VIDEO_NOTE != 'upload_video_note': + if types.ChatActions.UPLOAD_VIDEO_NOTE != "upload_video_note": raise AssertionError diff --git a/tests/types/test_chat_member.py b/tests/types/test_chat_member.py index d8cbac10..ab25a577 100644 --- a/tests/types/test_chat_member.py +++ b/tests/types/test_chat_member.py @@ -21,44 +21,44 @@ def test_user(): def test_status(): if not isinstance(chat_member.status, str): raise AssertionError - if chat_member.status != CHAT_MEMBER['status']: + if chat_member.status != CHAT_MEMBER["status"]: raise AssertionError def test_privileges(): if not isinstance(chat_member.can_be_edited, bool): raise AssertionError - if chat_member.can_be_edited != CHAT_MEMBER['can_be_edited']: + if chat_member.can_be_edited != CHAT_MEMBER["can_be_edited"]: raise AssertionError if not isinstance(chat_member.can_change_info, bool): raise AssertionError - if chat_member.can_change_info != CHAT_MEMBER['can_change_info']: + if chat_member.can_change_info != CHAT_MEMBER["can_change_info"]: raise AssertionError if not isinstance(chat_member.can_delete_messages, bool): raise AssertionError - if chat_member.can_delete_messages != CHAT_MEMBER['can_delete_messages']: + if chat_member.can_delete_messages != CHAT_MEMBER["can_delete_messages"]: raise AssertionError if not isinstance(chat_member.can_invite_users, bool): raise AssertionError - if chat_member.can_invite_users != CHAT_MEMBER['can_invite_users']: + if chat_member.can_invite_users != CHAT_MEMBER["can_invite_users"]: raise AssertionError if not isinstance(chat_member.can_restrict_members, bool): raise AssertionError - if chat_member.can_restrict_members != CHAT_MEMBER['can_restrict_members']: + if chat_member.can_restrict_members != CHAT_MEMBER["can_restrict_members"]: raise AssertionError if not isinstance(chat_member.can_pin_messages, bool): raise AssertionError - if chat_member.can_pin_messages != CHAT_MEMBER['can_pin_messages']: + if chat_member.can_pin_messages != CHAT_MEMBER["can_pin_messages"]: raise AssertionError if not isinstance(chat_member.can_promote_members, bool): raise AssertionError - if chat_member.can_promote_members != CHAT_MEMBER['can_promote_members']: + if chat_member.can_promote_members != CHAT_MEMBER["can_promote_members"]: raise AssertionError @@ -70,17 +70,17 @@ def test_int(): def test_chat_member_status(): - if types.ChatMemberStatus.CREATOR != 'creator': + if types.ChatMemberStatus.CREATOR != "creator": raise AssertionError - if types.ChatMemberStatus.ADMINISTRATOR != 'administrator': + if types.ChatMemberStatus.ADMINISTRATOR != "administrator": raise AssertionError - if types.ChatMemberStatus.MEMBER != 'member': + if types.ChatMemberStatus.MEMBER != "member": raise AssertionError - if types.ChatMemberStatus.RESTRICTED != 'restricted': + if types.ChatMemberStatus.RESTRICTED != "restricted": raise AssertionError - if types.ChatMemberStatus.LEFT != 'left': + if types.ChatMemberStatus.LEFT != "left": raise AssertionError - if types.ChatMemberStatus.KICKED != 'kicked': + if types.ChatMemberStatus.KICKED != "kicked": raise AssertionError diff --git a/tests/types/test_document.py b/tests/types/test_document.py index 4a76975a..d61e0513 100644 --- a/tests/types/test_document.py +++ b/tests/types/test_document.py @@ -16,14 +16,14 @@ def test_export(): def test_file_name(): if not isinstance(document.file_name, str): raise AssertionError - if document.file_name != DOCUMENT['file_name']: + if document.file_name != DOCUMENT["file_name"]: raise AssertionError def test_mime_type(): if not isinstance(document.mime_type, str): raise AssertionError - if document.mime_type != DOCUMENT['mime_type']: + if document.mime_type != DOCUMENT["mime_type"]: raise AssertionError @@ -31,14 +31,14 @@ def test_file_id(): if not isinstance(document.file_id, str): raise AssertionError # assert hash(document) == DOCUMENT['file_id'] - if document.file_id != DOCUMENT['file_id']: + if document.file_id != DOCUMENT["file_id"]: raise AssertionError def test_file_size(): if not isinstance(document.file_size, int): raise AssertionError - if document.file_size != DOCUMENT['file_size']: + if document.file_size != DOCUMENT["file_size"]: raise AssertionError diff --git a/tests/types/test_game.py b/tests/types/test_game.py index 484cc258..0e2b070f 100644 --- a/tests/types/test_game.py +++ b/tests/types/test_game.py @@ -16,21 +16,21 @@ def test_export(): def test_title(): if not isinstance(game.title, str): raise AssertionError - if game.title != GAME['title']: + if game.title != GAME["title"]: raise AssertionError def test_description(): if not isinstance(game.description, str): raise AssertionError - if game.description != GAME['description']: + if game.description != GAME["description"]: raise AssertionError def test_photo(): if not isinstance(game.photo, list): raise AssertionError - if len(game.photo) != len(GAME['photo']): + if len(game.photo) != len(GAME["photo"]): raise AssertionError if not all(map(lambda t: isinstance(t, types.PhotoSize), game.photo)): raise AssertionError diff --git a/tests/types/test_input_media.py b/tests/types/test_input_media.py index ca250a9e..3e22de94 100644 --- a/tests/types/test_input_media.py +++ b/tests/types/test_input_media.py @@ -2,19 +2,14 @@ from aiogram import types from .dataset import ANIMATION, AUDIO, DOCUMENT, PHOTO, VIDEO -WIDTH = 'width' -HEIGHT = 'height' +WIDTH = "width" +HEIGHT = "height" -input_media_audio = types.InputMediaAudio( - types.Audio(**AUDIO)) -input_media_animation = types.InputMediaAnimation( - types.Animation(**ANIMATION)) -input_media_document = types.InputMediaDocument( - types.Document(**DOCUMENT)) -input_media_video = types.InputMediaVideo( - types.Video(**VIDEO)) -input_media_photo = types.InputMediaPhoto( - types.PhotoSize(**PHOTO)) +input_media_audio = types.InputMediaAudio(types.Audio(**AUDIO)) +input_media_animation = types.InputMediaAnimation(types.Animation(**ANIMATION)) +input_media_document = types.InputMediaDocument(types.Document(**DOCUMENT)) +input_media_video = types.InputMediaVideo(types.Video(**VIDEO)) +input_media_photo = types.InputMediaPhoto(types.PhotoSize(**PHOTO)) def test_field_width(): diff --git a/tests/types/test_message.py b/tests/types/test_message.py index a668c204..044efa0c 100644 --- a/tests/types/test_message.py +++ b/tests/types/test_message.py @@ -17,37 +17,37 @@ def test_export(): def test_message_id(): # assert hash(message) == MESSAGE['message_id'] - if message.message_id != MESSAGE['message_id']: + if message.message_id != MESSAGE["message_id"]: raise AssertionError - if message['message_id'] != MESSAGE['message_id']: + if message["message_id"] != MESSAGE["message_id"]: raise AssertionError def test_from(): if not isinstance(message.from_user, types.User): raise AssertionError - if message.from_user != message['from']: + if message.from_user != message["from"]: raise AssertionError def test_chat(): if not isinstance(message.chat, types.Chat): raise AssertionError - if message.chat != message['chat']: + if message.chat != message["chat"]: raise AssertionError def test_date(): if not isinstance(message.date, datetime.datetime): raise AssertionError - if int(message.date.timestamp()) != MESSAGE['date']: + if int(message.date.timestamp()) != MESSAGE["date"]: raise AssertionError - if message.date != message['date']: + if message.date != message["date"]: raise AssertionError def test_text(): - if message.text != MESSAGE['text']: + if message.text != MESSAGE["text"]: raise AssertionError - if message['text'] != MESSAGE['text']: + if message["text"] != MESSAGE["text"]: raise AssertionError diff --git a/tests/types/test_photo.py b/tests/types/test_photo.py index f2ed4915..05540f6f 100644 --- a/tests/types/test_photo.py +++ b/tests/types/test_photo.py @@ -16,14 +16,14 @@ def test_export(): def test_file_id(): if not isinstance(photo.file_id, str): raise AssertionError - if photo.file_id != PHOTO['file_id']: + if photo.file_id != PHOTO["file_id"]: raise AssertionError def test_file_size(): if not isinstance(photo.file_size, int): raise AssertionError - if photo.file_size != PHOTO['file_size']: + if photo.file_size != PHOTO["file_size"]: raise AssertionError @@ -32,7 +32,7 @@ def test_size(): raise AssertionError if not isinstance(photo.height, int): raise AssertionError - if photo.width != PHOTO['width']: + if photo.width != PHOTO["width"]: raise AssertionError - if photo.height != PHOTO['height']: + if photo.height != PHOTO["height"]: raise AssertionError diff --git a/tests/types/test_update.py b/tests/types/test_update.py index d82d45fa..93982b4f 100644 --- a/tests/types/test_update.py +++ b/tests/types/test_update.py @@ -17,7 +17,7 @@ def test_update_id(): if not isinstance(update.update_id, int): raise AssertionError # assert hash(update) == UPDATE['update_id'] - if update.update_id != UPDATE['update_id']: + if update.update_id != UPDATE["update_id"]: raise AssertionError diff --git a/tests/types/test_user.py b/tests/types/test_user.py index c1ca2f88..5c764050 100644 --- a/tests/types/test_user.py +++ b/tests/types/test_user.py @@ -18,7 +18,7 @@ def test_export(): def test_id(): if not isinstance(user.id, int): raise AssertionError - if user.id != USER['id']: + if user.id != USER["id"]: raise AssertionError # assert hash(user) == USER['id'] @@ -26,23 +26,23 @@ def test_id(): def test_bot(): if not isinstance(user.is_bot, bool): raise AssertionError - if user.is_bot != USER['is_bot']: + if user.is_bot != USER["is_bot"]: raise AssertionError def test_name(): - if user.first_name != USER['first_name']: + if user.first_name != USER["first_name"]: raise AssertionError - if user.last_name != USER['last_name']: + if user.last_name != USER["last_name"]: raise AssertionError - if user.username != USER['username']: + if user.username != USER["username"]: raise AssertionError def test_language_code(): - if user.language_code != USER['language_code']: + if user.language_code != USER["language_code"]: raise AssertionError - if user.locale != Locale.parse(USER['language_code'], sep='-'): + if user.locale != Locale.parse(USER["language_code"], sep="-"): raise AssertionError @@ -54,9 +54,12 @@ def test_full_name(): def test_mention(): if user.mention != f"@{USER['username']}": raise AssertionError - if user.get_mention('foo', as_html=False) != f"[foo](tg://user?id={USER['id']})": + if user.get_mention("foo", as_html=False) != f"[foo](tg://user?id={USER['id']})": raise AssertionError - if user.get_mention('foo', as_html=True) != f"foo": + if ( + user.get_mention("foo", as_html=True) + != f"foo" + ): raise AssertionError