Fix a Bug in ChatMemberUpdated.difference (#2947)

This commit is contained in:
Bibo-Joshi 2022-04-27 21:54:57 +02:00 committed by Hinrich Mahler
parent 97281da351
commit 36888a7c47
2 changed files with 33 additions and 5 deletions

View file

@ -125,6 +125,19 @@ class ChatMemberUpdated(TelegramObject):
return data
def _get_attribute_difference(self, attribute: str) -> Tuple[object, object]:
try:
old = self.old_chat_member[attribute]
except KeyError:
old = None
try:
new = self.new_chat_member[attribute]
except KeyError:
new = None
return old, new
def difference(
self,
) -> Dict[
@ -162,10 +175,7 @@ class ChatMemberUpdated(TelegramObject):
# we can't directly use the values from old_dict ^ new_dict b/c that set is unordered
attributes = (entry[0] for entry in set(old_dict.items()) ^ set(new_dict.items()))
result = {
attribute: (self.old_chat_member[attribute], self.new_chat_member[attribute])
for attribute in attributes
}
result = {attribute: self._get_attribute_difference(attribute) for attribute in attributes}
if old_user_dict != new_user_dict:
result['user'] = (self.old_chat_member.user, self.new_chat_member.user)

View file

@ -29,6 +29,8 @@ from telegram import (
Chat,
ChatMemberUpdated,
ChatInviteLink,
ChatMemberOwner,
ChatMemberBanned,
)
from telegram._utils.datetime import to_timestamp
@ -210,7 +212,7 @@ class TestChatMemberUpdated:
)
assert chat_member_updated.difference() == {'status': ('old_status', 'new_status')}
# We deliberately change an optional argument here to make sure that comparision doesn't
# We deliberately change an optional argument here to make sure that comparison doesn't
# just happens by id/required args
new_user = User(1, 'First name', False, last_name='last name')
new_chat_member.user = new_user
@ -239,3 +241,19 @@ class TestChatMemberUpdated:
chat, user, datetime.datetime.utcnow(), old_chat_member, new_chat_member
)
assert chat_member_updated.difference() == {optional_attribute: (old_value, new_value)}
def test_difference_different_classes(self, user, chat):
old_chat_member = ChatMemberOwner(user=user, is_anonymous=False)
new_chat_member = ChatMemberBanned(user=user, until_date=datetime.datetime(2021, 1, 1))
chat_member_updated = ChatMemberUpdated(
chat=chat,
from_user=user,
date=datetime.datetime.utcnow(),
old_chat_member=old_chat_member,
new_chat_member=new_chat_member,
)
diff = chat_member_updated.difference()
assert diff.pop('is_anonymous') == (False, None)
assert diff.pop('until_date') == (None, datetime.datetime(2021, 1, 1))
assert diff.pop('status') == (ChatMember.CREATOR, ChatMember.KICKED)
assert diff == {}