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: 4e472085-2e87-4f61-b7a1-ed208506962f/
This commit is contained in:
deepsource-autofix[bot] 2020-11-08 21:49:34 +00:00 committed by GitHub
parent dd50a9b13e
commit af4ceef153
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 1214 additions and 720 deletions

View file

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

View file

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

View file

@ -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:

View file

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

View file

@ -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:

View file

@ -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.

View file

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

View file

@ -2,9 +2,7 @@ from aiogram.dispatcher.filters.state import StatesGroup
class TestStatesGroup:
def test_all_childs(self):
class InnerState1(StatesGroup):
pass

View file

@ -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,

View file

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

View file

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

View file

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

View file

@ -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:

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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():

View file

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

View file

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

View file

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

View file

@ -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"<a href=\"tg://user?id={USER['id']}\">foo</a>":
if (
user.get_mention("foo", as_html=True)
!= f"<a href=\"tg://user?id={USER['id']}\">foo</a>"
):
raise AssertionError