Skip to content

Commit

Permalink
Merge pull request #4 from OCCCAS/dev
Browse files Browse the repository at this point in the history
BREAKING CHANGE: baes path renamed from aiogram_pytest to aiogram_tests
  • Loading branch information
OCCASS authored Oct 25, 2022
2 parents a572f88 + f30b558 commit 32650d8
Show file tree
Hide file tree
Showing 15 changed files with 61 additions and 63 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ import pytest

from bot import echo

from aiogram_pytest import Requester
from aiogram_pytest.handler import MessageHandler
from aiogram_pytest.types.dataset import MESSAGE
from aiogram_tests import Requester
from aiogram_tests.handler import MessageHandler
from aiogram_tests.types.dataset import MESSAGE


@pytest.mark.asyncio
Expand Down
File renamed without changes.
File renamed without changes.
92 changes: 45 additions & 47 deletions aiogram_pytest/handler.py → aiogram_tests/handler.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
from typing import Any
from typing import Callable
from typing import Dict
from typing import Generator
from typing import Iterable
from typing import List
from typing import Tuple
from typing import Union

from aiogram import Bot
from aiogram import Dispatcher
from aiogram import types
from aiogram.dispatcher.event.telegram import TelegramEventObserver
from aiogram.filters import Filter
from aiogram.filters import StateFilter
from aiogram.fsm.state import State
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.types import Update

from .mocked_bot import MockedBot
from .types.dataset import CHAT
Expand All @@ -21,7 +21,11 @@

