Add context manager support for bot client (#1468)

* Add context manager support for bot client

The bot client now supports the context manager protocol, providing automatic resource management. This enhancement helps to automatically close the session when leaving the context, which cleans up resources better. The documentation and tests have been updated accordingly to illustrate this new feature. Moreover, an example of usage without a dispatcher has been provided to clarify its use in simple cases.

* Added changelog
This commit is contained in:
Alex Root Junior 2024-04-22 23:42:47 +03:00 committed by GitHub
parent 9756dac877
commit 4729978c60
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 84 additions and 0 deletions

View file

@ -14,6 +14,7 @@ from aiogram.methods import GetFile, GetMe
from aiogram.types import File, PhotoSize
from tests.deprecated import check_deprecated
from tests.mocked_bot import MockedBot
from tests.test_api.test_client.test_session.test_base_session import CustomSession
@pytest.fixture()
@ -42,6 +43,18 @@ class TestBot:
assert isinstance(bot.session, AiohttpSession)
assert bot.id == 42
async def test_bot_context_manager_over_session(self):
session = CustomSession()
with patch(
"tests.test_api.test_client.test_session.test_base_session.CustomSession.close",
new_callable=AsyncMock,
) as mocked_close:
async with Bot(token="42:TEST", session=session) as bot:
assert bot.id == 42
assert bot.session is session
mocked_close.assert_awaited_once()
def test_init_default(self):
with check_deprecated(
max_version="3.7.0",