Add middleware for logging outgoing requests (#716)

* add middleware for logging outgoing requests

* add middleware description

* fix RequestMiddlewareType callable signature

* undo `fix`, update signatures in tests

* remove repeating code

* accept proposed changes

Co-authored-by: Alex Root Junior <jroot.junior@gmail.com>

* update tests

* add patchnote

Co-authored-by: Alex Root Junior <jroot.junior@gmail.com>
This commit is contained in:
darksidecat 2021-10-06 00:57:26 +03:00 committed by GitHub
parent 45a1fb2749
commit 99c99cec78
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 137 additions and 12 deletions

View file

@ -245,14 +245,14 @@ class TestBaseSession:
flag_after = False
@bot.session.middleware
async def my_middleware(b, method, make_request):
async def my_middleware(make_request, b, method):
nonlocal flag_before, flag_after
flag_before = True
try:
assert isinstance(b, Bot)
assert isinstance(method, TelegramMethod)
return await make_request(bot, method)
return await make_request(b, method)
finally:
flag_after = True

View file

@ -0,0 +1,42 @@
import datetime
import logging
import pytest
from aiogram.client.session.middlewares.request_logging import RequestLogging
from aiogram.methods import GetMe, SendMessage
from aiogram.types import Chat, Message, User
from tests.mocked_bot import MockedBot
pytestmark = pytest.mark.asyncio
class TestRequestLogging:
async def test_use_middleware(self, bot: MockedBot, caplog):
caplog.set_level(logging.INFO)
bot.session.middleware(RequestLogging())
bot.add_result_for(GetMe, ok=True, result=User(id=42, is_bot=True, first_name="Test"))
assert await bot.get_me()
assert "Make request with method='GetMe' by bot id=42" in caplog.text
async def test_ignore_methods(self, bot: MockedBot, caplog):
caplog.set_level(logging.INFO)
bot.session.middleware(RequestLogging(ignore_methods=[GetMe]))
bot.add_result_for(GetMe, ok=True, result=User(id=42, is_bot=True, first_name="Test"))
assert await bot.get_me()
assert "Make request with method='GetMe' by bot id=42" not in caplog.text
bot.add_result_for(
SendMessage,
ok=True,
result=Message(
message_id=42,
date=datetime.datetime.now(),
text="test",
chat=Chat(id=42, type="private"),
),
)
assert await bot.send_message(chat_id=1, text="Test")
assert "Make request with method='SendMessage' by bot id=42" in caplog.text