Clean obsolete code and change configs

This commit is contained in:
jrootjunior 2019-11-15 12:44:24 +02:00
parent d09b72ce6e
commit 65815e509f
58 changed files with 78 additions and 3959 deletions

View file

@ -1,42 +0,0 @@
import aresponses
from aiogram import Bot
TOKEN = "123456789:AABBCCDDEEFFaabbccddeeff-1234567890"
class FakeTelegram(aresponses.ResponsesMockServer):
def __init__(self, message_dict, bot=None, **kwargs):
super().__init__(**kwargs)
self._body, self._headers = self.parse_data(message_dict)
if isinstance(bot, Bot):
Bot.set_current(bot)
async def __aenter__(self):
await super().__aenter__()
_response = self.Response(text=self._body, headers=self._headers, status=200, reason="OK")
self.add(self.ANY, response=_response)
async def __aexit__(self, exc_type, exc_val, exc_tb):
if hasattr(self, "monkeypatch"):
self.monkeypatch.undo()
await super().__aexit__(exc_type, exc_val, exc_tb)
@staticmethod
def parse_data(message_dict):
import json
_body = '{"ok":true,"result":' + json.dumps(message_dict) + "}"
_headers = {
"Server": "nginx/1.12.2",
"Date": "Tue, 03 Apr 2018 16:59:54 GMT",
"Content-Type": "application/json",
"Content-Length": str(len(_body)),
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Expose-Headers": "Content-Length,Content-Type,Date,Server,Connection",
"Strict-Transport-Security": "max-age=31536000; includeSubdomains",
}
return _body, _headers

View file

@ -1 +0,0 @@
# pytest_plugins = "pytest_asyncio.plugin"

View file

