mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-12-22 22:45:09 +01:00
Improve Code Quality (#2450)
* chore: refactor code quality issues * Add comment for removing assert statements * Remove deepsource config file * Fix Coverage Co-authored-by: Hinrich Mahler <hinrich.mahler@freenet.de>
This commit is contained in:
parent
9949b44560
commit
9d93417d9a
20 changed files with 46 additions and 31 deletions
|
@ -13,7 +13,6 @@
|
||||||
# serve to show the default.
|
# serve to show the default.
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
import shlex
|
|
||||||
# import telegram
|
# import telegram
|
||||||
|
|
||||||
# If extensions (or modules to document with autodoc) are in another directory,
|
# If extensions (or modules to document with autodoc) are in another directory,
|
||||||
|
|
|
@ -34,7 +34,7 @@ def start(update: Update, _: CallbackContext) -> None:
|
||||||
"""Send a message when the command /start is issued."""
|
"""Send a message when the command /start is issued."""
|
||||||
user = update.effective_user
|
user = update.effective_user
|
||||||
update.message.reply_markdown_v2(
|
update.message.reply_markdown_v2(
|
||||||
f'Hi {user.mention_markdown_v2()}\!',
|
fr'Hi {user.mention_markdown_v2()}\!',
|
||||||
reply_markup=ForceReply(selective=True),
|
reply_markup=ForceReply(selective=True),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
2
setup.py
2
setup.py
|
@ -1,7 +1,5 @@
|
||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
"""The setup and build script for the python-telegram-bot library."""
|
"""The setup and build script for the python-telegram-bot library."""
|
||||||
|
|
||||||
import codecs
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
|
|
|
@ -76,7 +76,7 @@ class TelegramObject:
|
||||||
return json.dumps(self.to_dict())
|
return json.dumps(self.to_dict())
|
||||||
|
|
||||||
def to_dict(self) -> JSONDict:
|
def to_dict(self) -> JSONDict:
|
||||||
data = dict()
|
data = {}
|
||||||
|
|
||||||
for key in iter(self.__dict__):
|
for key in iter(self.__dict__):
|
||||||
if key == 'bot' or key.startswith('_'):
|
if key == 'bot' or key.startswith('_'):
|
||||||
|
|
|
@ -3457,7 +3457,10 @@ class Bot(TelegramObject):
|
||||||
data: JSONDict = {'shipping_query_id': shipping_query_id, 'ok': ok}
|
data: JSONDict = {'shipping_query_id': shipping_query_id, 'ok': ok}
|
||||||
|
|
||||||
if ok:
|
if ok:
|
||||||
assert shipping_options
|
if not shipping_options:
|
||||||
|
# not using an assert statement directly here since they are removed in
|
||||||
|
# the optimized bytecode
|
||||||
|
raise AssertionError
|
||||||
data['shipping_options'] = [option.to_dict() for option in shipping_options]
|
data['shipping_options'] = [option.to_dict() for option in shipping_options]
|
||||||
if error_message is not None:
|
if error_message is not None:
|
||||||
data['error_message'] = error_message
|
data['error_message'] = error_message
|
||||||
|
|
|
@ -354,9 +354,9 @@ class PrefixHandler(CommandHandler):
|
||||||
run_async: Union[bool, DefaultValue] = DEFAULT_FALSE,
|
run_async: Union[bool, DefaultValue] = DEFAULT_FALSE,
|
||||||
):
|
):
|
||||||
|
|
||||||
self._prefix: List[str] = list()
|
self._prefix: List[str] = []
|
||||||
self._command: List[str] = list()
|
self._command: List[str] = []
|
||||||
self._commands: List[str] = list()
|
self._commands: List[str] = []
|
||||||
|
|
||||||
super().__init__(
|
super().__init__(
|
||||||
'nocommand',
|
'nocommand',
|
||||||
|
|
|
@ -241,9 +241,9 @@ class ConversationHandler(Handler[Update]):
|
||||||
Set by dispatcher"""
|
Set by dispatcher"""
|
||||||
self._map_to_parent = map_to_parent
|
self._map_to_parent = map_to_parent
|
||||||
|
|
||||||
self.timeout_jobs: Dict[Tuple[int, ...], 'Job'] = dict()
|
self.timeout_jobs: Dict[Tuple[int, ...], 'Job'] = {}
|
||||||
self._timeout_jobs_lock = Lock()
|
self._timeout_jobs_lock = Lock()
|
||||||
self._conversations: ConversationDict = dict()
|
self._conversations: ConversationDict = {}
|
||||||
self._conversations_lock = Lock()
|
self._conversations_lock = Lock()
|
||||||
|
|
||||||
self.logger = logging.getLogger(__name__)
|
self.logger = logging.getLogger(__name__)
|
||||||
|
@ -257,7 +257,7 @@ class ConversationHandler(Handler[Update]):
|
||||||
"since message IDs are not globally unique."
|
"since message IDs are not globally unique."
|
||||||
)
|
)
|
||||||
|
|
||||||
all_handlers: List[Handler] = list()
|
all_handlers: List[Handler] = []
|
||||||
all_handlers.extend(entry_points)
|
all_handlers.extend(entry_points)
|
||||||
all_handlers.extend(fallbacks)
|
all_handlers.extend(fallbacks)
|
||||||
|
|
||||||
|
@ -407,7 +407,7 @@ class ConversationHandler(Handler[Update]):
|
||||||
chat = update.effective_chat
|
chat = update.effective_chat
|
||||||
user = update.effective_user
|
user = update.effective_user
|
||||||
|
|
||||||
key = list()
|
key = []
|
||||||
|
|
||||||
if self.per_chat:
|
if self.per_chat:
|
||||||
key.append(chat.id) # type: ignore[union-attr]
|
key.append(chat.id) # type: ignore[union-attr]
|
||||||
|
|
|
@ -511,7 +511,7 @@ class Dispatcher:
|
||||||
handler.conversations = self.persistence.get_conversations(handler.name)
|
handler.conversations = self.persistence.get_conversations(handler.name)
|
||||||
|
|
||||||
if group not in self.handlers:
|
if group not in self.handlers:
|
||||||
self.handlers[group] = list()
|
self.handlers[group] = []
|
||||||
self.groups.append(group)
|
self.groups.append(group)
|
||||||
self.groups = sorted(self.groups)
|
self.groups = sorted(self.groups)
|
||||||
|
|
||||||
|
|
|
@ -202,7 +202,7 @@ class Handler(Generic[UT], ABC):
|
||||||
check_result: The result from check_update
|
check_result: The result from check_update
|
||||||
|
|
||||||
"""
|
"""
|
||||||
optional_args: Dict[str, object] = dict()
|
optional_args: Dict[str, object] = {}
|
||||||
|
|
||||||
if self.pass_update_queue:
|
if self.pass_update_queue:
|
||||||
optional_args['update_queue'] = dispatcher.update_queue
|
optional_args['update_queue'] = dispatcher.update_queue
|
||||||
|
|
|
@ -106,7 +106,7 @@ class PicklePersistence(BasePersistence):
|
||||||
self.bot_data = data.get('bot_data', {})
|
self.bot_data = data.get('bot_data', {})
|
||||||
self.conversations = data['conversations']
|
self.conversations = data['conversations']
|
||||||
except OSError:
|
except OSError:
|
||||||
self.conversations = dict()
|
self.conversations = {}
|
||||||
self.user_data = defaultdict(dict)
|
self.user_data = defaultdict(dict)
|
||||||
self.chat_data = defaultdict(dict)
|
self.chat_data = defaultdict(dict)
|
||||||
self.bot_data = {}
|
self.bot_data = {}
|
||||||
|
@ -233,7 +233,7 @@ class PicklePersistence(BasePersistence):
|
||||||
new_state (:obj:`tuple` | :obj:`any`): The new state for the given key.
|
new_state (:obj:`tuple` | :obj:`any`): The new state for the given key.
|
||||||
"""
|
"""
|
||||||
if not self.conversations:
|
if not self.conversations:
|
||||||
self.conversations = dict()
|
self.conversations = {}
|
||||||
if self.conversations.setdefault(name, {}).get(key) == new_state:
|
if self.conversations.setdefault(name, {}).get(key) == new_state:
|
||||||
return
|
return
|
||||||
self.conversations[name][key] = new_state
|
self.conversations[name][key] = new_state
|
||||||
|
|
|
@ -83,7 +83,7 @@ class Game(TelegramObject):
|
||||||
self.photo = photo
|
self.photo = photo
|
||||||
# Optionals
|
# Optionals
|
||||||
self.text = text
|
self.text = text
|
||||||
self.text_entities = text_entities or list()
|
self.text_entities = text_entities or []
|
||||||
self.animation = animation
|
self.animation = animation
|
||||||
|
|
||||||
self._id_attrs = (self.title, self.description, self.photo)
|
self._id_attrs = (self.title, self.description, self.photo)
|
||||||
|
|
|
@ -438,12 +438,12 @@ class Message(TelegramObject):
|
||||||
self.reply_to_message = reply_to_message
|
self.reply_to_message = reply_to_message
|
||||||
self.edit_date = edit_date
|
self.edit_date = edit_date
|
||||||
self.text = text
|
self.text = text
|
||||||
self.entities = entities or list()
|
self.entities = entities or []
|
||||||
self.caption_entities = caption_entities or list()
|
self.caption_entities = caption_entities or []
|
||||||
self.audio = audio
|
self.audio = audio
|
||||||
self.game = game
|
self.game = game
|
||||||
self.document = document
|
self.document = document
|
||||||
self.photo = photo or list()
|
self.photo = photo or []
|
||||||
self.sticker = sticker
|
self.sticker = sticker
|
||||||
self.video = video
|
self.video = video
|
||||||
self.voice = voice
|
self.voice = voice
|
||||||
|
@ -452,10 +452,10 @@ class Message(TelegramObject):
|
||||||
self.contact = contact
|
self.contact = contact
|
||||||
self.location = location
|
self.location = location
|
||||||
self.venue = venue
|
self.venue = venue
|
||||||
self.new_chat_members = new_chat_members or list()
|
self.new_chat_members = new_chat_members or []
|
||||||
self.left_chat_member = left_chat_member
|
self.left_chat_member = left_chat_member
|
||||||
self.new_chat_title = new_chat_title
|
self.new_chat_title = new_chat_title
|
||||||
self.new_chat_photo = new_chat_photo or list()
|
self.new_chat_photo = new_chat_photo or []
|
||||||
self.delete_chat_photo = bool(delete_chat_photo)
|
self.delete_chat_photo = bool(delete_chat_photo)
|
||||||
self.group_chat_created = bool(group_chat_created)
|
self.group_chat_created = bool(group_chat_created)
|
||||||
self.supergroup_chat_created = bool(supergroup_chat_created)
|
self.supergroup_chat_created = bool(supergroup_chat_created)
|
||||||
|
|
|
@ -119,7 +119,7 @@ class Request:
|
||||||
read_timeout: float = 5.0,
|
read_timeout: float = 5.0,
|
||||||
):
|
):
|
||||||
if urllib3_proxy_kwargs is None:
|
if urllib3_proxy_kwargs is None:
|
||||||
urllib3_proxy_kwargs = dict()
|
urllib3_proxy_kwargs = {}
|
||||||
|
|
||||||
self._connect_timeout = connect_timeout
|
self._connect_timeout = connect_timeout
|
||||||
|
|
||||||
|
|
|
@ -1442,6 +1442,9 @@ class TestBot:
|
||||||
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
|
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
|
||||||
bot.answer_shipping_query(1, True)
|
bot.answer_shipping_query(1, True)
|
||||||
|
|
||||||
|
with pytest.raises(AssertionError):
|
||||||
|
bot.answer_shipping_query(1, True, shipping_options=[])
|
||||||
|
|
||||||
# TODO: Needs improvement. Need incoming pre checkout queries to test
|
# TODO: Needs improvement. Need incoming pre checkout queries to test
|
||||||
def test_answer_pre_checkout_query_ok(self, monkeypatch, bot):
|
def test_answer_pre_checkout_query_ok(self, monkeypatch, bot):
|
||||||
# For now just test that our internals pass the correct data
|
# For now just test that our internals pass the correct data
|
||||||
|
|
|
@ -213,7 +213,7 @@ class TestChat:
|
||||||
def make_assertion(*_, **kwargs):
|
def make_assertion(*_, **kwargs):
|
||||||
chat_id = kwargs['chat_id'] == chat.id
|
chat_id = kwargs['chat_id'] == chat.id
|
||||||
user_id = kwargs['user_id'] == 42
|
user_id = kwargs['user_id'] == 42
|
||||||
o_i_b = kwargs.get('only_if_banned', None) == only_if_banned
|
o_i_b = kwargs.get('only_if_banned') == only_if_banned
|
||||||
return chat_id and user_id and o_i_b
|
return chat_id and user_id and o_i_b
|
||||||
|
|
||||||
assert check_shortcut_signature(Chat.unban_member, Bot.unban_chat_member, ['chat_id'], [])
|
assert check_shortcut_signature(Chat.unban_member, Bot.unban_chat_member, ['chat_id'], [])
|
||||||
|
@ -228,7 +228,7 @@ class TestChat:
|
||||||
def make_assertion(*_, **kwargs):
|
def make_assertion(*_, **kwargs):
|
||||||
chat_id = kwargs['chat_id'] == chat.id
|
chat_id = kwargs['chat_id'] == chat.id
|
||||||
user_id = kwargs['user_id'] == 42
|
user_id = kwargs['user_id'] == 42
|
||||||
o_i_b = kwargs.get('is_anonymous', None) == is_anonymous
|
o_i_b = kwargs.get('is_anonymous') == is_anonymous
|
||||||
return chat_id and user_id and o_i_b
|
return chat_id and user_id and o_i_b
|
||||||
|
|
||||||
assert check_shortcut_signature(
|
assert check_shortcut_signature(
|
||||||
|
@ -246,7 +246,7 @@ class TestChat:
|
||||||
def make_assertion(*_, **kwargs):
|
def make_assertion(*_, **kwargs):
|
||||||
chat_id = kwargs['chat_id'] == chat.id
|
chat_id = kwargs['chat_id'] == chat.id
|
||||||
user_id = kwargs['user_id'] == 42
|
user_id = kwargs['user_id'] == 42
|
||||||
o_i_b = kwargs.get('permissions', None) == permissions
|
o_i_b = kwargs.get('permissions') == permissions
|
||||||
return chat_id and user_id and o_i_b
|
return chat_id and user_id and o_i_b
|
||||||
|
|
||||||
assert check_shortcut_signature(
|
assert check_shortcut_signature(
|
||||||
|
|
|
@ -79,7 +79,7 @@ class BaseTest:
|
||||||
|
|
||||||
def make_callback_for(self, pass_keyword):
|
def make_callback_for(self, pass_keyword):
|
||||||
def callback(bot, update, **kwargs):
|
def callback(bot, update, **kwargs):
|
||||||
self.test_flag = kwargs.get(keyword, None) is not None
|
self.test_flag = kwargs.get(keyword) is not None
|
||||||
|
|
||||||
keyword = pass_keyword[5:]
|
keyword = pass_keyword[5:]
|
||||||
return callback
|
return callback
|
||||||
|
|
|
@ -99,7 +99,7 @@ class TestConversationHandler:
|
||||||
def reset(self):
|
def reset(self):
|
||||||
self.raise_dp_handler_stop = False
|
self.raise_dp_handler_stop = False
|
||||||
self.test_flag = False
|
self.test_flag = False
|
||||||
self.current_state = dict()
|
self.current_state = {}
|
||||||
self.entry_points = [CommandHandler('start', self.start)]
|
self.entry_points = [CommandHandler('start', self.start)]
|
||||||
self.states = {
|
self.states = {
|
||||||
self.THIRSTY: [CommandHandler('brew', self.brew), CommandHandler('wait', self.start)],
|
self.THIRSTY: [CommandHandler('brew', self.brew), CommandHandler('wait', self.start)],
|
||||||
|
|
|
@ -569,7 +569,7 @@ class TestDispatcher:
|
||||||
self.store_bot_data = True
|
self.store_bot_data = True
|
||||||
|
|
||||||
def get_bot_data(self):
|
def get_bot_data(self):
|
||||||
return dict()
|
return {}
|
||||||
|
|
||||||
def update_bot_data(self, data):
|
def update_bot_data(self, data):
|
||||||
raise Exception
|
raise Exception
|
||||||
|
|
|
@ -131,7 +131,7 @@ class TestErrors:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def make_assertion(cls):
|
def make_assertion(cls):
|
||||||
assert {sc for sc in cls.__subclasses__()} == covered_subclasses[cls]
|
assert set(cls.__subclasses__()) == covered_subclasses[cls]
|
||||||
for subcls in cls.__subclasses__():
|
for subcls in cls.__subclasses__():
|
||||||
make_assertion(subcls)
|
make_assertion(subcls)
|
||||||
|
|
||||||
|
|
|
@ -960,10 +960,16 @@ class TestPickelPersistence:
|
||||||
assert not pickle_persistence.conversations['name1'] == conversation1
|
assert not pickle_persistence.conversations['name1'] == conversation1
|
||||||
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
||||||
assert pickle_persistence.conversations['name1'] == conversation1
|
assert pickle_persistence.conversations['name1'] == conversation1
|
||||||
|
assert pickle_persistence.get_conversations('name1') == conversation1
|
||||||
with open('pickletest_conversations', 'rb') as f:
|
with open('pickletest_conversations', 'rb') as f:
|
||||||
conversations_test = defaultdict(dict, pickle.load(f))
|
conversations_test = defaultdict(dict, pickle.load(f))
|
||||||
assert conversations_test['name1'] == conversation1
|
assert conversations_test['name1'] == conversation1
|
||||||
|
|
||||||
|
pickle_persistence.conversations = None
|
||||||
|
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
||||||
|
assert pickle_persistence.conversations['name1'] == {(123, 123): 5}
|
||||||
|
assert pickle_persistence.get_conversations('name1') == {(123, 123): 5}
|
||||||
|
|
||||||
def test_updating_single_file(self, pickle_persistence, good_pickle_files):
|
def test_updating_single_file(self, pickle_persistence, good_pickle_files):
|
||||||
pickle_persistence.single_file = True
|
pickle_persistence.single_file = True
|
||||||
|
|
||||||
|
@ -999,10 +1005,16 @@ class TestPickelPersistence:
|
||||||
assert not pickle_persistence.conversations['name1'] == conversation1
|
assert not pickle_persistence.conversations['name1'] == conversation1
|
||||||
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
||||||
assert pickle_persistence.conversations['name1'] == conversation1
|
assert pickle_persistence.conversations['name1'] == conversation1
|
||||||
|
assert pickle_persistence.get_conversations('name1') == conversation1
|
||||||
with open('pickletest', 'rb') as f:
|
with open('pickletest', 'rb') as f:
|
||||||
conversations_test = defaultdict(dict, pickle.load(f)['conversations'])
|
conversations_test = defaultdict(dict, pickle.load(f)['conversations'])
|
||||||
assert conversations_test['name1'] == conversation1
|
assert conversations_test['name1'] == conversation1
|
||||||
|
|
||||||
|
pickle_persistence.conversations = None
|
||||||
|
pickle_persistence.update_conversation('name1', (123, 123), 5)
|
||||||
|
assert pickle_persistence.conversations['name1'] == {(123, 123): 5}
|
||||||
|
assert pickle_persistence.get_conversations('name1') == {(123, 123): 5}
|
||||||
|
|
||||||
def test_save_on_flush_multi_files(self, pickle_persistence, good_pickle_files):
|
def test_save_on_flush_multi_files(self, pickle_persistence, good_pickle_files):
|
||||||
# Should run without error
|
# Should run without error
|
||||||
pickle_persistence.flush()
|
pickle_persistence.flush()
|
||||||
|
|
Loading…
Reference in a new issue