Propagate update to context in router

This commit is contained in:
Alex Root Junior 2020-01-26 02:34:32 +02:00
parent f0f1523142
commit 3dd5530241
3 changed files with 20 additions and 4 deletions

View file

@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Dict, Generic, TypeVar
from aiogram import Bot
from aiogram.api.types import Update
T = TypeVar("T")
@ -27,6 +28,10 @@ class BaseHandler(BaseHandlerMixin[T], ABC):
return self.data["bot"]
return Bot.get_current()
@property
def update(self) -> Update:
return self.data["update"]
@abstractmethod
async def handle(self) -> Any: # pragma: no cover
pass

View file

@ -200,7 +200,7 @@ class Router:
User.set_current(from_user)
if chat:
Chat.set_current(chat)
async for result in observer.trigger(event, **kwargs):
async for result in observer.trigger(event, update=update, **kwargs):
return result
for router in self.sub_routers:

View file

@ -1,10 +1,11 @@
import asyncio
import datetime
from typing import Any
import pytest
from aiogram import Bot
from aiogram.api.types import Update
from aiogram.api.types import Chat, Message, Update
from aiogram.dispatcher.handler.base import BaseHandler
@ -27,7 +28,7 @@ class TestBaseClassBasedHandler:
assert await handler == 42
@pytest.mark.asyncio
async def test_bot_mixin_from_context(self):
async def test_bot_from_context(self):
event = Update(update_id=42)
handler = MyHandler(event=event, key=42)
bot = Bot("42:TEST")
@ -38,10 +39,20 @@ class TestBaseClassBasedHandler:
assert handler.bot == bot
@pytest.mark.asyncio
async def test_bot_mixin_from_data(self):
async def test_bot_from_data(self):
event = Update(update_id=42)
bot = Bot("42:TEST")
handler = MyHandler(event=event, key=42, bot=bot)
assert "bot" in handler.data
assert handler.bot == bot
def test_update_from_data(self):
event = Message(
message_id=42, chat=Chat(id=42, type="private"), date=datetime.datetime.now()
)
update = Update(update_id=42, message=event)
handler = MyHandler(event=event, update=update)
assert handler.event == event
assert handler.update == update