Merge pull request #11 from muhammedfurkan/deepsource-fix-b44d2859

Remove assert statement from non-test files
This commit is contained in:
M.Furkan 2020-11-09 00:52:09 +03:00 committed by GitHub
commit deab57c6dc
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
29 changed files with 1738 additions and 930 deletions

File diff suppressed because it is too large Load diff

View file

@ -4,32 +4,40 @@ 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)
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}")
@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,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') == {}
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") != {}:
raise AssertionError
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'})
assert 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()
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

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,11 +18,13 @@ 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):
result = await bot.me
assert result == user
if result != user:
raise AssertionError
async def test_log_out(bot: Bot, event_loop):
@ -30,7 +32,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,273 +41,400 @@ 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):
""" sendMessage method test """
from .types.dataset import MESSAGE
msg = types.Message(**MESSAGE)
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):
""" 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)
assert result == msg
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
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)
assert result == msg
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
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)
assert result == msg
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
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)
assert result == msg
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
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)
assert result == msg
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
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)
assert result == msg
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
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)
assert result == msg
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
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)
assert len(result) == len(media)
assert result.pop().media_group_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
)
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):
""" 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)
assert result == msg
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
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)
assert result == msg
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
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)
assert isinstance(result, bool) and result is True
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
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)
assert result == msg
result = await bot.stop_message_live_location(
chat_id=msg.chat.id, message_id=msg.message_id
)
if result != msg:
raise AssertionError
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)
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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)
assert result == msg
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
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)
assert result == msg
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
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):
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):
""" 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)
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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):
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):
""" getFile method test """
from .types.dataset import FILE
file = types.File(**FILE)
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):
""" 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)
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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)
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):
""" restrictChatMember method test """
from .types.dataset import CHAT, USER
user = types.User(**USER)
chat = types.Chat(**CHAT)
@ -316,178 +446,240 @@ 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)
assert isinstance(result, bool)
assert result is True
can_send_other_messages=False,
),
until_date=123,
)
if not isinstance(result, bool):
raise AssertionError
if result is not True:
raise AssertionError
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)
assert isinstance(result, bool)
assert result is 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:
raise AssertionError
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):
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):
""" deleteChatPhoto method test """
from .types.dataset import CHAT
chat = types.Chat(**CHAT)
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):
""" 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')
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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')
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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)
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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):
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):
""" leaveChat method test """
from .types.dataset import CHAT
chat = types.Chat(**CHAT)
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):
""" getChat method test """
from .types.dataset import CHAT
chat = types.Chat(**CHAT)
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):
""" getChatAdministrators method test """
from .types.dataset import CHAT, CHAT_MEMBER
chat = types.Chat(**CHAT)
member = types.ChatMember(**CHAT_MEMBER)
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):
""" getChatMembersCount method test """
from .types.dataset import CHAT
chat = types.Chat(**CHAT)
count = 5
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):
""" getChatMember method test """
from .types.dataset import CHAT, CHAT_MEMBER
chat = types.Chat(**CHAT)
member = types.ChatMember(**CHAT_MEMBER)
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):
""" 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')
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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):
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):
""" 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')
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
async def test_set_my_commands(bot: Bot, event_loop):
@ -495,56 +687,76 @@ 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)
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):
""" 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):
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):
""" 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)
assert result == msg
result = await bot.edit_message_text(
text=msg.text, chat_id=msg.chat.id, message_id=msg.message_id
)
if result != msg:
raise AssertionError
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)
assert isinstance(result, bool)
assert result is True
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:
raise AssertionError
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')
assert isinstance(result, bool)
assert result is True
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:
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

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,15 +17,15 @@ 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):
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):

View file

@ -16,21 +16,33 @@ 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):
socks_ver, host, port, username, password = (
"socks5", "124.90.90.90", 9999, "login", "password"
"socks5",
"124.90.90.90",
9999,
"login",
"password",
)
bot = BaseBot(
@ -39,19 +51,27 @@ 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):
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:
@ -59,4 +79,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

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()
@ -23,9 +23,10 @@ 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'])
@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,94 +12,144 @@ 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)
assert res == {key: value}
if res != {key: value}:
raise AssertionError
@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",
),
),
)
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:
@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)
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):
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)
assert await filter.check(not_forwarded_message)
assert not await filter.check(forwarded_message)
if await filter.check(forwarded_message):
raise AssertionError
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
@ -16,4 +14,5 @@ class TestStatesGroup:
inner2 = InnerState2
form_childs = Form.all_childs
assert form_childs == (InnerState1, InnerState2)
if form_childs != (InnerState1, InnerState2):
raise AssertionError

View file

@ -38,16 +38,22 @@ 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",
[
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,
@ -63,4 +69,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

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)
@ -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))
@ -265,47 +266,54 @@ 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
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}')
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}')
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}')
message = Message(text=f"{self.START} {self.GOOD}")
result = await test_filter.check(message)
assert isinstance(result, dict)
match = result.get('deep_link')
assert isinstance(match, Match)
if not isinstance(result, dict):
raise AssertionError
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)
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}')
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

View file

@ -14,90 +14,127 @@ 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():
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 == (
'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')
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",
):
raise AssertionError
if MyGroup.MySubGroup.NewGroup.states_names != (
"MyGroup.MySubGroup.NewGroup:spam",
"MyGroup.MySubGroup.NewGroup:spam_state",
):
raise AssertionError
assert 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')
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",
):
raise AssertionError
assert 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')
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",
):
raise AssertionError
assert MyGroup.MySubGroup.NewGroup.all_states_names == (
'MyGroup.MySubGroup.NewGroup:spam',
'MyGroup.MySubGroup.NewGroup:spam_state')
if MyGroup.MySubGroup.NewGroup.all_states_names != (
"MyGroup.MySubGroup.NewGroup:spam",
"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()

View file

@ -3,44 +3,49 @@ 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)
assert res == data['hash']
if res != data["hash"]:
raise AssertionError
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
data.pop("username")
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
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,15 +40,17 @@ 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:
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 +58,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 +76,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

View file

@ -4,11 +4,21 @@ 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)
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

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,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 +19,5 @@ class TestOrderedHelper:
C = ListItem()
B = ListItem()
assert Helper.all() == ['A', 'D', 'C', 'B']
if Helper.all() != ["A", "D", "C", "B"]:
raise AssertionError

View file

@ -4,8 +4,10 @@ from aiogram.utils import markdown
class TestMarkdownEscape:
def test_equality_sign_is_escaped(self):
assert markdown.escape_md(r"e = mc2") == r"e \= mc2"
def test_equality_sign_is_escaped(self):
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\\\."
def test_pre_escaped(self):
if markdown.escape_md(r"hello\.") != r"hello\\\.":
raise AssertionError

View file

@ -3,23 +3,35 @@ from aiogram.utils import text_decorations
class TestTextDecorations:
def test_unparse_entities_normal_text(self):
assert 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*"
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
"""
assert 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*"
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

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

View file

@ -7,56 +7,88 @@ 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

View file

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

View file

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

View file

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

View file

@ -2,40 +2,45 @@ 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():
"""
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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,41 +9,60 @@ 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"<a href=\"tg://user?id={USER['id']}\">foo</a>"
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"<a href=\"tg://user?id={USER['id']}\">foo</a>"
):
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