mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-08 17:13:56 +00:00
Merge pull request #106 from aiogram/bot_from_context_exception
Raise Exception if there's no bot instance in context
This commit is contained in:
commit
843be46d19
3 changed files with 93 additions and 1 deletions
|
|
@ -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:
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -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
|
||||
47
tests/test_message.py
Normal file
47
tests/test_message.py
Normal file
|
|
@ -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')
|
||||
Loading…
Add table
Add a link
Reference in a new issue