class RequestHandler:
def __init__(
self, dp_middlewares: Iterable = None, dp_filters: Iterable = None, exclude_observer_methods: Iterable = None
self,
dp_middlewares: Iterable = None,
dp_filters: Iterable = None,
exclude_observer_methods: Iterable = None,
**kwargs,
):
self.bot = MockedBot()
self.dp = Dispatcher(storage=MemoryStorage())
Expand All @@ -44,21 +48,21 @@ def __init__(
types.User.set_current(USER.as_object())
types.Chat.set_current(CHAT.as_object())

def _get_dispatcher_event_observers(self):
result = []
for name in dir(self.bot):
if isinstance(getattr(self.bot, name), TelegramEventObserver):
result.append(name)
def _get_dispatcher_event_observers(self) -> Generator[str]:
"""
Returns a names for bot event observers, like message, callback_query etc.
"""

result = (name for name in dir(self.bot) if isinstance(getattr(self.bot, name), TelegramEventObserver))
return result

def _register_middlewares(self, event_observer: Tuple, middlewares: Tuple):
def _register_middlewares(self, event_observer: Iterable, middlewares: Iterable) -> None:
for eo_name in event_observer:
for m in middlewares:
eo_obj = getattr(self.bot, eo_name)
eo_obj.middleware.register(m)

def _register_filters(self, event_observer: Tuple, filters: Tuple):
def _register_filters(self, event_observer: Iterable, filters: Iterable) -> None:
for eo_name in event_observer:
for f in filters:
eo_obj = getattr(self.bot, eo_name)
Expand All @@ -68,18 +72,19 @@ async def __call__(self, *args, **kwargs):
raise NotImplementedError


class MessageHandler(RequestHandler):
class TelegramEventObserverHandler(RequestHandler):
def __init__(
self,
callback,
*filters: Any,
callback: Callable,
*filters: Filter,
state: Union[State, str, None] = None,
state_data: dict = None,
state_data: Dict = None,
dp_middlewares: Iterable = None,
exclude_observer_methods: Iterable = None,
**kwargs,
):
super().__init__(dp_middlewares, (), exclude_observer_methods)

self._callback = callback
self._filters: List = list(filters)
self._state: Union[State, str, None] = state
Expand All @@ -94,52 +99,45 @@ def __init__(
if not isinstance(self._state_data, dict):
raise ValueError("state_data is not a dict")

async def __call__(self, message: types.Message):
def __call__(self, *args, **kwargs):
if self._state:
self._filters.append(StateFilter(self._state))

self.dp.message.register(self._callback, *self._filters)
self.register_handler()

if self._state:
state = self.dp.fsm.get_context(self.bot, user_id=12345678, chat_id=12345678)
await state.set_state(self._state)
await state.update_data(**self._state_data)

await self.dp.feed_update(self.bot, Update(update_id=12345678, message=message))
self.feed_update(*args, **kwargs)

def register_handler(self) -> None:
"""
Register TelegramEventObserver in dispatcher
"""

class CallbackQueryHandler(RequestHandler):
def __init__(
self,
callback,
*filters,
state: Union[State, str, None] = None,
state_data: dict = None,
dp_middlewares: Iterable = None,
exclude_observer_methods: Iterable = None,
**kwargs,
):
super().__init__(dp_middlewares, (), exclude_observer_methods)
self._callback = callback
self._filters: List = list(filters)
self._state: Union[State, str, None] = state
self._state_data: Dict = state_data
raise NotImplementedError

if self._state_data is None:
self._state_data = {}
def feed_update(self, *args, **kwargs) -> None:
"""
Feed dispatcher updates
"""

if self._filters is None:
self._filters = []
raise NotImplementedError

async def __call__(self, callback_query: types.CallbackQuery):
if self._state:
self._filters.append(StateFilter(self._state))

self.dp.callback_query.register(self._callback, *self._filters)
class MessageHandler(TelegramEventObserverHandler):
def register_handler(self) -> None:
self.dp.message.register(self._callback, *self._filters)

if self._state:
state = self.dp.fsm.get_context(self.bot, user_id=12345678, chat_id=12345678)
await state.set_state(self._state)
await state.update_data(**self._state_data)
def feed_update(self, message: types.Message, *args, **kwargs) -> None:
self.dp.feed_update(self.bot, types.Update(update_id=12345678, message=message))


class CallbackQueryHandler(TelegramEventObserverHandler):
def register_handler(self) -> None:
self.dp.callback_query.register(self._callback, *self._filters)

await self.dp.feed_update(self.bot, types.Update(update_id=12345678, callback_query=callback_query))
def feed_update(self, callback_query: types.CallbackQuery, *args, **kwargs) -> None:
self.dp.feed_update(self.bot, types.Update(update_id=12345678, callback_query=callback_query))
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
10 changes: 5 additions & 5 deletions examples/example_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
from test_bot import States
from test_bot import TestCallbackData

from aiogram_pytest import Requester
from aiogram_pytest.handler import CallbackQueryHandler
from aiogram_pytest.handler import MessageHandler
from aiogram_pytest.types.dataset import CALLBACK_QUERY
from aiogram_pytest.types.dataset import MESSAGE
from aiogram_tests import Requester
from aiogram_tests.handler import CallbackQueryHandler
from aiogram_tests.handler import MessageHandler
from aiogram_tests.types.dataset import CALLBACK_QUERY
from aiogram_tests.types.dataset import MESSAGE


@pytest.mark.asyncio
Expand Down
10 changes: 5 additions & 5 deletions tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@
from .bot import message_handler_with_state_data
from .bot import States
from .bot import TestCallbackData
from aiogram_pytest import Requester
from aiogram_pytest.handler import CallbackQueryHandler
from aiogram_pytest.handler import MessageHandler
from aiogram_pytest.types.dataset import CALLBACK_QUERY
from aiogram_pytest.types.dataset import MESSAGE
from aiogram_tests import Requester
from aiogram_tests.handler import CallbackQueryHandler
from aiogram_tests.handler import MessageHandler
from aiogram_tests.types.dataset import CALLBACK_QUERY
from aiogram_tests.types.dataset import MESSAGE


@pytest.mark.asyncio
Expand Down
4 changes: 2 additions & 2 deletions tests/test_dataset_item.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from aiogram import types

import aiogram_pytest.types.dataset as dataset
from aiogram_pytest.types.dataset import DatasetItem
import aiogram_tests.types.dataset as dataset
from aiogram_tests.types.dataset import DatasetItem


def test_as_object():
Expand Down
Empty file added tests/test_handlers.py
Empty file.
2 changes: 1 addition & 1 deletion tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from aiogram_pytest.utils import camel_case2snake_case
from aiogram_tests.utils import camel_case2snake_case


def test_camle_case_convertor():
Expand Down

0 comments on commit 32650d8

Please sign in to comment.