Skip to content

Commit

Permalink
Refactor Debug logging in Bot to Improve Type Hinting (#4151)
Browse files Browse the repository at this point in the history
  • Loading branch information
Bibo-Joshi committed Mar 24, 2024
1 parent c0716dd commit 8a542e2
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 161 deletions.
147 changes: 9 additions & 138 deletions telegram/_bot.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion telegram/_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -1169,7 +1169,7 @@ async def set_permissions(

async def set_administrator_custom_title(
self,
user_id: Union[int, str],
user_id: int,
custom_title: str,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
Expand Down
2 changes: 1 addition & 1 deletion telegram/_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -2871,7 +2871,7 @@ async def reply_game(
do_quote, quote, reply_to_message_id, reply_parameters
)
return await self.get_bot().send_game(
chat_id=chat_id,
chat_id=chat_id, # type: ignore[arg-type]
game_short_name=game_short_name,
disable_notification=disable_notification,
reply_parameters=effective_reply_parameters,
Expand Down
3 changes: 2 additions & 1 deletion telegram/_passport/passportfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,5 +203,6 @@ async def get_file(
pool_timeout=pool_timeout,
api_kwargs=api_kwargs,
)
file.set_credentials(self._credentials)
if self._credentials:
file.set_credentials(self._credentials)
return file
8 changes: 6 additions & 2 deletions telegram/ext/_extbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@
from telegram.ext import BaseRateLimiter, Defaults

HandledTypes = TypeVar("HandledTypes", bound=Union[Message, CallbackQuery, Chat])
KT = TypeVar("KT", bound=ReplyMarkup)


class ExtBot(Bot, Generic[RLARGS]):
Expand Down Expand Up @@ -485,11 +486,14 @@ def _insert_defaults(self, data: Dict[str, object]) -> None:

data[key] = new_value

def _replace_keyboard(self, reply_markup: Optional[ReplyMarkup]) -> Optional[ReplyMarkup]:
def _replace_keyboard(self, reply_markup: Optional[KT]) -> Optional[KT]:
# If the reply_markup is an inline keyboard and we allow arbitrary callback data, let the
# CallbackDataCache build a new keyboard with the data replaced. Otherwise return the input
if isinstance(reply_markup, InlineKeyboardMarkup) and self.callback_data_cache is not None:
return self.callback_data_cache.process_keyboard(reply_markup)
# for some reason mypy doesn't understand that IKB is a subtype of Optional[KT]
return self.callback_data_cache.process_keyboard( # type: ignore[return-value]
reply_markup
)

return reply_markup

Expand Down
2 changes: 1 addition & 1 deletion telegram/ext/_updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ async def bootstrap_set_webhook() -> bool:
if drop_pending_updates:
_LOGGER.debug("Dropping pending updates from Telegram server")
await self.bot.set_webhook(
url=webhook_url,
url=webhook_url, # type: ignore[arg-type]
certificate=cert,
allowed_updates=allowed_updates,
ip_address=ip_address,
Expand Down
29 changes: 12 additions & 17 deletions tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import inspect
import logging
import pickle
import re
import socket
import time
from collections import defaultdict
Expand Down Expand Up @@ -388,22 +387,10 @@ def test_bot_deepcopy_error(self, bot):
with pytest.raises(TypeError, match="Bot objects cannot be deepcopied"):
copy.deepcopy(bot)

@bot_methods(ext_bot=False)
def test_api_methods_have_log_decorator(self, bot_class, bot_method_name, bot_method):
"""Check that all bot methods have the log decorator ..."""
# not islower() skips the camelcase aliases
if not bot_method_name.islower():
return
source = inspect.getsource(bot_method)
assert (
# Use re.match to only match at *the beginning* of the string
re.match(rf"\s*\@\_log\s*async def {bot_method_name}", source)
), f"{bot_method_name} is missing the @_log decorator"

@pytest.mark.parametrize(
("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")]
)
async def test_log_decorator(self, bot: PytestExtBot, cls, logger_name, caplog):
async def test_bot_method_logging(self, bot: PytestExtBot, cls, logger_name, caplog):
# Second argument makes sure that we ignore logs from e.g. httpx
with caplog.at_level(logging.DEBUG, logger="telegram"):
await cls(bot.token).get_me()
Expand All @@ -415,11 +402,19 @@ async def test_log_decorator(self, bot: PytestExtBot, cls, logger_name, caplog):
caplog.records.pop(idx)
if record.getMessage().startswith("Task exception was never retrieved"):
caplog.records.pop(idx)
assert len(caplog.records) == 3
assert len(caplog.records) == 2

assert all(caplog.records[i].name == logger_name for i in [-1, 0])
assert caplog.records[0].getMessage().startswith("Entering: get_me")
assert caplog.records[-1].getMessage().startswith("Exiting: get_me")
assert (
caplog.records[0]
.getMessage()
.startswith("Calling Bot API endpoint `getMe` with parameters `{}`")
)
assert (
caplog.records[-1]
.getMessage()
.startswith("Call to Bot API endpoint `getMe` finished with return value")
)

@bot_methods()
def test_camel_case_aliases(self, bot_class, bot_method_name, bot_method):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,19 @@ async def make_assertion(*_, **kwargs):
custom_title = kwargs["custom_title"] == "custom_title"
return chat_id and user_id and custom_title

assert check_shortcut_signature(
Chat.set_administrator_custom_title,
Bot.set_chat_administrator_custom_title,
["chat_id"],
[],
)
assert await check_shortcut_call(
chat.set_administrator_custom_title,
chat.get_bot(),
"set_chat_administrator_custom_title",
)
assert await check_defaults_handling(chat.set_administrator_custom_title, chat.get_bot())

monkeypatch.setattr("telegram.Bot.set_chat_administrator_custom_title", make_assertion)
assert await chat.set_administrator_custom_title(user_id=42, custom_title="custom_title")

Expand Down

0 comments on commit 8a542e2

Please sign in to comment.