diff --git a/examples/conversationbot2.py b/examples/conversationbot2.py index ce6d9ca70..49d0deea9 100644 --- a/examples/conversationbot2.py +++ b/examples/conversationbot2.py @@ -50,7 +50,7 @@ def facts_to_str(user_data: Dict[str, str]) -> str: facts = list() for key, value in user_data.items(): - facts.append('{} - {}'.format(key, value)) + facts.append(f'{key} - {value}') return "\n".join(facts).join(['\n', '\n']) @@ -68,9 +68,7 @@ def start(update: Update, context: CallbackContext) -> int: def regular_choice(update: Update, context: CallbackContext) -> int: text = update.message.text context.user_data['choice'] = text - update.message.reply_text( - 'Your {}? Yes, I would love to hear about that!'.format(text.lower()) - ) + update.message.reply_text(f'Your {text.lower()}? Yes, I would love to hear about that!') return TYPING_REPLY @@ -92,8 +90,8 @@ def received_information(update: Update, context: CallbackContext) -> int: update.message.reply_text( "Neat! Just so you know, this is what you already told me:" - "{} You can tell me more, or change your opinion" - " on something.".format(facts_to_str(user_data)), + f"{facts_to_str(user_data)} You can tell me more, or change your opinion" + " on something.", reply_markup=markup, ) @@ -106,7 +104,7 @@ def done(update: Update, context: CallbackContext) -> int: del user_data['choice'] update.message.reply_text( - "I learned these facts about you:" "{}" "Until next time!".format(facts_to_str(user_data)) + f"I learned these facts about you: {facts_to_str(user_data)} Until next time!" ) user_data.clear() diff --git a/examples/deeplinking.py b/examples/deeplinking.py index 23e30275e..eb1cee13c 100644 --- a/examples/deeplinking.py +++ b/examples/deeplinking.py @@ -66,7 +66,7 @@ def deep_linked_level_2(update: Update, context: CallbackContext) -> None: """Reached through the SO_COOL payload""" bot = context.bot url = helpers.create_deep_linked_url(bot.get_me().username, USING_ENTITIES) - text = "You can also mask the deep-linked URLs as links: " "[▶️ CLICK HERE]({}).".format(url) + text = f"You can also mask the deep-linked URLs as links: [▶️ CLICK HERE]({url})." update.message.reply_text(text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) @@ -74,7 +74,7 @@ def deep_linked_level_3(update: Update, context: CallbackContext) -> None: """Reached through the USING_ENTITIES payload""" payload = context.args update.message.reply_text( - "Congratulations! This is as deep as it gets 👏🏻\n\n" "The payload was: {}".format(payload) + f"Congratulations! This is as deep as it gets 👏🏻\n\nThe payload was: {payload}" ) diff --git a/examples/errorhandlerbot.py b/examples/errorhandlerbot.py index 4836be668..3aa90d0df 100644 --- a/examples/errorhandlerbot.py +++ b/examples/errorhandlerbot.py @@ -42,16 +42,12 @@ def error_handler(update: Update, context: CallbackContext) -> None: # Build the message with some markup and additional information about what happened. # You might need to add some logic to deal with messages longer than the 4096 character limit. message = ( - 'An exception was raised while handling an update\n' - '
update = {}\n\n' - '
context.chat_data = {}\n\n' - '
context.user_data = {}\n\n' - '
{}' - ).format( - html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False)), - html.escape(str(context.chat_data)), - html.escape(str(context.user_data)), - html.escape(tb_string), + f'An exception was raised while handling an update\n' + f'
update = {html.escape(json.dumps(update.to_dict(), indent=2, ensure_ascii=False))}' + '\n\n' + f'
context.chat_data = {html.escape(str(context.chat_data))}\n\n' + f'
context.user_data = {html.escape(str(context.user_data))}\n\n' + f'
{html.escape(tb_string)}' ) # Finally, send the message @@ -66,7 +62,7 @@ def bad_command(update: Update, context: CallbackContext) -> None: def start(update: Update, context: CallbackContext) -> None: update.effective_message.reply_html( 'Use /bad_command to cause an error.\n' - 'Your chat id is
{}
.'.format(update.effective_chat.id)
+ f'Your chat id is {update.effective_chat.id}
.'
)
diff --git a/examples/inlinebot.py b/examples/inlinebot.py
index f9f804cd4..460e4c70a 100644
--- a/examples/inlinebot.py
+++ b/examples/inlinebot.py
@@ -52,14 +52,14 @@ def inlinequery(update: Update, context: CallbackContext) -> None:
id=uuid4(),
title="Bold",
input_message_content=InputTextMessageContent(
- "*{}*".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN
+ f"*{escape_markdown(query)}*", parse_mode=ParseMode.MARKDOWN
),
),
InlineQueryResultArticle(
id=uuid4(),
title="Italic",
input_message_content=InputTextMessageContent(
- "_{}_".format(escape_markdown(query)), parse_mode=ParseMode.MARKDOWN
+ f"_{escape_markdown(query)}_", parse_mode=ParseMode.MARKDOWN
),
),
]
diff --git a/examples/inlinekeyboard.py b/examples/inlinekeyboard.py
index 70461a004..8158cc084 100644
--- a/examples/inlinekeyboard.py
+++ b/examples/inlinekeyboard.py
@@ -39,7 +39,7 @@ def button(update: Update, context: CallbackContext) -> None:
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
- query.edit_message_text(text="Selected option: {}".format(query.data))
+ query.edit_message_text(text=f"Selected option: {query.data}")
def help_command(update: Update, context: CallbackContext) -> None:
diff --git a/examples/nestedconversationbot.py b/examples/nestedconversationbot.py
index ec9bb8410..9b91576dd 100644
--- a/examples/nestedconversationbot.py
+++ b/examples/nestedconversationbot.py
@@ -128,15 +128,13 @@ def show_data(update: Update, context: CallbackContext) -> None:
text = ''
if level == SELF:
for person in user_data[level]:
- text += '\nName: {}, Age: {}'.format(person.get(NAME, '-'), person.get(AGE, '-'))
+ text += f"\nName: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
else:
male, female = _name_switcher(level)
for person in user_data[level]:
gender = female if person[GENDER] == FEMALE else male
- text += '\n{}: Name: {}, Age: {}'.format(
- gender, person.get(NAME, '-'), person.get(AGE, '-')
- )
+ text += f"\n{gender}: Name: {person.get(NAME, '-')}, Age: {person.get(AGE, '-')}"
return text
user_data = context.user_data
@@ -341,9 +339,7 @@ def main():
entry_points=[CallbackQueryHandler(select_level, pattern='^' + str(ADDING_MEMBER) + '$')],
states={
SELECTING_LEVEL: [
- CallbackQueryHandler(
- select_gender, pattern='^{}$|^{}$'.format(str(PARENTS), str(CHILDREN))
- )
+ CallbackQueryHandler(select_gender, pattern=f'^{PARENTS}$|^{CHILDREN}$')
],
SELECTING_GENDER: [description_conv],
},
diff --git a/examples/persistentconversationbot.py b/examples/persistentconversationbot.py
index 0f2afb705..492f202bb 100644
--- a/examples/persistentconversationbot.py
+++ b/examples/persistentconversationbot.py
@@ -51,7 +51,7 @@ def facts_to_str(user_data):
facts = list()
for key, value in user_data.items():
- facts.append('{} - {}'.format(key, value))
+ facts.append(f'{key} - {value}')
return "\n".join(facts).join(['\n', '\n'])
@@ -60,9 +60,8 @@ def start(update: Update, context: CallbackContext) -> None:
reply_text = "Hi! My name is Doctor Botter."
if context.user_data:
reply_text += (
- " You already told me your {}. Why don't you tell me something more "
- "about yourself? Or change anything I "
- "already know.".format(", ".join(context.user_data.keys()))
+ f" You already told me your {', '.join(context.user_data.keys())}. Why don't you "
+ f"tell me something more about yourself? Or change anything I already know."
)
else:
reply_text += (
@@ -78,11 +77,11 @@ def regular_choice(update: Update, context: CallbackContext) -> None:
text = update.message.text.lower()
context.user_data['choice'] = text
if context.user_data.get(text):
- reply_text = 'Your {}, I already know the following ' 'about that: {}'.format(
- text, context.user_data[text]
+ reply_text = (
+ f'Your {text}, I already know the following about that: {context.user_data[text]}'
)
else:
- reply_text = 'Your {}? Yes, I would love to hear about that!'.format(text)
+ reply_text = f'Your {text}? Yes, I would love to hear about that!'
update.message.reply_text(reply_text)
return TYPING_REPLY
@@ -104,9 +103,9 @@ def received_information(update: Update, context: CallbackContext) -> None:
update.message.reply_text(
"Neat! Just so you know, this is what you already told me:"
- "{}"
+ f"{facts_to_str(context.user_data)}"
"You can tell me more, or change your opinion on "
- "something.".format(facts_to_str(context.user_data)),
+ "something.",
reply_markup=markup,
)
@@ -115,7 +114,7 @@ def received_information(update: Update, context: CallbackContext) -> None:
def show_data(update: Update, context: CallbackContext) -> None:
update.message.reply_text(
- "This is what you already told me:" "{}".format(facts_to_str(context.user_data))
+ f"This is what you already told me: {facts_to_str(context.user_data)}"
)
@@ -124,9 +123,7 @@ def done(update: Update, context: CallbackContext) -> None:
del context.user_data['choice']
update.message.reply_text(
- "I learned these facts about you:"
- "{}"
- "Until next time!".format(facts_to_str(context.user_data))
+ "I learned these facts about you:" f"{facts_to_str(context.user_data)}" "Until next time!"
)
return ConversationHandler.END
diff --git a/examples/pollbot.py b/examples/pollbot.py
index b0540bf01..4f604a9a5 100644
--- a/examples/pollbot.py
+++ b/examples/pollbot.py
@@ -84,7 +84,7 @@ def receive_poll_answer(update: Update, context: CallbackContext) -> None:
answer_string += questions[question_id]
context.bot.send_message(
context.bot_data[poll_id]["chat_id"],
- "{} feels {}!".format(update.effective_user.mention_html(), answer_string),
+ f"{update.effective_user.mention_html()} feels {answer_string}!",
parse_mode=ParseMode.HTML,
)
context.bot_data[poll_id]["answers"] += 1
diff --git a/telegram/__main__.py b/telegram/__main__.py
index affefe628..56ecfd4fb 100644
--- a/telegram/__main__.py
+++ b/telegram/__main__.py
@@ -38,12 +38,10 @@ def _git_revision() -> Optional[str]:
def print_ver_info() -> None:
git_revision = _git_revision()
- print(
- 'python-telegram-bot {}'.format(telegram_ver)
- + (' ({})'.format(git_revision) if git_revision else '')
- )
- print('certifi {}'.format(certifi.__version__)) # type: ignore[attr-defined]
- print('Python {}'.format(sys.version.replace('\n', ' ')))
+ print(f'python-telegram-bot {telegram_ver}' + (f' ({git_revision})' if git_revision else ''))
+ print(f'certifi {certifi.__version__}') # type: ignore[attr-defined]
+ sys_version = sys.version.replace('\n', ' ')
+ print(f'Python {sys_version}')
def main() -> None:
diff --git a/telegram/base.py b/telegram/base.py
index 332a373f0..67fe59abc 100644
--- a/telegram/base.py
+++ b/telegram/base.py
@@ -102,13 +102,13 @@ class TelegramObject:
if isinstance(other, self.__class__):
if self._id_attrs == ():
warnings.warn(
- "Objects of type {} can not be meaningfully tested for "
- "equivalence.".format(self.__class__.__name__)
+ f"Objects of type {self.__class__.__name__} can not be meaningfully tested for"
+ " equivalence."
)
if other._id_attrs == ():
warnings.warn(
- "Objects of type {} can not be meaningfully tested for "
- "equivalence.".format(other.__class__.__name__)
+ f"Objects of type {other.__class__.__name__} can not be meaningfully tested"
+ " for equivalence."
)
return self._id_attrs == other._id_attrs
return super().__eq__(other) # pylint: disable=no-member
diff --git a/telegram/bot.py b/telegram/bot.py
index daad48e57..28902ea57 100644
--- a/telegram/bot.py
+++ b/telegram/bot.py
@@ -231,9 +231,7 @@ class Bot(TelegramObject):
else:
data = api_kwargs
- return self.request.post(
- '{}/{}'.format(self.base_url, endpoint), data=data, timeout=timeout
- )
+ return self.request.post(f'{self.base_url}/{endpoint}', data=data, timeout=timeout)
def _message(
self,
@@ -321,7 +319,7 @@ class Bot(TelegramObject):
def link(self) -> str:
""":obj:`str`: Convenience property. Returns the t.me link of the bot."""
- return "https://t.me/{}".format(self.username)
+ return f"https://t.me/{self.username}"
@property # type: ignore
@info
@@ -355,7 +353,7 @@ class Bot(TelegramObject):
def name(self) -> str:
""":obj:`str`: Bot's @username."""
- return '@{}'.format(self.username)
+ return f'@{self.username}'
@log
def get_me(self, timeout: int = None, api_kwargs: JSONDict = None) -> Optional[User]:
@@ -2010,9 +2008,7 @@ class Bot(TelegramObject):
result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs)
if result.get('file_path'): # type: ignore
- result['file_path'] = '{}/{}'.format( # type: ignore
- self.base_file_url, result['file_path'] # type: ignore
- )
+ result['file_path'] = f'{self.base_file_url}/{result["file_path"]}' # type: ignore
return File.de_json(result, self) # type: ignore
diff --git a/telegram/chat.py b/telegram/chat.py
index d1c4c7e48..7751fb4ab 100644
--- a/telegram/chat.py
+++ b/telegram/chat.py
@@ -148,7 +148,7 @@ class Chat(TelegramObject):
""":obj:`str`: Convenience property. If the chat has a :attr:`username`, returns a t.me
link of the chat."""
if self.username:
- return "https://t.me/{}".format(self.username)
+ return f"https://t.me/{self.username}"
return None
@property
diff --git a/telegram/error.py b/telegram/error.py
index e5b9dbb8e..fdc94be81 100644
--- a/telegram/error.py
+++ b/telegram/error.py
@@ -93,7 +93,7 @@ class ChatMigrated(TelegramError):
"""
def __init__(self, new_chat_id: int):
- super().__init__('Group migrated to supergroup. New chat id: {}'.format(new_chat_id))
+ super().__init__(f'Group migrated to supergroup. New chat id: {new_chat_id}')
self.new_chat_id = new_chat_id
def __reduce__(self) -> Tuple[type, Tuple[int]]: # type: ignore[override]
@@ -108,7 +108,7 @@ class RetryAfter(TelegramError):
"""
def __init__(self, retry_after: int):
- super().__init__('Flood control exceeded. Retry in {} seconds'.format(float(retry_after)))
+ super().__init__(f'Flood control exceeded. Retry in {float(retry_after)} seconds')
self.retry_after = float(retry_after)
def __reduce__(self) -> Tuple[type, Tuple[float]]: # type: ignore[override]
diff --git a/telegram/ext/dispatcher.py b/telegram/ext/dispatcher.py
index be2cd952d..95af35233 100644
--- a/telegram/ext/dispatcher.py
+++ b/telegram/ext/dispatcher.py
@@ -216,12 +216,10 @@ class Dispatcher:
return self.__exception_event
def _init_async_threads(self, base_name: str, workers: int) -> None:
- base_name = '{}_'.format(base_name) if base_name else ''
+ base_name = f'{base_name}_' if base_name else ''
for i in range(workers):
- thread = Thread(
- target=self._pooled, name='Bot:{}:worker:{}{}'.format(self.bot.id, base_name, i)
- )
+ thread = Thread(target=self._pooled, name=f'Bot:{self.bot.id}:worker:{base_name}{i}')
self.__async_threads.add(thread)
thread.start()
@@ -243,7 +241,7 @@ class Dispatcher:
"""
if cls.__singleton is not None:
return cls.__singleton() # type: ignore[return-value] # pylint: disable=not-callable
- raise RuntimeError('{} not initialized or multiple instances exist'.format(cls.__name__))
+ raise RuntimeError(f'{cls.__name__} not initialized or multiple instances exist')
def _pooled(self) -> None:
thr_name = current_thread().getName()
@@ -484,14 +482,14 @@ class Dispatcher:
from .conversationhandler import ConversationHandler # pylint: disable=C0415
if not isinstance(handler, Handler):
- raise TypeError('handler is not an instance of {}'.format(Handler.__name__))
+ raise TypeError(f'handler is not an instance of {Handler.__name__}')
if not isinstance(group, int):
raise TypeError('group is not int')
if isinstance(handler, ConversationHandler) and handler.persistent and handler.name:
if not self.persistence:
raise ValueError(
- "ConversationHandler {} can not be persistent if dispatcher has no "
- "persistence".format(handler.name)
+ f"ConversationHandler {handler.name} can not be persistent if dispatcher has "
+ f"no persistence"
)
handler.persistence = self.persistence
handler.conversations = self.persistence.get_conversations(handler.name)
diff --git a/telegram/ext/filters.py b/telegram/ext/filters.py
index c6b5530ab..cd202d3c2 100644
--- a/telegram/ext/filters.py
+++ b/telegram/ext/filters.py
@@ -223,7 +223,7 @@ class InvertedFilter(UpdateFilter):
@property
def name(self) -> str:
- return "' + text + '
'
elif entity.type == MessageEntity.PRE:
if entity.language:
- insert = '{}
'.format(
- entity.language, text
- )
+ insert = f'{text}
'
else:
insert = '' + text + '' elif entity.type == MessageEntity.UNDERLINE: @@ -1480,15 +1478,15 @@ class Message(TelegramObject): url = escape_markdown( entity.url, version=version, entity_type=MessageEntity.TEXT_LINK ) - insert = '[{}]({})'.format(text, url) + insert = f'[{text}]({url})' elif entity.type == MessageEntity.TEXT_MENTION and entity.user: - insert = '[{}](tg://user?id={})'.format(text, entity.user.id) + insert = f'[{text}](tg://user?id={entity.user.id})' elif entity.type == MessageEntity.URL and urled: if version == 1: link = orig_text else: link = text - insert = '[{}]({})'.format(link, orig_text) + insert = f'[{link}]({orig_text})' elif entity.type == MessageEntity.BOLD: insert = '*' + text + '*' elif entity.type == MessageEntity.ITALIC: diff --git a/telegram/passport/credentials.py b/telegram/passport/credentials.py index 8830e34d3..8552db176 100644 --- a/telegram/passport/credentials.py +++ b/telegram/passport/credentials.py @@ -45,7 +45,7 @@ class TelegramDecryptionError(TelegramError): """ def __init__(self, message: Union[str, Exception]): - super().__init__("TelegramDecryptionError: {}".format(message)) + super().__init__(f"TelegramDecryptionError: {message}") self._msg = str(message) def __reduce__(self) -> Tuple[type, Tuple[str]]: @@ -91,7 +91,7 @@ def decrypt(secret, hash, data): # If the newly calculated hash did not match the one telegram gave us if data_hash != hash: # Raise a error that is caught inside telegram.PassportData and transformed into a warning - raise TelegramDecryptionError("Hashes are not equal! {} != {}".format(data_hash, hash)) + raise TelegramDecryptionError(f"Hashes are not equal! {data_hash} != {hash}") # Return data without padding return data[data[0] :] diff --git a/telegram/user.py b/telegram/user.py index 8f9a93cda..05312d176 100644 --- a/telegram/user.py +++ b/telegram/user.py @@ -101,7 +101,7 @@ class User(TelegramObject): """:obj:`str`: Convenience property. If available, returns the user's :attr:`username` prefixed with "@". If :attr:`username` is not available, returns :attr:`full_name`.""" if self.username: - return '@{}'.format(self.username) + return f'@{self.username}' return self.full_name @property @@ -119,7 +119,7 @@ class User(TelegramObject): of the user.""" if self.username: - return "https://t.me/{}".format(self.username) + return f"https://t.me/{self.username}" return None @property diff --git a/telegram/utils/deprecate.py b/telegram/utils/deprecate.py index 356d2c60a..a92db7633 100644 --- a/telegram/utils/deprecate.py +++ b/telegram/utils/deprecate.py @@ -33,7 +33,7 @@ class TelegramDeprecationWarning(Warning): def warn_deprecate_obj(old: str, new: str, stacklevel: int = 3) -> None: warnings.warn( - '{} is being deprecated, please use {} from now on.'.format(old, new), + f'{old} is being deprecated, please use {new} from now on.', category=TelegramDeprecationWarning, stacklevel=stacklevel, ) diff --git a/telegram/utils/helpers.py b/telegram/utils/helpers.py index 0b4e24860..cdd5557a5 100644 --- a/telegram/utils/helpers.py +++ b/telegram/utils/helpers.py @@ -80,7 +80,7 @@ def escape_markdown(text: str, version: int = 1, entity_type: str = None) -> str else: raise ValueError('Markdown version must be either 1 or 2!') - return re.sub('([{}])'.format(re.escape(escape_chars)), r'\\\1', text) + return re.sub(f'([{re.escape(escape_chars)}])', r'\\\1', text) # -------- date/time related helpers -------- @@ -178,7 +178,7 @@ def to_float_timestamp( if isinstance(time_object, Number): return reference_timestamp + time_object - raise TypeError('Unable to convert {} object to timestamp'.format(type(time_object).__name__)) + raise TypeError(f'Unable to convert {type(time_object).__name__} object to timestamp') def to_timestamp( @@ -273,7 +273,7 @@ def effective_message_type(entity: 'MessageEntity') -> Optional[str]: elif isinstance(entity, Update): message = entity.effective_message else: - raise TypeError("entity is not Message or Update (got: {})".format(type(entity))) + raise TypeError(f"entity is not Message or Update (got: {type(entity)})") for i in Message.MESSAGE_TYPES: if getattr(message, i, None): @@ -309,7 +309,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool = if bot_username is None or len(bot_username) <= 3: raise ValueError("You must provide a valid bot_username.") - base_url = 'https://t.me/{}'.format(bot_username) + base_url = f'https://t.me/{bot_username}' if not payload: return base_url @@ -327,7 +327,7 @@ def create_deep_linked_url(bot_username: str, payload: str = None, group: bool = else: key = 'start' - return '{}?{}={}'.format(base_url, key, payload) + return f'{base_url}?{key}={payload}' def encode_conversations_to_json(conversations: Dict[str, Dict[Tuple, Any]]) -> str: diff --git a/telegram/utils/request.py b/telegram/utils/request.py index 69a509e02..b95616206 100644 --- a/telegram/utils/request.py +++ b/telegram/utils/request.py @@ -255,7 +255,7 @@ class Request: except urllib3.exceptions.HTTPError as error: # HTTPError must come last as its the base urllib3 exception class # TODO: do something smart here; for now just raise NetworkError - raise NetworkError('urllib3 HTTPError {}'.format(error)) from error + raise NetworkError(f'urllib3 HTTPError {error}') from error if 200 <= resp.status <= 299: # 200-299 range are HTTP success statuses @@ -281,7 +281,7 @@ class Request: ) if resp.status == 502: raise NetworkError('Bad Gateway') - raise NetworkError('{} ({})'.format(message, resp.status)) + raise NetworkError(f'{message} ({resp.status})') def post(self, url: str, data: JSONDict, timeout: float = None) -> Union[JSONDict, bool]: """Request an URL. diff --git a/telegram/utils/webhookhandler.py b/telegram/utils/webhookhandler.py index 8db7e13cb..ec03887ed 100644 --- a/telegram/utils/webhookhandler.py +++ b/telegram/utils/webhookhandler.py @@ -139,7 +139,7 @@ class WebhookServer: class WebhookAppClass(tornado.web.Application): def __init__(self, webhook_path: str, bot: 'Bot', update_queue: Queue): self.shared_objects = {"bot": bot, "update_queue": update_queue} - handlers = [(r"{}/?".format(webhook_path), WebhookHandler, self.shared_objects)] # noqa + handlers = [(rf"{webhook_path}/?", WebhookHandler, self.shared_objects)] # noqa tornado.web.Application.__init__(self, handlers) def log_request(self, handler: tornado.web.RequestHandler) -> None: diff --git a/tests/bots.py b/tests/bots.py index f79078a8d..2aa514943 100644 --- a/tests/bots.py +++ b/tests/bots.py @@ -87,7 +87,7 @@ def patient_request_wrapper(*args, **kwargs): try: return original_request_wrapper(*args, **kwargs) except RetryAfter as e: - pytest.xfail('Not waiting for flood control: {}'.format(e)) + pytest.xfail(f'Not waiting for flood control: {e}') Request._request_wrapper = patient_request_wrapper diff --git a/tests/conftest.py b/tests/conftest.py index 6afe0912a..aa1989866 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -336,6 +336,6 @@ def expect_bad_request(func, message, reason): return func() except BadRequest as e: if message in str(e): - pytest.xfail('{}. {}'.format(reason, e)) + pytest.xfail(f'{reason}. {e}') else: raise e diff --git a/tests/plugin_github_group.py b/tests/plugin_github_group.py index a4ec14973..e6f7cbdd6 100644 --- a/tests/plugin_github_group.py +++ b/tests/plugin_github_group.py @@ -26,7 +26,7 @@ def terminal_summary_wrapper(original, plugin_name): text = fold_plugins[plugin_name] def pytest_terminal_summary(terminalreporter): - terminalreporter.write('##[group] {}\n'.format(text)) + terminalreporter.write(f'##[group] {text}\n') original(terminalreporter) terminalreporter.write('##[endgroup]') @@ -68,7 +68,7 @@ def pytest_runtest_protocol(item, nextitem): if previous_name is None or previous_name != name: previous_name = name - terminal.write('\n##[group] {}'.format(name)) + terminal.write(f'\n##[group] {name}') yield diff --git a/tests/test_bot.py b/tests/test_bot.py index f12e51671..43dfc2b71 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -141,7 +141,7 @@ class TestBot: assert get_me_bot.can_join_groups == bot.can_join_groups assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages assert get_me_bot.supports_inline_queries == bot.supports_inline_queries - assert 'https://t.me/{}'.format(get_me_bot.username) == bot.link + assert f'https://t.me/{get_me_bot.username}' == bot.link assert commands == bot.commands @flaky(3, 1) @@ -949,7 +949,7 @@ class TestBot: chat = bot.get_chat(super_group_id) assert chat.type == 'supergroup' - assert chat.title == '>>> telegram.Bot(test) @{}'.format(bot.username) + assert chat.title == f'>>> telegram.Bot(test) @{bot.username}' assert chat.id == int(super_group_id) @flaky(3, 1) diff --git a/tests/test_chat.py b/tests/test_chat.py index 337c209c8..bc9481740 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -91,7 +91,7 @@ class TestChat: assert chat_dict['slow_mode_delay'] == chat.slow_mode_delay def test_link(self, chat): - assert chat.link == 'https://t.me/{}'.format(chat.username) + assert chat.link == f'https://t.me/{chat.username}' chat.username = None assert chat.link is None diff --git a/tests/test_commandhandler.py b/tests/test_commandhandler.py index e3d865ff1..6fbc79248 100644 --- a/tests/test_commandhandler.py +++ b/tests/test_commandhandler.py @@ -158,7 +158,7 @@ class TestCommandHandler(BaseTest): def ch_callback_args(self, bot, update, args): if update.message.text == self.CMD: self.test_flag = len(args) == 0 - elif update.message.text == '{}@{}'.format(self.CMD, bot.username): + elif update.message.text == f'{self.CMD}@{bot.username}': self.test_flag = len(args) == 0 else: self.test_flag = args == ['one', 'two'] @@ -175,8 +175,8 @@ class TestCommandHandler(BaseTest): assert self.response(dp, make_command_update(command)) assert not is_match(handler, make_command_update(command[1:])) - assert not is_match(handler, make_command_update('/not{}'.format(command[1:]))) - assert not is_match(handler, make_command_update('not {} at start'.format(command))) + assert not is_match(handler, make_command_update(f'/not{command[1:]}')) + assert not is_match(handler, make_command_update(f'not {command} at start')) @pytest.mark.parametrize( 'cmd', @@ -227,7 +227,7 @@ class TestCommandHandler(BaseTest): """Test the passing of arguments alongside a command""" handler = self.make_default_handler(self.ch_callback_args, pass_args=True) dp.add_handler(handler) - at_command = '{}@{}'.format(command, bot.username) + at_command = f'{command}@{bot.username}' assert self.response(dp, make_command_update(command)) assert self.response(dp, make_command_update(command + ' one two')) assert self.response(dp, make_command_update(at_command, bot=bot)) @@ -344,7 +344,7 @@ class TestPrefixHandler(BaseTest): assert self.response(dp, make_message_update(text)) assert not is_match(handler, make_message_update(command)) assert not is_match(handler, make_message_update(prefix + 'notacommand')) - assert not is_match(handler, make_command_update('not {} at start'.format(text))) + assert not is_match(handler, make_command_update(f'not {text} at start')) def test_single_multi_prefixes_commands(self, prefixes, commands, prefix_message_update): """Test various combinations of prefixes and commands""" diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 76c6fd9d4..e0de02598 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -278,7 +278,7 @@ class TestConversationHandler: assert list(value.keys())[0] == attr else: assert getattr(ch, attr) == attr - with pytest.raises(ValueError, match='You can not assign a new value to {}'.format(attr)): + with pytest.raises(ValueError, match=f'You can not assign a new value to {attr}'): setattr(ch, attr, True) def test_immutable_per_message(self): diff --git a/tests/test_dispatcher.py b/tests/test_dispatcher.py index 5fbce1486..3ce3f34c6 100644 --- a/tests/test_dispatcher.py +++ b/tests/test_dispatcher.py @@ -678,7 +678,7 @@ class TestDispatcher: thread_names = [thread.name for thread in getattr(dp2, '_Dispatcher__async_threads')] print(thread_names) for thread_name in thread_names: - assert thread_name.startswith("Bot:{}:worker:".format(dp2.bot.id)) + assert thread_name.startswith(f"Bot:{dp2.bot.id}:worker:") def test_non_context_deprecation(self, dp): with pytest.warns(TelegramDeprecationWarning): diff --git a/tests/test_helpers.py b/tests/test_helpers.py index 3ef327062..eda515fa5 100644 --- a/tests/test_helpers.py +++ b/tests/test_helpers.py @@ -183,16 +183,16 @@ class TestHelpers: username = 'JamesTheMock' payload = "hello" - expected = "https://t.me/{}?start={}".format(username, payload) + expected = f"https://t.me/{username}?start={payload}" actual = helpers.create_deep_linked_url(username, payload) assert expected == actual - expected = "https://t.me/{}?startgroup={}".format(username, payload) + expected = f"https://t.me/{username}?startgroup={payload}" actual = helpers.create_deep_linked_url(username, payload, group=True) assert expected == actual payload = "" - expected = "https://t.me/{}".format(username) + expected = f"https://t.me/{username}" assert expected == helpers.create_deep_linked_url(username) assert expected == helpers.create_deep_linked_url(username, payload) payload = None diff --git a/tests/test_inputmedia.py b/tests/test_inputmedia.py index 39609faaf..cfc274289 100644 --- a/tests/test_inputmedia.py +++ b/tests/test_inputmedia.py @@ -350,7 +350,7 @@ class TestSendMediaGroup: video_check = data[input_video.media.attach] == input_video.media.field_tuple thumb_check = data[input_video.thumb.attach] == input_video.thumb.field_tuple result = video_check and thumb_check - raise (Exception('Test was {}'.format('successful' if result else 'failing'))) + raise Exception(f"Test was {'successful' if result else 'failing'}") monkeypatch.setattr('telegram.utils.request.Request._request_wrapper', test) input_video = InputMediaVideo(video_file, thumb=photo_file) diff --git a/tests/test_message.py b/tests/test_message.py index ab25f4da5..7ad95a971 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -579,9 +579,7 @@ class TestMessage: def test_link_with_username(self, message, type): message.chat.username = 'username' message.chat.type = type - assert message.link == 'https://t.me/{}/{}'.format( - message.chat.username, message.message_id - ) + assert message.link == f'https://t.me/{message.chat.username}/{message.message_id}' @pytest.mark.parametrize( 'type, id', argvalues=[(Chat.CHANNEL, -1003), (Chat.SUPERGROUP, -1003)] @@ -591,7 +589,7 @@ class TestMessage: message.chat.id = id message.chat.type = type # The leading - for group ids/ -100 for supergroup ids isn't supposed to be in the link - assert message.link == 'https://t.me/c/{}/{}'.format(3, message.message_id) + assert message.link == f'https://t.me/c/{3}/{message.message_id}' @pytest.mark.parametrize('id, username', argvalues=[(None, 'username'), (-3, None)]) def test_link_private_chats(self, message, id, username): diff --git a/tests/test_official.py b/tests/test_official.py index 39f5864e3..b43b40aed 100644 --- a/tests/test_official.py +++ b/tests/test_official.py @@ -68,9 +68,7 @@ def check_method(h4): checked = [] for parameter in table: param = sig.parameters.get(parameter[0]) - assert param is not None, "Parameter {} not found in {}".format( - parameter[0], method.__name__ - ) + assert param is not None, f"Parameter {parameter[0]} not found in {method.__name__}" # TODO: Check type via docstring # TODO: Check if optional or required checked.append(parameter[0]) @@ -117,7 +115,7 @@ def check_object(h4): continue param = sig.parameters.get(field) - assert param is not None, "Attribute {} not found in {}".format(field, obj.__name__) + assert param is not None, f"Attribute {field} not found in {obj.__name__}" # TODO: Check type via docstring # TODO: Check if optional or required checked.append(field) diff --git a/tests/test_sticker.py b/tests/test_sticker.py index 047c8162e..3a1ceead9 100644 --- a/tests/test_sticker.py +++ b/tests/test_sticker.py @@ -258,7 +258,7 @@ class TestSticker: @pytest.fixture(scope='function') def sticker_set(bot): - ss = bot.get_sticker_set('test_by_{}'.format(bot.username)) + ss = bot.get_sticker_set(f'test_by_{bot.username}') if len(ss.stickers) > 100: try: for i in range(1, 50): @@ -270,7 +270,7 @@ def sticker_set(bot): @pytest.fixture(scope='function') def animated_sticker_set(bot): - ss = bot.get_sticker_set('animated_test_by_{}'.format(bot.username)) + ss = bot.get_sticker_set(f'animated_test_by_{bot.username}') if len(ss.stickers) > 100: try: for i in range(1, 50): @@ -295,7 +295,7 @@ class TestStickerSet: name = 'NOTAREALNAME' def test_de_json(self, bot, sticker): - name = 'test_by_{}'.format(bot.username) + name = f'test_by_{bot.username}' json_dict = { 'name': name, 'title': self.title, @@ -320,12 +320,12 @@ class TestStickerSet: file = bot.upload_sticker_file(95205500, f) assert file assert bot.add_sticker_to_set( - chat_id, 'test_by_{}'.format(bot.username), png_sticker=file.file_id, emojis='😄' + chat_id, f'test_by_{bot.username}', png_sticker=file.file_id, emojis='😄' ) # Also test with file input and mask assert bot.add_sticker_to_set( chat_id, - 'test_by_{}'.format(bot.username), + f'test_by_{bot.username}', png_sticker=sticker_file, emojis='😄', mask_position=MaskPosition(MaskPosition.EYES, -1, 1, 2), @@ -336,7 +336,7 @@ class TestStickerSet: def test_bot_methods_1_tgs(self, bot, chat_id): assert bot.add_sticker_to_set( chat_id, - 'animated_test_by_{}'.format(bot.username), + f'animated_test_by_{bot.username}', tgs_sticker=open('tests/data/telegram_animated_sticker.tgs', 'rb'), emojis='😄', ) @@ -368,7 +368,7 @@ class TestStickerSet: def test_bot_methods_3_png(self, bot, chat_id, sticker_set_thumb_file): sleep(1) assert bot.set_sticker_set_thumb( - 'test_by_{}'.format(bot.username), chat_id, sticker_set_thumb_file + f'test_by_{bot.username}', chat_id, sticker_set_thumb_file ) @flaky(10, 1) @@ -376,13 +376,11 @@ class TestStickerSet: def test_bot_methods_3_tgs(self, bot, chat_id, animated_sticker_file, animated_sticker_set): sleep(1) assert bot.set_sticker_set_thumb( - 'animated_test_by_{}'.format(bot.username), chat_id, animated_sticker_file + f'animated_test_by_{bot.username}', chat_id, animated_sticker_file ) file_id = animated_sticker_set.stickers[-1].file_id # also test with file input and mask - assert bot.set_sticker_set_thumb( - 'animated_test_by_{}'.format(bot.username), chat_id, file_id - ) + assert bot.set_sticker_set_thumb(f'animated_test_by_{bot.username}', chat_id, file_id) @flaky(10, 1) @pytest.mark.timeout(10) diff --git a/tests/test_updater.py b/tests/test_updater.py index 3da71945d..745836acd 100644 --- a/tests/test_updater.py +++ b/tests/test_updater.py @@ -134,7 +134,7 @@ class TestUpdater: pprint.pprint([rec.getMessage() for rec in caplog.get_records('call')]) assert any( - 'unhandled exception in Bot:{}:updater'.format(updater.bot.id) in rec.getMessage() + f'unhandled exception in Bot:{updater.bot.id}:updater' in rec.getMessage() for rec in caplog.get_records('call') ) @@ -487,7 +487,7 @@ class TestUpdater: if content_len is not None: headers['content-length'] = str(content_len) - url = 'http://{ip}:{port}/{path}'.format(ip=ip, port=port, path=url_path) + url = f'http://{ip}:{port}/{url_path}' req = Request(url, data=payload, headers=headers) @@ -512,7 +512,7 @@ class TestUpdater: updater.idle() rec = caplog.records[-2] - assert rec.getMessage().startswith('Received signal {}'.format(signal.SIGTERM)) + assert rec.getMessage().startswith(f'Received signal {signal.SIGTERM}') assert rec.levelname == 'INFO' rec = caplog.records[-1] diff --git a/tests/test_user.py b/tests/test_user.py index 15fc159df..a2155268d 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -123,7 +123,7 @@ class TestUser: assert user.full_name == u'first\u2022name' def test_link(self, user): - assert user.link == 'https://t.me/{}'.format(user.username) + assert user.link == f'https://t.me/{user.username}' user.username = None assert user.link is None