feat(disp): raise RuntimeError when no storage is set

tests: improve coverage
This commit is contained in:
mpa 2020-08-22 05:16:30 +04:00
parent 25ecc6fafc
commit 608fa5e27b
No known key found for this signature in database
GPG key ID: BCCFBFCCC9B754A8
2 changed files with 24 additions and 3 deletions

View file

@ -17,7 +17,6 @@ from .middlewares.user_context import UserContextMiddleware
from .router import Router
from .state.context import CurrentUserContext
from .storage.base import BaseStorage
from .storage.dummy import DummyStorage
class Dispatcher(Router, Generic[StorageDataT]):
@ -40,7 +39,11 @@ class Dispatcher(Router, Generic[StorageDataT]):
@property
def current_state(self) -> CurrentUserContext[StorageDataT]:
if self.storage is None:
self.storage: DummyStorage = DummyStorage() # type: ignore
raise RuntimeError(
"`Dispatcher.current_state` requires storage to be used properly. "
"Set the storage first while initialization: "
"Dispatcher(storage=<required_storage>, )"
)
chat = cast(Optional[Chat], Chat.get_current())
user = cast(Optional[User], User.get_current())
@ -233,7 +236,7 @@ class Dispatcher(Router, Generic[StorageDataT]):
try:
try:
await waiter
except CancelledError: # pragma: nocover
except CancelledError: # pragma: no cover
process_updates.remove_done_callback(release_waiter)
process_updates.cancel()
raise

View file

@ -11,6 +11,8 @@ from aiogram.api.types import Chat, Message, Update, User
from aiogram.dispatcher.dispatcher import Dispatcher
from aiogram.dispatcher.event.bases import NOT_HANDLED
from aiogram.dispatcher.router import Router
from aiogram.dispatcher.state.context import CurrentUserContext
from aiogram.dispatcher.storage.dict import DictStorage
from tests.mocked_bot import MockedBot
try:
@ -51,6 +53,22 @@ class TestDispatcher:
dp._parent_router = Router()
assert dp.parent_router is None
def test_init_storage(self):
dp = Dispatcher()
with pytest.raises(RuntimeError):
_ = dp.current_state
assert dp.storage is None
_storage = DictStorage()
dp = Dispatcher(storage=_storage)
assert dp.storage == _storage
@pytest.mark.asyncio
async def test_current_state(self):
user = User(id=109_112_97, is_bot=False, first_name="mpa")
User.set_current(user)
dp = Dispatcher(storage=DictStorage())
assert isinstance(dp.current_state, CurrentUserContext)
@pytest.mark.asyncio
async def test_feed_update(self):
dp = Dispatcher()