@ -1,681 +0,0 @@
import aresponses
import pytest
from aiogram import Bot, types
TOKEN = "123456789:AABBCCDDEEFFaabbccddeeff-1234567890"
class FakeTelegram(aresponses.ResponsesMockServer):
def __init__(self, message_dict, **kwargs):
super().__init__(**kwargs)
self._body, self._headers = self.parse_data(message_dict)
async def __aenter__(self):
await super().__aenter__()
_response = self.Response(text=self._body, headers=self._headers, status=200, reason="OK")
self.add(self.ANY, response=_response)
@staticmethod
def parse_data(message_dict):
import json
_body = '{"ok":true,"result":' + json.dumps(message_dict) + "}"
_headers = {
"Server": "nginx/1.12.2",
"Date": "Tue, 03 Apr 2018 16:59:54 GMT",
"Content-Type": "application/json",
"Content-Length": str(len(_body)),
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Expose-Headers": "Content-Length,Content-Type,Date,Server,Connection",
"Strict-Transport-Security": "max-age=31536000; includeSubdomains",
}
return _body, _headers
@pytest.yield_fixture()
@pytest.mark.asyncio
async def bot(event_loop):
""" Bot fixture """
_bot = Bot(TOKEN, loop=event_loop, parse_mode=types.ParseMode.MARKDOWN)
yield _bot
await _bot.close()
@pytest.mark.asyncio
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_dict=USER, loop=event_loop):
result = await bot.me
assert result == user
@pytest.mark.asyncio
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_dict=MESSAGE, loop=event_loop):
result = await bot.send_message(chat_id=msg.chat.id, text=msg.text)
assert result == msg
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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),
]
async with FakeTelegram(
message_dict=[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
@pytest.mark.asyncio
async def test_send_location(bot: Bot, event_loop):
""" sendLocation method test """
from .types.dataset import MESSAGE_WITH_LOCATION, LOCATION
msg = types.Message(**MESSAGE_WITH_LOCATION)
location = types.Location(**LOCATION)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
async def test_edit_message_live_location_by_bot(bot: Bot, event_loop):
""" editMessageLiveLocation method test """
from .types.dataset import MESSAGE_WITH_LOCATION, LOCATION
msg = types.Message(**MESSAGE_WITH_LOCATION)
location = types.Location(**LOCATION)
# editing bot message
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
async def test_edit_message_live_location_by_user(bot: Bot, event_loop):
""" editMessageLiveLocation method test """
from .types.dataset import MESSAGE_WITH_LOCATION, LOCATION
msg = types.Message(**MESSAGE_WITH_LOCATION)
location = types.Location(**LOCATION)
# editing user's message
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
async def test_send_venue(bot: Bot, event_loop):
""" sendVenue method test """
from .types.dataset import MESSAGE_WITH_VENUE, VENUE, LOCATION
msg = types.Message(**MESSAGE_WITH_VENUE)
location = types.Location(**LOCATION)
venue = types.Venue(**VENUE)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
async def test_send_contact(bot: Bot, event_loop):
""" sendContact method test """
from .types.dataset import MESSAGE_WITH_CONTACT, CONTACT
msg = types.Message(**MESSAGE_WITH_CONTACT)
contact = types.Contact(**CONTACT)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
async def test_get_user_profile_photo(bot: Bot, event_loop):
""" getUserProfilePhotos method test """
from .types.dataset import USER_PROFILE_PHOTOS, USER
user = types.User(**USER)
async with FakeTelegram(message_dict=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)
@pytest.mark.asyncio
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_dict=FILE, loop=event_loop):
result = await bot.get_file(file_id=file.file_id)
assert isinstance(result, types.File)
@pytest.mark.asyncio
async def test_kick_chat_member(bot: Bot, event_loop):
""" kickChatMember method test """
from .types.dataset import USER, CHAT
user = types.User(**USER)
chat = types.Chat(**CHAT)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
async def test_unban_chat_member(bot: Bot, event_loop):
""" unbanChatMember method test """
from .types.dataset import USER, CHAT
user = types.User(**USER)
chat = types.Chat(**CHAT)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
async def test_restrict_chat_member(bot: Bot, event_loop):
""" restrictChatMember method test """
from .types.dataset import USER, CHAT
user = types.User(**USER)
chat = types.Chat(**CHAT)
async with FakeTelegram(message_dict=True, loop=event_loop):
result = await bot.restrict_chat_member(
chat_id=chat.id,
user_id=user.id,
permissions=types.ChatPermissions(
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
@pytest.mark.asyncio
async def test_promote_chat_member(bot: Bot, event_loop):
""" promoteChatMember method test """
from .types.dataset import USER, CHAT
user = types.User(**USER)
chat = types.Chat(**CHAT)
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
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_dict=INVITE_LINK, loop=event_loop):
result = await bot.export_chat_invite_link(chat_id=chat.id)
assert result == INVITE_LINK
@pytest.mark.asyncio
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_dict=True, loop=event_loop):
result = await bot.delete_chat_photo(chat_id=chat.id)
assert isinstance(result, bool)
assert result is True
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=True, loop=event_loop):
result = await bot.unpin_chat_message(chat_id=chat.id)
assert isinstance(result, bool)
assert result is True
@pytest.mark.asyncio
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_dict=True, loop=event_loop):
result = await bot.leave_chat(chat_id=chat.id)
assert isinstance(result, bool)
assert result is True
@pytest.mark.asyncio
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_dict=CHAT, loop=event_loop):
result = await bot.get_chat(chat_id=chat.id)
assert result == chat
@pytest.mark.asyncio
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_dict=[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
@pytest.mark.asyncio
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_dict=count, loop=event_loop):
result = await bot.get_chat_members_count(chat_id=chat.id)
assert result == count
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=True, loop=event_loop):
result = await bot.delete_chat_sticker_set(chat_id=chat.id)
assert isinstance(result, bool)
assert result is True
@pytest.mark.asyncio
async def test_answer_callback_query(bot: Bot, event_loop):
""" answerCallbackQuery method test """
async with FakeTelegram(message_dict=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
@pytest.mark.asyncio
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_dict=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
@pytest.mark.asyncio
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_dict=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

View file

@ -1,16 +0,0 @@
import pytest
from aiogram.bot.api import check_token
from aiogram.utils.exceptions import ValidationError
VALID_TOKEN = "123456789:AABBCCDDEEFFaabbccddeeff-1234567890"
INVALID_TOKEN = "123456789:AABBCCDDEEFFaabbccddeeff 123456789" # Space in token and wrong length
class Test_check_token:
def test_valid(self):
assert check_token(VALID_TOKEN) is True
def test_invalid_token(self):
with pytest.raises(ValidationError):
check_token(INVALID_TOKEN)

View file

@ -1,34 +0,0 @@
import pytest
from aiogram import Bot, Dispatcher
pytestmark = pytest.mark.asyncio
@pytest.yield_fixture()
async def bot(event_loop):
""" Bot fixture """
_bot = Bot(token="123456789:AABBCCDDEEFFaabbccddeeff-1234567890", loop=event_loop)
yield _bot
await _bot.close()
class TestDispatcherInit:
async def test_successful_init(self, bot):
"""
Success __init__ case
:param bot: bot instance
:type bot: Bot
"""
dp = Dispatcher(bot=bot)
assert isinstance(dp, Dispatcher)
@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.
:return: TypeError with reason
"""
with pytest.raises(TypeError):
_ = Dispatcher(bot=bot_instance)

View file

@ -1,20 +0,0 @@
import pytest
from aiogram.dispatcher.filters.builtin import Text
class TestText:
@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"
config = {param: value}
res = Text.validate(config)
assert res == {key: value}

View file

@ -1,17 +0,0 @@
from aiogram.dispatcher.filters.state import StatesGroup
class TestStatesGroup:
def test_all_childs(self):
class InnerState1(StatesGroup):
pass
class InnerState2(InnerState1):
pass
class Form(StatesGroup):
inner1 = InnerState1
inner2 = InnerState2
form_childs = Form.all_childs
assert form_childs == (InnerState1, InnerState2)

View file

@ -1,264 +0,0 @@
import pytest
from aiogram.dispatcher.filters import Text
from aiogram.types import CallbackQuery, InlineQuery, Message, Poll
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"),
]
class TestTextFilter:
async def _run_check(self, check, test_text):
assert await check(Message(text=test_text))
assert await check(CallbackQuery(data=test_text))
assert await check(InlineQuery(query=test_text))
assert await check(Poll(question=test_text))
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_prefix = test_prefix.lower()
_test_text = test_text.lower()
else:
_test_prefix = test_prefix
_test_text = test_text
return result is _test_text.startswith(_test_prefix)
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_prefix_list = map(str.lower, test_prefix_list)
_test_text = test_text.lower()
else:
_test_prefix_list = test_prefix_list
_test_text = test_text
return result is any(map(_test_text.startswith, _test_prefix_list))
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_postfix = test_postfix.lower()
_test_text = test_text.lower()
else:
_test_postfix = test_postfix
_test_text = test_text
return result is _test_text.endswith(_test_postfix)
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_postfix_list = map(str.lower, test_postfix_list)
_test_text = test_text.lower()
else:
_test_postfix_list = test_postfix_list
_test_text = test_text
return result is any(map(_test_text.endswith, _test_postfix_list))
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_string = test_string.lower()
_test_text = test_text.lower()
else:
_test_string = test_string
_test_text = test_text
return result is (_test_string in _test_text)
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_filter_list = list(map(str.lower, test_filter_list))
_test_text = test_text.lower()
else:
_test_filter_list = test_filter_list
_test_text = test_text
return result is all(map(_test_text.__contains__, _test_filter_list))
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_filter_text = test_filter_text.lower()
_test_text = test_text.lower()
else:
_test_filter_text = test_filter_text
_test_text = test_text
return result is (_test_text == _test_filter_text)
await self._run_check(check, test_text)
@pytest.mark.asyncio
@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)
async def check(obj):
result = await test_filter.check(obj)
if ignore_case:
_test_filter_list = list(map(str.lower, test_filter_list))
_test_text = test_text.lower()
else:
_test_filter_list = test_filter_list
_test_text = test_text
assert result is (_test_text in _test_filter_list)
await check(Message(text=test_text))
await check(CallbackQuery(data=test_text))
await check(InlineQuery(query=test_text))
await check(Poll(question=test_text))

View file

@ -1,49 +0,0 @@
from asyncio import BaseEventLoop
import pytest
from aiogram import Bot, types
from . import TOKEN, FakeTelegram
pytestmark = pytest.mark.asyncio
@pytest.yield_fixture()
async def bot(event_loop):
""" Bot fixture """
_bot = Bot(TOKEN, loop=event_loop, parse_mode=types.ParseMode.HTML)
yield _bot
await _bot.close()
@pytest.yield_fixture()
async def message(bot, event_loop):
"""
Message fixture
:param bot: Telegram bot fixture
:type bot: Bot
:param event_loop: asyncio event loop
:type event_loop: BaseEventLoop
"""
from .types.dataset import MESSAGE
msg = types.Message(**MESSAGE)
async with FakeTelegram(message_dict=MESSAGE, loop=event_loop):
_message = await bot.send_message(chat_id=msg.chat.id, text=msg.text)
yield _message
class TestMiscCases:
async def test_calling_bot_not_from_context(self, message):
"""
Calling any helper method without bot instance in context.
:param message: message fixture
:type message: types.Message
:return: RuntimeError with reason and help
"""
with pytest.raises(RuntimeError):
await message.edit_text("test_calling_bot_not_from_context")

10
tests/test_nothing.py Normal file
View file

@ -0,0 +1,10 @@
import asyncio
import pytest
class TestNothing:
@pytest.mark.asyncio
async def test_nothing(self):
result = await asyncio.sleep(1, result=42)
assert result == 42

View file

@ -1,114 +0,0 @@
import pytest
from aiogram.dispatcher.filters.state import State, StatesGroup, any_state, default_state
class MyGroup(StatesGroup):
state = State()
state_1 = State()
state_2 = State()
class MySubGroup(StatesGroup):
sub_state = State()
sub_state_1 = State()
sub_state_2 = State()
in_custom_group = State(group_name="custom_group")
class NewGroup(StatesGroup):
spam = State()
renamed_state = State(state="spam_state")
alone_state = State("alone")
alone_in_group = State("alone", group_name="home")
def test_default_state():
assert default_state.state is None
def test_any_state():
assert any_state.state == "*"
def test_alone_state():
assert alone_state.state == "@:alone"
assert alone_in_group.state == "home:alone"
def test_group_names():
assert MyGroup.__group_name__ == "MyGroup"
assert MyGroup.__full_group_name__ == "MyGroup"
assert MyGroup.MySubGroup.__group_name__ == "MySubGroup"
assert MyGroup.MySubGroup.__full_group_name__ == "MyGroup.MySubGroup"
assert MyGroup.MySubGroup.NewGroup.__group_name__ == "NewGroup"
assert MyGroup.MySubGroup.NewGroup.__full_group_name__ == "MyGroup.MySubGroup.NewGroup"
def test_custom_group_in_group():
assert MyGroup.MySubGroup.in_custom_group.state == "custom_group:in_custom_group"
def test_custom_state_name_in_group():
assert (
MyGroup.MySubGroup.NewGroup.renamed_state.state == "MyGroup.MySubGroup.NewGroup:spam_state"
)
def test_group_states_names():
assert len(MyGroup.states) == 3
assert len(MyGroup.all_states) == 9
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",
)
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",
)
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",
)
assert MyGroup.MySubGroup.NewGroup.all_states_names == (
"MyGroup.MySubGroup.NewGroup:spam",
"MyGroup.MySubGroup.NewGroup:spam_state",
)
def test_root_element():
root = MyGroup.MySubGroup.NewGroup.spam.get_root()
assert issubclass(root, StatesGroup)
assert root == MyGroup
assert root == MyGroup.state.get_root()
assert root == MyGroup.MySubGroup.get_root()
with pytest.raises(RuntimeError):
any_state.get_root()

View file

@ -1,45 +0,0 @@
import pytest
from aiogram.utils.auth_widget import check_integrity, check_token, generate_hash
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",
}
def test_generate_hash(data):
res = generate_hash(data, TOKEN)
assert res == data["hash"]
class Test_check_token:
"""
This case gonna be deleted
"""
def test_ok(self, data):
assert check_token(data, TOKEN) is True
def test_fail(self, data):
data.pop("username")
assert check_token(data, TOKEN) is False
class Test_check_integrity:
def test_ok(self, data):
assert check_integrity(TOKEN, data) is True
def test_fail(self, data):
data.pop("username")
assert check_integrity(TOKEN, data) is False

View file

@ -1,21 +0,0 @@
from aiogram.utils.helper import Item, ListItem, OrderedHelper
class TestOrderedHelper:
def test_items_are_ordered(self):
class Helper(OrderedHelper):
A = Item()
D = Item()
C = Item()
B = Item()
assert Helper.all() == ["A", "D", "C", "B"]
def test_list_items_are_ordered(self):
class Helper(OrderedHelper):
A = ListItem()
D = ListItem()
C = ListItem()
B = ListItem()
assert Helper.all() == ["A", "D", "C", "B"]

View file

@ -1,402 +0,0 @@
""""
Dict data set for Telegram message types
"""
USER = {
"id": 12345678,
"is_bot": False,
"first_name": "FirstName",
"last_name": "LastName",
"username": "username",
"language_code": "ru",
}
CHAT = {
"id": 12345678,
"first_name": "FirstName",
"last_name": "LastName",
"username": "username",
"type": "private",
}
PHOTO = {
"file_id": "AgADBAADFak0G88YZAf8OAug7bHyS9x2ZxkABHVfpJywcloRAAGAAQABAg",
"file_size": 1101,
"width": 90,
"height": 51,
}
AUDIO = {
"duration": 236,
"mime_type": "audio/mpeg3",
"title": "The Best Song",
"performer": "The Best Singer",
"file_id": "CQADAgADbQEAAsnrIUpNoRRNsH7_hAI",
"file_size": 9507774,
}
CHAT_MEMBER = {
"user": USER,
"status": "administrator",
"can_be_edited": False,
"can_change_info": True,
"can_delete_messages": True,
"can_invite_users": True,
"can_restrict_members": True,
"can_pin_messages": True,
"can_promote_members": False,
}
CONTACT = {"phone_number": "88005553535", "first_name": "John", "last_name": "Smith"}
DOCUMENT = {
"file_name": "test.docx",
"mime_type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"file_id": "BQADAgADpgADy_JxS66XQTBRHFleAg",
"file_size": 21331,
}
ANIMATION = {
"file_name": "a9b0e0ca537aa344338f80978f0896b7.gif.mp4",
"mime_type": "video/mp4",
"thumb": PHOTO,
"file_id": "CgADBAAD4DUAAoceZAe2WiE9y0crrAI",
"file_size": 65837,
}
ENTITY_BOLD = {"offset": 5, "length": 2, "type": "bold"}
ENTITY_ITALIC = {"offset": 8, "length": 1, "type": "italic"}
ENTITY_LINK = {"offset": 10, "length": 6, "type": "text_link", "url": "http://google.com/"}
ENTITY_CODE = {"offset": 17, "length": 7, "type": "code"}
ENTITY_PRE = {"offset": 30, "length": 4, "type": "pre"}
ENTITY_MENTION = {"offset": 47, "length": 9, "type": "mention"}
GAME = {
"title": "Karate Kido",
"description": "No trees were harmed in the making of this game :)",
"photo": [PHOTO, PHOTO, PHOTO],
"animation": ANIMATION,
}
INVOICE = {
"title": "Working Time Machine",
"description": "Want to visit your great-great-great-grandparents? "
"Make a fortune at the races? "
"Shake hands with Hammurabi and take a stroll in the Hanging Gardens? "
"Order our Working Time Machine today!",
"start_parameter": "time-machine-example",
"currency": "USD",
"total_amount": 6250,
}
LOCATION = {"latitude": 50.693416, "longitude": 30.624605}
VENUE = {
"location": LOCATION,
"title": "Venue Name",
"address": "Venue Address",
"foursquare_id": "4e6f2cec483bad563d150f98",
}
SHIPPING_ADDRESS = {
"country_code": "US",
"state": "State",
"city": "DefaultCity",
"street_line1": "Central",
"street_line2": "Middle",
"post_code": "424242",
}
STICKER = {
"width": 512,
"height": 512,
"emoji": "🛠",
"set_name": "StickerSet",
"thumb": {
"file_id": "AAbbCCddEEffGGhh1234567890",
"file_size": 1234,
"width": 128,
"height": 128,
},
"file_id": "AAbbCCddEEffGGhh1234567890",
"file_size": 12345,
}
SUCCESSFUL_PAYMENT = {
"currency": "USD",
"total_amount": 6250,
"invoice_payload": "HAPPY FRIDAYS COUPON",
"telegram_payment_charge_id": "_",
"provider_payment_charge_id": "12345678901234_test",
}
VIDEO = {
"duration": 52,
"width": 853,
"height": 480,
"mime_type": "video/quicktime",
"thumb": PHOTO,
"file_id": "BAADAgpAADdawy_JxS72kRvV3cortAg",
"file_size": 10099782,
}
VIDEO_NOTE = {
"duration": 4,
"length": 240,
"thumb": PHOTO,
"file_id": "AbCdEfGhIjKlMnOpQrStUvWxYz",
"file_size": 186562,
}
VOICE = {
"duration": 1,
"mime_type": "audio/ogg",
"file_id": "AwADawAgADADy_JxS2gopIVIIxlhAg",
"file_size": 4321,
}
CALLBACK_QUERY = {}
CHANNEL_POST = {}
CHOSEN_INLINE_RESULT = {}
EDITED_CHANNEL_POST = {}
EDITED_MESSAGE = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508825372,
"edit_date": 1508825379,
"text": "hi there (edited)",
}
FORWARDED_MESSAGE = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1522828529,
"forward_from_chat": CHAT,
"forward_from_message_id": 123,
"forward_date": 1522749037,
"text": "Forwarded text with entities from public channel ",
"entities": [
ENTITY_BOLD,
ENTITY_CODE,
ENTITY_ITALIC,
ENTITY_LINK,
ENTITY_LINK,
ENTITY_MENTION,
ENTITY_PRE,
],
}
INLINE_QUERY = {}
MESSAGE = {
"message_id": 11223,
"from": USER,
"chat": CHAT,
"date": 1508709711,
"text": "Hi, world!",
}
MESSAGE_WITH_AUDIO = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508739776,
"audio": AUDIO,
"caption": "This is my favourite song",
}
MESSAGE_WITH_AUTHOR_SIGNATURE = {}
MESSAGE_WITH_CHANNEL_CHAT_CREATED = {}
MESSAGE_WITH_CONTACT = {
"message_id": 56006,
"from": USER,
"chat": CHAT,
"date": 1522850298,
"contact": CONTACT,
}
MESSAGE_WITH_DELETE_CHAT_PHOTO = {}
MESSAGE_WITH_DOCUMENT = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508768012,
"document": DOCUMENT,
"caption": "Read my document",
}
MESSAGE_WITH_EDIT_DATE = {}
MESSAGE_WITH_ENTITIES = {}
MESSAGE_WITH_GAME = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508824810,
"game": GAME,
}
MESSAGE_WITH_GROUP_CHAT_CREATED = {}
MESSAGE_WITH_INVOICE = {
"message_id": 9772,
"from": USER,
"chat": CHAT,
"date": 1508761719,
"invoice": INVOICE,
}
MESSAGE_WITH_LEFT_CHAT_MEMBER = {}
MESSAGE_WITH_LOCATION = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508755473,
"location": LOCATION,
}
MESSAGE_WITH_MIGRATE_TO_CHAT_ID = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1526943253,
"migrate_to_chat_id": -1234567890987,
}
MESSAGE_WITH_MIGRATE_FROM_CHAT_ID = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1526943253,
"migrate_from_chat_id": -123456789,
}
MESSAGE_WITH_NEW_CHAT_MEMBERS = {}
MESSAGE_WITH_NEW_CHAT_PHOTO = {}
MESSAGE_WITH_NEW_CHAT_TITLE = {}
MESSAGE_WITH_PHOTO = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508825154,
"photo": [PHOTO, PHOTO, PHOTO, PHOTO],
"caption": "photo description",
}
MESSAGE_WITH_MEDIA_GROUP = {
"message_id": 55966,
"from": USER,
"chat": CHAT,
"date": 1522843665,
"media_group_id": "12182749320567362",
"photo": [PHOTO, PHOTO, PHOTO, PHOTO],
}
MESSAGE_WITH_PINNED_MESSAGE = {}
MESSAGE_WITH_REPLY_TO_MESSAGE = {}
MESSAGE_WITH_STICKER = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508771450,
"sticker": STICKER,
}
MESSAGE_WITH_SUCCESSFUL_PAYMENT = {
"message_id": 9768,
"from": USER,
"chat": CHAT,
"date": 1508761169,
"successful_payment": SUCCESSFUL_PAYMENT,
}
MESSAGE_WITH_SUPERGROUP_CHAT_CREATED = {}
MESSAGE_WITH_VENUE = {
"message_id": 56004,
"from": USER,
"chat": CHAT,
"date": 1522849819,
"location": LOCATION,
"venue": VENUE,
}
MESSAGE_WITH_VIDEO = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508756494,
"video": VIDEO,
"caption": "description",
}
MESSAGE_WITH_VIDEO_NOTE = {
"message_id": 55934,
"from": USER,
"chat": CHAT,
"date": 1522835890,
"video_note": VIDEO_NOTE,
}
MESSAGE_WITH_VOICE = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508768403,
"voice": VOICE,
}
PRE_CHECKOUT_QUERY = {
"id": "262181558630368727",
"from": USER,
"currency": "USD",
"total_amount": 6250,
"invoice_payload": "HAPPY FRIDAYS COUPON",
}
REPLY_MESSAGE = {
"message_id": 12345,
"from": USER,
"chat": CHAT,
"date": 1508751866,
"reply_to_message": MESSAGE,
"text": "Reply to quoted message",
}
SHIPPING_QUERY = {
"id": "262181558684397422",
"from": USER,
"invoice_payload": "HAPPY FRIDAYS COUPON",
"shipping_address": SHIPPING_ADDRESS,
}
USER_PROFILE_PHOTOS = {"total_count": 1, "photos": [[PHOTO, PHOTO, PHOTO]]}
FILE = {"file_id": "XXXYYYZZZ", "file_size": 5254, "file_path": "voice/file_8"}
INVITE_LINK = "https://t.me/joinchat/AbCdEfjKILDADwdd123"
UPDATE = {"update_id": 123456789, "message": MESSAGE}
WEBHOOK_INFO = {"url": "", "has_custom_certificate": False, "pending_update_count": 0}

View file

@ -1,40 +0,0 @@
from aiogram import types
from .dataset import ANIMATION
animation = types.Animation(**ANIMATION)
def test_export():
exported = animation.to_python()
assert isinstance(exported, dict)
assert exported == ANIMATION
def test_file_name():
assert isinstance(animation.file_name, str)
assert animation.file_name == ANIMATION["file_name"]
def test_mime_type():
assert isinstance(animation.mime_type, str)
assert animation.mime_type == ANIMATION["mime_type"]
def test_file_id():
assert isinstance(animation.file_id, str)
# assert hash(animation) == ANIMATION['file_id']
assert animation.file_id == ANIMATION["file_id"]
def test_file_size():
assert isinstance(animation.file_size, int)
assert animation.file_size == ANIMATION["file_size"]
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"]

View file

@ -1,63 +0,0 @@
from aiogram import types
from .dataset import CHAT
chat = types.Chat(**CHAT)
def test_export():
exported = chat.to_python()
assert isinstance(exported, dict)
assert exported == CHAT
def test_id():
assert isinstance(chat.id, int)
assert chat.id == CHAT["id"]
# assert hash(chat) == CHAT['id']
def test_name():
assert isinstance(chat.first_name, str)
assert chat.first_name == CHAT["first_name"]
assert isinstance(chat.last_name, str)
assert chat.last_name == CHAT["last_name"]
assert isinstance(chat.username, str)
assert chat.username == CHAT["username"]
def test_type():
assert isinstance(chat.type, str)
assert chat.type == CHAT["type"]
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"
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)
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"

View file

@ -1,78 +0,0 @@
from aiogram import types
from .dataset import CHAT_MEMBER
chat_member = types.ChatMember(**CHAT_MEMBER)
def test_export():
exported = chat_member.to_python()
assert isinstance(exported, dict)
assert exported == CHAT_MEMBER
def test_user():
assert isinstance(chat_member.user, types.User)
def test_status():
assert isinstance(chat_member.status, str)
assert chat_member.status == CHAT_MEMBER["status"]
def test_privileges():
assert isinstance(chat_member.can_be_edited, bool)
assert chat_member.can_be_edited == CHAT_MEMBER["can_be_edited"]
assert isinstance(chat_member.can_change_info, bool)
assert chat_member.can_change_info == CHAT_MEMBER["can_change_info"]
assert isinstance(chat_member.can_delete_messages, bool)
assert chat_member.can_delete_messages == CHAT_MEMBER["can_delete_messages"]
assert isinstance(chat_member.can_invite_users, bool)
assert chat_member.can_invite_users == CHAT_MEMBER["can_invite_users"]
assert isinstance(chat_member.can_restrict_members, bool)
assert chat_member.can_restrict_members == CHAT_MEMBER["can_restrict_members"]
assert isinstance(chat_member.can_pin_messages, bool)
assert chat_member.can_pin_messages == CHAT_MEMBER["can_pin_messages"]
assert isinstance(chat_member.can_promote_members, bool)
assert chat_member.can_promote_members == CHAT_MEMBER["can_promote_members"]
def test_int():
assert int(chat_member) == chat_member.user.id
assert isinstance(int(chat_member), int)
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"
def test_chat_member_status_filters():
assert types.ChatMemberStatus.is_chat_admin(chat_member.status)
assert types.ChatMemberStatus.is_chat_member(chat_member.status)
assert types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.CREATOR)
assert types.ChatMemberStatus.is_chat_admin(types.ChatMemberStatus.ADMINISTRATOR)
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)
assert not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.LEFT)
assert not types.ChatMemberStatus.is_chat_member(types.ChatMemberStatus.KICKED)
def test_chat_member_filters():
assert chat_member.is_chat_admin()
assert chat_member.is_chat_member()

View file

@ -1,36 +0,0 @@
from aiogram import types
from .dataset import DOCUMENT
document = types.Document(**DOCUMENT)
def test_export():
exported = document.to_python()
assert isinstance(exported, dict)
assert exported == DOCUMENT
def test_file_name():
assert isinstance(document.file_name, str)
assert document.file_name == DOCUMENT["file_name"]
def test_mime_type():
assert isinstance(document.mime_type, str)
assert document.mime_type == DOCUMENT["mime_type"]
def test_file_id():
assert isinstance(document.file_id, str)
# assert hash(document) == DOCUMENT['file_id']
assert document.file_id == DOCUMENT["file_id"]
def test_file_size():
assert isinstance(document.file_size, int)
assert document.file_size == DOCUMENT["file_size"]
def test_thumb():
assert document.thumb is None

View file

@ -1,31 +0,0 @@
from aiogram import types
from .dataset import GAME
game = types.Game(**GAME)
def test_export():
exported = game.to_python()
assert isinstance(exported, dict)
assert exported == GAME
def test_title():
assert isinstance(game.title, str)
assert game.title == GAME["title"]
def test_description():
assert isinstance(game.description, str)
assert game.description == GAME["description"]
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))
def test_animation():
assert isinstance(game.animation, types.Animation)

View file

@ -1,40 +0,0 @@
import datetime
from aiogram import types
from .dataset import MESSAGE
message = types.Message(**MESSAGE)
def test_export():
exported_chat = message.to_python()
assert isinstance(exported_chat, dict)
assert exported_chat == MESSAGE
def test_message_id():
# assert hash(message) == MESSAGE['message_id']
assert message.message_id == MESSAGE["message_id"]
assert message["message_id"] == MESSAGE["message_id"]
def test_from():
assert isinstance(message.from_user, types.User)
assert message.from_user == message["from"]
def test_chat():
assert isinstance(message.chat, types.Chat)
assert message.chat == message["chat"]
def test_date():
assert isinstance(message.date, datetime.datetime)
assert int(message.date.timestamp()) == MESSAGE["date"]
assert message.date == message["date"]
def test_text():
assert message.text == MESSAGE["text"]
assert message["text"] == MESSAGE["text"]

View file

@ -1,28 +0,0 @@
from aiogram import types
from .dataset import PHOTO
photo = types.PhotoSize(**PHOTO)
def test_export():
exported = photo.to_python()
assert isinstance(exported, dict)
assert exported == PHOTO
def test_file_id():
assert isinstance(photo.file_id, str)
assert photo.file_id == PHOTO["file_id"]
def test_file_size():
assert isinstance(photo.file_size, int)
assert photo.file_size == PHOTO["file_size"]
def test_size():
assert isinstance(photo.width, int)
assert isinstance(photo.height, int)
assert photo.width == PHOTO["width"]
assert photo.height == PHOTO["height"]

View file

@ -1,21 +0,0 @@
from aiogram import types
from .dataset import UPDATE
update = types.Update(**UPDATE)
def test_export():
exported = update.to_python()
assert isinstance(exported, dict)
assert exported == UPDATE
def test_update_id():
assert isinstance(update.update_id, int)
# assert hash(update) == UPDATE['update_id']
assert update.update_id == UPDATE["update_id"]
def test_message():
assert isinstance(update.message, types.Message)

View file

@ -1,51 +0,0 @@
from babel import Locale
from aiogram import types
from .dataset import USER
user = types.User(**USER)
def test_export():
exported = user.to_python()
assert isinstance(exported, dict)
assert exported == USER
def test_id():
assert isinstance(user.id, int)
assert user.id == USER["id"]
# assert hash(user) == USER['id']
def test_bot():
assert isinstance(user.is_bot, bool)
assert user.is_bot == USER["is_bot"]
def test_name():
assert user.first_name == USER["first_name"]
assert user.last_name == USER["last_name"]
assert user.username == USER["username"]
def test_language_code():
assert user.language_code == USER["language_code"]
assert user.locale == Locale.parse(USER["language_code"], sep="-")
def test_full_name():
assert user.full_name == f"{USER['first_name']} {USER['last_name']}"
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>"
)
def test_url():
assert user.url == f"tg://user?id={USER['id']}"