diff --git a/aiogram/types/base.py b/aiogram/types/base.py index 8125a37d..4514e956 100644 --- a/aiogram/types/base.py +++ b/aiogram/types/base.py @@ -142,7 +142,13 @@ class TelegramObject(ContextInstanceMixin, metaclass=MetaTelegramObject): @property def bot(self): from ..bot.bot import Bot - return Bot.get_current() + + bot = Bot.get_current() + if bot is None: + raise RuntimeError("Can't get bot instance from context. " + "You can fix it with setting current instance: " + "'Bot.set_current(bot_instance)'") + return bot def to_python(self) -> typing.Dict: """ diff --git a/tests/__init__.py b/tests/__init__.py index e69de29b..cb0c6b9d 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -0,0 +1,39 @@ +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 diff --git a/tests/test_message.py b/tests/test_message.py new file mode 100644 index 00000000..996529f3 --- /dev/null +++ b/tests/test_message.py @@ -0,0 +1,47 @@ +from asyncio import BaseEventLoop + +import pytest + +from aiogram import Bot, types +from . import FakeTelegram, TOKEN + +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')