From 3dd55302418f974323c868e164be5eac7d99ccce Mon Sep 17 00:00:00 2001 From: Alex Root Junior Date: Sun, 26 Jan 2020 02:34:32 +0200 Subject: [PATCH] Propagate update to context in router --- aiogram/dispatcher/handler/base.py | 5 +++++ aiogram/dispatcher/router.py | 2 +- tests/test_dispatcher/test_handler/test_base.py | 17 ++++++++++++++--- 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/aiogram/dispatcher/handler/base.py b/aiogram/dispatcher/handler/base.py index 6df413a4..d4ce4c53 100644 --- a/aiogram/dispatcher/handler/base.py +++ b/aiogram/dispatcher/handler/base.py @@ -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 diff --git a/aiogram/dispatcher/router.py b/aiogram/dispatcher/router.py index df48df4e..073e98d0 100644 --- a/aiogram/dispatcher/router.py +++ b/aiogram/dispatcher/router.py @@ -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: diff --git a/tests/test_dispatcher/test_handler/test_base.py b/tests/test_dispatcher/test_handler/test_base.py index b385d4e4..5e8ef0f3 100644 --- a/tests/test_dispatcher/test_handler/test_base.py +++ b/tests/test_dispatcher/test_handler/test_base.py @@ -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