-
Notifications
You must be signed in to change notification settings - Fork 6k
Expand file tree
/
Copy pathtest_message.py
More file actions
3410 lines (3116 loc) · 131 KB
/
test_message.py
File metadata and controls
3410 lines (3116 loc) · 131 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2026
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import datetime as dtm
from copy import copy, deepcopy
from zoneinfo import ZoneInfo
import pytest
from telegram import (
Animation,
Audio,
BackgroundTypeChatTheme,
Bot,
Chat,
ChatBackground,
ChatBoostAdded,
ChatOwnerChanged,
ChatOwnerLeft,
ChatShared,
Checklist,
ChecklistTask,
ChecklistTasksAdded,
ChecklistTasksDone,
Contact,
Dice,
DirectMessagePriceChanged,
Document,
ExternalReplyInfo,
Game,
Gift,
GiftInfo,
Giveaway,
GiveawayCompleted,
GiveawayCreated,
GiveawayWinners,
InputChecklist,
InputChecklistTask,
InputPaidMediaPhoto,
Invoice,
LinkPreviewOptions,
Location,
Message,
MessageAutoDeleteTimerChanged,
MessageEntity,
MessageOriginChat,
PaidMediaInfo,
PaidMediaPreview,
PaidMessagePriceChanged,
PassportData,
PhotoSize,
Poll,
PollOption,
ProximityAlertTriggered,
RefundedPayment,
ReplyParameters,
SharedUser,
Sticker,
Story,
SuccessfulPayment,
SuggestedPostApprovalFailed,
SuggestedPostApproved,
SuggestedPostDeclined,
SuggestedPostInfo,
SuggestedPostPaid,
SuggestedPostPrice,
SuggestedPostRefunded,
TextQuote,
UniqueGift,
UniqueGiftBackdrop,
UniqueGiftBackdropColors,
UniqueGiftInfo,
UniqueGiftModel,
UniqueGiftSymbol,
Update,
User,
UsersShared,
Venue,
Video,
VideoChatEnded,
VideoChatParticipantsInvited,
VideoChatScheduled,
VideoChatStarted,
VideoNote,
Voice,
WebAppData,
)
from telegram._directmessagestopic import DirectMessagesTopic
from telegram._utils.datetime import UTC
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.types import ODVInput
from telegram.constants import ChatAction, ParseMode
from telegram.ext import Defaults
from telegram.warnings import PTBDeprecationWarning
from tests._passport.test_passport import RAW_PASSPORT_DATA
from tests.auxil.bot_method_checks import (
check_defaults_handling,
check_shortcut_call,
check_shortcut_signature,
)
from tests.auxil.build_messages import make_message
from tests.auxil.dummy_objects import get_dummy_object_json_dict
from tests.auxil.pytest_classes import PytestExtBot, PytestMessage
from tests.auxil.slots import mro_slots
@pytest.fixture
def message(bot):
message = PytestMessage(
message_id=MessageTestBase.id_,
date=MessageTestBase.date,
chat=copy(MessageTestBase.chat),
from_user=copy(MessageTestBase.from_user),
business_connection_id="123456789",
)
message.set_bot(bot)
message._unfreeze()
message.chat._unfreeze()
message.from_user._unfreeze()
return message
@pytest.fixture(
params=[
{
"reply_to_message": Message(
50, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
)
},
{"edit_date": dtm.datetime.utcnow()},
{
"text": "a text message",
"entities": [MessageEntity("bold", 10, 4), MessageEntity("italic", 16, 7)],
},
{
"caption": "A message caption",
"caption_entities": [MessageEntity("bold", 1, 1), MessageEntity("text_link", 4, 3)],
},
{"audio": Audio("audio_id", "unique_id", 12), "caption": "audio_file"},
{"document": Document("document_id", "unique_id"), "caption": "document_file"},
{
"animation": Animation("animation_id", "unique_id", 30, 30, 1),
"caption": "animation_file",
},
{
"game": Game(
"my_game",
"just my game",
[
PhotoSize("game_photo_id", "unique_id", 30, 30),
],
)
},
{"photo": [PhotoSize("photo_id", "unique_id", 50, 50)], "caption": "photo_file"},
{"sticker": Sticker("sticker_id", "unique_id", 50, 50, True, False, Sticker.REGULAR)},
{"story": Story(Chat(1, Chat.PRIVATE), 0)},
{"video": Video("video_id", "unique_id", 12, 12, 12), "caption": "video_file"},
{"voice": Voice("voice_id", "unique_id", 5)},
{"video_note": VideoNote("video_note_id", "unique_id", 20, 12)},
{"new_chat_members": [User(55, "new_user", False)]},
{"contact": Contact("phone_numner", "contact_name")},
{"location": Location(-23.691288, 46.788279)},
{"venue": Venue(Location(-23.691288, 46.788279), "some place", "right here")},
{"left_chat_member": User(33, "kicked", False)},
{"new_chat_title": "new title"},
{"new_chat_photo": [PhotoSize("photo_id", "unique_id", 50, 50)]},
{"delete_chat_photo": True},
{"group_chat_created": True},
{"supergroup_chat_created": True},
{"channel_chat_created": True},
{"message_auto_delete_timer_changed": MessageAutoDeleteTimerChanged(42)},
{"migrate_to_chat_id": -12345},
{"migrate_from_chat_id": -54321},
{
"pinned_message": Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
)
},
{"invoice": Invoice("my invoice", "invoice", "start", "EUR", 243)},
{
"successful_payment": SuccessfulPayment(
"EUR", 243, "payload", "charge_id", "provider_id", order_info={}
)
},
{"connected_website": "http://example.com/"},
{"author_signature": "some_author_sign"},
{
"photo": [PhotoSize("photo_id", "unique_id", 50, 50)],
"caption": "photo_file",
"media_group_id": 1234443322222,
},
{"passport_data": PassportData.de_json(RAW_PASSPORT_DATA, None)},
{
"poll": Poll(
id="abc",
question="What is this?",
options=[PollOption(text="a", voter_count=1), PollOption(text="b", voter_count=2)],
is_closed=False,
total_voter_count=0,
is_anonymous=False,
type=Poll.REGULAR,
allows_multiple_answers=True,
explanation_entities=[],
)
},
{
"text": "a text message",
"reply_markup": {
"inline_keyboard": [
[
{"text": "start", "url": "http://google.com"},
{"text": "next", "callback_data": "abcd"},
],
[{"text": "Cancel", "callback_data": "Cancel"}],
]
},
},
{"dice": Dice(4, "🎲")},
{"via_bot": User(9, "A_Bot", True)},
{
"proximity_alert_triggered": ProximityAlertTriggered(
User(1, "John", False), User(2, "Doe", False), 42
)
},
{"video_chat_scheduled": VideoChatScheduled(dtm.datetime.utcnow())},
{"video_chat_started": VideoChatStarted()},
{"video_chat_ended": VideoChatEnded(100)},
{
"video_chat_participants_invited": VideoChatParticipantsInvited(
[User(1, "Rem", False), User(2, "Emilia", False)]
)
},
{"sender_chat": Chat(-123, "discussion_channel")},
{"is_automatic_forward": True},
{"has_protected_content": True},
{
"entities": [
MessageEntity(MessageEntity.BOLD, 0, 1),
MessageEntity(MessageEntity.TEXT_LINK, 2, 3, url="https://ptb.org"),
]
},
{"web_app_data": WebAppData("some_data", "some_button_text")},
{"message_thread_id": 123},
{"users_shared": UsersShared(1, users=[SharedUser(2, "user2"), SharedUser(3, "user3")])},
{"chat_shared": ChatShared(3, 4)},
{
"gift": GiftInfo(
gift=Gift(
"gift_id",
Sticker("file_id", "file_unique_id", 512, 512, False, False, "regular"),
5,
)
)
},
{
"unique_gift": UniqueGiftInfo(
gift=UniqueGift(
gift_id="gift_id",
base_name="human_readable_name",
name="unique_name",
number=2,
model=UniqueGiftModel(
"model_name",
Sticker("file_id1", "file_unique_id1", 512, 512, False, False, "regular"),
10,
),
symbol=UniqueGiftSymbol(
"symbol_name",
Sticker("file_id2", "file_unique_id2", 512, 512, True, True, "mask"),
20,
),
backdrop=UniqueGiftBackdrop(
"backdrop_name",
UniqueGiftBackdropColors(0x00FF00, 0xEE00FF, 0xAA22BB, 0x20FE8F),
30,
),
),
origin=UniqueGiftInfo.UPGRADE,
owned_gift_id="id",
transfer_star_count=10,
)
},
{
"giveaway": Giveaway(
chats=[Chat(1, Chat.SUPERGROUP)],
winners_selection_date=dtm.datetime.utcnow().replace(microsecond=0),
winner_count=5,
)
},
{"giveaway_created": GiveawayCreated(prize_star_count=99)},
{
"giveaway_winners": GiveawayWinners(
chat=Chat(1, Chat.CHANNEL),
giveaway_message_id=123456789,
winners_selection_date=dtm.datetime.utcnow().replace(microsecond=0),
winner_count=42,
winners=[User(1, "user1", False), User(2, "user2", False)],
)
},
{
"giveaway_completed": GiveawayCompleted(
winner_count=42,
unclaimed_prize_count=4,
giveaway_message=make_message(text="giveaway_message"),
)
},
{
"link_preview_options": LinkPreviewOptions(
is_disabled=True,
url="https://python-telegram-bot.org",
prefer_small_media=True,
prefer_large_media=True,
show_above_text=True,
)
},
{
"external_reply": ExternalReplyInfo(
MessageOriginChat(dtm.datetime.utcnow(), Chat(1, Chat.PRIVATE))
)
},
{"quote": TextQuote("a text quote", 1)},
{"forward_origin": MessageOriginChat(dtm.datetime.utcnow(), Chat(1, Chat.PRIVATE))},
{"reply_to_story": Story(Chat(1, Chat.PRIVATE), 0)},
{"boost_added": ChatBoostAdded(100)},
{"sender_boost_count": 1},
{"is_from_offline": True},
{"sender_business_bot": User(1, "BusinessBot", True)},
{"business_connection_id": "123456789"},
{"chat_background_set": ChatBackground(type=BackgroundTypeChatTheme("ice"))},
{"effect_id": "123456789"},
{"show_caption_above_media": True},
{"paid_media": PaidMediaInfo(5, [PaidMediaPreview(10, 10, 10)])},
{"refunded_payment": RefundedPayment("EUR", 243, "payload", "charge_id", "provider_id")},
{"paid_star_count": 291},
{"paid_message_price_changed": PaidMessagePriceChanged(291)},
{"direct_message_price_changed": DirectMessagePriceChanged(True, 100)},
{
"checklist": Checklist(
"checklist_id",
tasks=[ChecklistTask(id=42, text="task 1"), ChecklistTask(id=43, text="task 2")],
)
},
{
"checklist_tasks_done": ChecklistTasksDone(
marked_as_done_task_ids=[1, 2, 3],
marked_as_not_done_task_ids=[4, 5],
)
},
{
"checklist_tasks_added": ChecklistTasksAdded(
tasks=[ChecklistTask(id=42, text="task 1"), ChecklistTask(id=43, text="task 2")],
)
},
{"is_paid_post": True},
{
"direct_messages_topic": DirectMessagesTopic(
topic_id=1234,
user=User(id=5678, first_name="TestUser", is_bot=False),
)
},
{"reply_to_checklist_task_id": 11},
{
"suggested_post_declined": SuggestedPostDeclined(
suggested_post_message=Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
),
comment="comment",
)
},
{
"suggested_post_paid": SuggestedPostPaid(
currency="XTR",
suggested_post_message=Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
),
amount=100,
)
},
{
"suggested_post_refunded": SuggestedPostRefunded(
reason="post_deleted",
suggested_post_message=Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
),
)
},
{
"suggested_post_approved": SuggestedPostApproved(
send_date=dtm.datetime.utcnow(),
price=SuggestedPostPrice(currency="XTR", amount=100),
suggested_post_message=Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
),
)
},
{
"suggested_post_approval_failed": SuggestedPostApprovalFailed(
price=SuggestedPostPrice(currency="XTR", amount=100),
suggested_post_message=Message(
7, dtm.datetime.utcnow(), Chat(13, "channel"), User(9, "i", False)
),
)
},
{
"suggested_post_info": SuggestedPostInfo(
state="pending",
price=SuggestedPostPrice(currency="XTR", amount=100),
send_date=dtm.datetime.utcnow(),
)
},
{
"gift_upgrade_sent": GiftInfo(
gift=Gift(
"gift_id",
Sticker("file_id", "file_unique_id", 512, 512, False, False, "regular"),
5,
)
)
},
{"chat_owner_changed": ChatOwnerChanged(new_owner=User(4, "Snow", False))},
{"chat_owner_left": ChatOwnerLeft(new_owner=User(5, "Crash", False))},
{"sender_tag": "This is a tag"},
],
ids=[
"reply",
"edited",
"text",
"caption_entities",
"audio",
"document",
"animation",
"game",
"photo",
"sticker",
"story",
"video",
"voice",
"video_note",
"new_members",
"contact",
"location",
"venue",
"left_member",
"new_title",
"new_photo",
"delete_photo",
"group_created",
"supergroup_created",
"channel_created",
"message_auto_delete_timer_changed",
"migrated_to",
"migrated_from",
"pinned",
"invoice",
"successful_payment",
"connected_website",
"author_signature",
"photo_from_media_group",
"passport_data",
"poll",
"reply_markup",
"dice",
"via_bot",
"proximity_alert_triggered",
"video_chat_scheduled",
"video_chat_started",
"video_chat_ended",
"video_chat_participants_invited",
"sender_chat",
"is_automatic_forward",
"has_protected_content",
"entities",
"web_app_data",
"message_thread_id",
"users_shared",
"chat_shared",
"gift",
"unique_gift",
"giveaway",
"giveaway_created",
"giveaway_winners",
"giveaway_completed",
"link_preview_options",
"external_reply",
"quote",
"forward_origin",
"reply_to_story",
"boost_added",
"sender_boost_count",
"sender_business_bot",
"business_connection_id",
"is_from_offline",
"chat_background_set",
"effect_id",
"show_caption_above_media",
"paid_media",
"refunded_payment",
"paid_star_count",
"paid_message_price_changed",
"direct_message_price_changed",
"checklist",
"checklist_tasks_done",
"checklist_tasks_added",
"is_paid_post",
"direct_messages_topic",
"reply_to_checklist_task_id",
"suggested_post_declined",
"suggested_post_paid",
"suggested_post_refunded",
"suggested_post_approved",
"suggested_post_approval_failed",
"suggested_post_info",
"gift_upgrade_sent",
"chat_owner_changed",
"chat_owner_left",
"sender_tag",
],
)
def message_params(bot, request):
message = Message(
message_id=MessageTestBase.id_,
from_user=MessageTestBase.from_user,
date=MessageTestBase.date,
chat=MessageTestBase.chat,
**request.param,
)
message.set_bot(bot)
return message
class MessageTestBase:
id_ = 1
from_user = User(2, "testuser", False)
date = dtm.datetime.utcnow()
chat = Chat(3, "private")
test_entities = [
{"length": 4, "offset": 10, "type": "bold"},
{"length": 3, "offset": 16, "type": "italic"},
{"length": 3, "offset": 20, "type": "italic"},
{"length": 4, "offset": 25, "type": "code"},
{"length": 5, "offset": 31, "type": "text_link", "url": "http://github.com/ab_"},
{
"length": 12,
"offset": 38,
"type": "text_mention",
"user": User(123456789, "mentioned user", False),
},
{"length": 3, "offset": 55, "type": "pre", "language": "python"},
{"length": 21, "offset": 60, "type": "url"},
]
test_text = "Test for <bold, ita_lic, code, links, text-mention and pre. http://google.com/ab_"
test_entities_v2 = [
{"length": 4, "offset": 0, "type": "underline"},
{"length": 4, "offset": 10, "type": "bold"},
{"length": 7, "offset": 16, "type": "italic"},
{"length": 6, "offset": 25, "type": "code"},
{"length": 5, "offset": 33, "type": "text_link", "url": r"http://github.com/abc\)def"},
{
"length": 12,
"offset": 40,
"type": "text_mention",
"user": User(123456789, "mentioned user", False),
},
{"length": 5, "offset": 57, "type": "pre"},
{"length": 17, "offset": 64, "type": "url"},
{"length": 41, "offset": 86, "type": "italic"},
{"length": 29, "offset": 91, "type": "bold"},
{"length": 9, "offset": 101, "type": "strikethrough"},
{"length": 10, "offset": 129, "type": "pre", "language": "python"},
{"length": 7, "offset": 141, "type": "spoiler"},
{"length": 2, "offset": 150, "type": "custom_emoji", "custom_emoji_id": "1"},
{"length": 34, "offset": 154, "type": "blockquote"},
{"length": 6, "offset": 181, "type": "bold"},
{"length": 33, "offset": 190, "type": "expandable_blockquote"},
{"length": 4, "offset": 224, "type": "date_time", "unix_time": dtm.datetime(2000, 7, 28)},
{
"length": 14,
"offset": 229,
"type": "date_time",
"unix_time": dtm.datetime(2000, 7, 28, tzinfo=ZoneInfo("Europe/Berlin")),
"date_time_format": "r",
},
]
test_text_v2 = (
r"Test for <bold, ita_lic, \`code, links, text-mention and `\pre. "
"http://google.com and bold nested in strk>trgh nested in italic. Python pre. Spoiled. "
"👍.\nMultiline\nblock quote\nwith nested.\n\nMultiline\nexpandable\nblock quote.\ntime"
"\ntime_formatted\n"
)
test_message = Message(
message_id=1,
from_user=None,
date=None,
chat=None,
text=test_text,
entities=[MessageEntity(**e) for e in test_entities],
caption=test_text,
caption_entities=[MessageEntity(**e) for e in test_entities],
)
test_message_v2 = Message(
message_id=1,
from_user=None,
date=None,
chat=None,
text=test_text_v2,
entities=[MessageEntity(**e) for e in test_entities_v2],
caption=test_text_v2,
caption_entities=[MessageEntity(**e) for e in test_entities_v2],
)
class TestMessageWithoutRequest(MessageTestBase):
async def check_quote_parsing(
self, message: Message, method, bot_method_name: str, args, monkeypatch
):
"""Used in testing reply_* below. Makes sure that do_quote is handled correctly"""
with pytest.raises(
ValueError,
match="`reply_to_message_id` and `reply_parameters` are mutually exclusive\\.",
):
await method(*args, reply_to_message_id=42, reply_parameters=42)
with pytest.raises(
ValueError,
match="`allow_sending_without_reply` and `reply_parameters` are mutually exclusive\\.",
):
await method(*args, allow_sending_without_reply=True, reply_parameters=42)
async def make_assertion(*args, **kwargs):
return kwargs.get("chat_id"), kwargs.get("reply_parameters")
monkeypatch.setattr(message.get_bot(), bot_method_name, make_assertion)
for aswr in (DEFAULT_NONE, True):
await self._check_quote_parsing(
message=message,
method=method,
bot_method_name=bot_method_name,
args=args,
monkeypatch=monkeypatch,
aswr=aswr,
)
@staticmethod
async def _check_quote_parsing(
message: Message, method, bot_method_name: str, args, monkeypatch, aswr
):
# test that boolean input for do_quote is parse correctly
for value in (True, False):
chat_id, reply_parameters = await method(
*args, do_quote=value, allow_sending_without_reply=aswr
)
if chat_id != message.chat.id:
pytest.fail(f"chat_id is {chat_id} but should be {message.chat.id}")
expected = (
ReplyParameters(message.message_id, allow_sending_without_reply=aswr)
if value
else None
)
if reply_parameters != expected:
pytest.fail(f"reply_parameters is {reply_parameters} but should be {expected}")
# test that dict input for do_quote is parsed correctly
input_chat_id = object()
input_reply_parameters = ReplyParameters(message_id=1, chat_id=42)
coro = method(
*args,
do_quote={"chat_id": input_chat_id, "reply_parameters": input_reply_parameters},
allow_sending_without_reply=aswr,
)
if aswr is True:
with pytest.raises(
ValueError,
match="`allow_sending_without_reply` and `dict`-value input",
):
await coro
else:
chat_id, reply_parameters = await coro
if chat_id is not input_chat_id:
pytest.fail(f"chat_id is {chat_id} but should be {input_chat_id}")
if reply_parameters is not input_reply_parameters:
pytest.fail(
f"reply_parameters is {reply_parameters} "
f"but should be {input_reply_parameters}"
)
# test that do_quote input is overridden by reply_parameters
input_parameters_2 = ReplyParameters(
message_id=message.message_id + 1, chat_id=message.chat_id + 1
)
chat_id, reply_parameters = await method(
*args,
reply_parameters=input_parameters_2,
# passing these here to make sure that `reply_parameters` has higher priority
do_quote={"chat_id": input_chat_id, "reply_parameters": input_reply_parameters},
)
if chat_id is not message.chat.id:
pytest.fail(f"chat_id is {chat_id} but should be {message.chat.id}")
if reply_parameters is not input_parameters_2:
pytest.fail(
f"reply_parameters is {reply_parameters} but should be {input_parameters_2}"
)
# test that do_quote input is overridden by reply_to_message_id
chat_id, reply_parameters = await method(
*args,
reply_to_message_id=42,
# passing these here to make sure that `reply_to_message_id` has higher priority
do_quote={"chat_id": input_chat_id, "reply_parameters": input_reply_parameters},
allow_sending_without_reply=aswr,
)
if chat_id != message.chat.id:
pytest.fail(f"chat_id is {chat_id} but should be {message.chat.id}")
if reply_parameters is None or reply_parameters.message_id != 42:
pytest.fail(f"reply_parameters is {reply_parameters} but should be 42")
if reply_parameters is None or reply_parameters.allow_sending_without_reply != aswr:
pytest.fail(
f"reply_parameters.allow_sending_without_reply is "
f"{reply_parameters.allow_sending_without_reply} it should be {aswr}"
)
@staticmethod
async def check_thread_id_parsing(
message: Message, method, bot_method_name: str, args, monkeypatch
):
"""Used in testing reply_* below. Makes sure that meassage_thread_id is parsed
correctly."""
async def extract_message_thread_id(*args, **kwargs):
return kwargs.get("message_thread_id")
monkeypatch.setattr(message.get_bot(), bot_method_name, extract_message_thread_id)
for is_topic_message in (True, False):
message.is_topic_message = is_topic_message
message.message_thread_id = None
message_thread_id = await method(*args)
assert message_thread_id is None
message.message_thread_id = 99
message_thread_id = await method(*args)
assert message_thread_id == (99 if is_topic_message else None)
message_thread_id = await method(*args, message_thread_id=50)
assert message_thread_id == 50
message_thread_id = await method(*args, message_thread_id=None)
assert message_thread_id is None
# These methods do not accept `do_quote` as passed below
if bot_method_name in ["send_chat_action", "send_message_draft"]:
return
message_thread_id = await method(
*args,
do_quote=message.build_reply_arguments(
target_chat_id=123,
),
)
assert message_thread_id is None
for target_chat_id in (message.chat_id, message.chat.username):
message_thread_id = await method(
*args,
do_quote=message.build_reply_arguments(
target_chat_id=target_chat_id,
),
)
assert message_thread_id == (message.message_thread_id if is_topic_message else None)
def test_slot_behaviour(self):
message = Message(
message_id=MessageTestBase.id_,
date=MessageTestBase.date,
chat=copy(MessageTestBase.chat),
from_user=copy(MessageTestBase.from_user),
)
for attr in message.__slots__:
assert getattr(message, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(message)) == len(set(mro_slots(message))), "duplicate slot"
def test_all_possibilities_de_json_and_to_dict(self, offline_bot, message_params):
new = Message.de_json(message_params.to_dict(), offline_bot)
assert new.api_kwargs == {}
assert new.to_dict() == message_params.to_dict()
# Checking that none of the attributes are dicts is a best effort approach to ensure that
# de_json converts everything to proper classes without having to write special tests for
# every single case
for slot in new.__slots__:
assert not isinstance(new[slot], dict)
def test_de_json_localization(self, offline_bot, raw_bot, tz_bot):
json_dict = {
"message_id": 12,
"from_user": get_dummy_object_json_dict("User"),
"date": int(dtm.datetime.now().timestamp()),
"chat": get_dummy_object_json_dict("Chat"),
"edit_date": int(dtm.datetime.now().timestamp()),
}
message_raw = Message.de_json(json_dict, raw_bot)
message_bot = Message.de_json(json_dict, offline_bot)
message_tz = Message.de_json(json_dict, tz_bot)
# comparing utcoffsets because comparing timezones is unpredicatable
date_offset = message_tz.date.utcoffset()
date_tz_bot_offset = tz_bot.defaults.tzinfo.utcoffset(message_tz.date.replace(tzinfo=None))
edit_date_offset = message_tz.edit_date.utcoffset()
edit_date_tz_bot_offset = tz_bot.defaults.tzinfo.utcoffset(
message_tz.edit_date.replace(tzinfo=None)
)
assert message_raw.date.tzinfo == UTC
assert message_bot.date.tzinfo == UTC
assert date_offset == date_tz_bot_offset
assert message_raw.edit_date.tzinfo == UTC
assert message_bot.edit_date.tzinfo == UTC
assert edit_date_offset == edit_date_tz_bot_offset
def test_de_json_api_kwargs_backward_compatibility(self, offline_bot, message_params):
message_dict = message_params.to_dict()
keys = (
"user_shared",
"forward_from",
"forward_from_chat",
"forward_from_message_id",
"forward_signature",
"forward_sender_name",
"forward_date",
)
for key in keys:
message_dict[key] = key
message = Message.de_json(message_dict, offline_bot)
assert message.api_kwargs == {key: key for key in keys}
def test_equality(self):
id_ = 1
a = Message(id_, self.date, self.chat, from_user=self.from_user)
b = Message(id_, self.date, self.chat, from_user=self.from_user)
c = Message(id_, self.date, Chat(123, Chat.GROUP), from_user=User(0, "", False))
d = Message(0, self.date, self.chat, from_user=self.from_user)
e = Update(id_)
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a != c
assert hash(a) != hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)
def test_bool(self, message, recwarn):
# Relevant as long as we override MaybeInaccessibleMessage.__bool__
# Can be removed once that's removed
assert bool(message) is True
assert len(recwarn) == 0
async def test_parse_entity(self):
text = (
b"\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467"
b"\\u200d\\U0001f467\\U0001f431http://google.com"
).decode("unicode-escape")
entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
message = Message(
1,
from_user=self.from_user,
date=self.date,
chat=self.chat,
text=text,
entities=[entity],
)
assert message.parse_entity(entity) == "http://google.com"
with pytest.raises(RuntimeError, match="Message has no"):
Message(message_id=1, date=self.date, chat=self.chat).parse_entity(entity)
async def test_parse_caption_entity(self):
caption = (
b"\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467"
b"\\u200d\\U0001f467\\U0001f431http://google.com"
).decode("unicode-escape")
entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
message = Message(
1,
from_user=self.from_user,
date=self.date,
chat=self.chat,
caption=caption,
caption_entities=[entity],
)
assert message.parse_caption_entity(entity) == "http://google.com"
with pytest.raises(RuntimeError, match="Message has no"):
Message(message_id=1, date=self.date, chat=self.chat).parse_entity(entity)
async def test_parse_entities(self):
text = (
b"\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467"
b"\\u200d\\U0001f467\\U0001f431http://google.com"
).decode("unicode-escape")
entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
message = Message(
1,
from_user=self.from_user,
date=self.date,
chat=self.chat,
text=text,
entities=[entity_2, entity],
)
assert message.parse_entities(MessageEntity.URL) == {entity: "http://google.com"}
assert message.parse_entities() == {entity: "http://google.com", entity_2: "h"}
async def test_parse_caption_entities(self):
text = (
b"\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467"
b"\\u200d\\U0001f467\\U0001f431http://google.com"
).decode("unicode-escape")
entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
message = Message(
1,
from_user=self.from_user,
date=self.date,
chat=self.chat,
caption=text,
caption_entities=[entity_2, entity],
)
assert message.parse_caption_entities(MessageEntity.URL) == {entity: "http://google.com"}
assert message.parse_caption_entities() == {
entity: "http://google.com",
entity_2: "h",
}
def test_text_html_simple(self):
test_html_string = (
"<u>Test</u> for <<b>bold</b>, <i>ita_lic</i>, "
r"<code>\`code</code>, "
r'<a href="http://github.com/abc\)def">links</a>, '
'<a href="tg://user?id=123456789">text-mention</a> and '
r"<pre>`\pre</pre>. http://google.com "
"and <i>bold <b>nested in <s>strk>trgh</s> nested in</b> italic</i>. "
'<pre><code class="python">Python pre</code></pre>. '
'<span class="tg-spoiler">Spoiled</span>. '
'<tg-emoji emoji-id="1">👍</tg-emoji>.\n'
"<blockquote>Multiline\nblock quote\nwith <b>nested</b>.</blockquote>\n\n"
"<blockquote expandable>Multiline\nexpandable\nblock quote.</blockquote>\n"
'<tg-time unix="964742400">time</tg-time>\n'
'<tg-time unix="964735200" format="r">time_formatted</tg-time>\n'
)
text_html = self.test_message_v2.text_html
assert text_html == test_html_string
def test_text_html_empty(self, message):
message.text = None
message.caption = "test"
assert message.text_html is None
def test_text_html_urled(self):
test_html_string = (
"<u>Test</u> for <<b>bold</b>, <i>ita_lic</i>, "
r"<code>\`code</code>, "
r'<a href="http://github.com/abc\)def">links</a>, '
'<a href="tg://user?id=123456789">text-mention</a> and '
r'<pre>`\pre</pre>. <a href="http://google.com">http://google.com</a> '
"and <i>bold <b>nested in <s>strk>trgh</s> nested in</b> italic</i>. "
'<pre><code class="python">Python pre</code></pre>. '
'<span class="tg-spoiler">Spoiled</span>. '
'<tg-emoji emoji-id="1">👍</tg-emoji>.\n'
"<blockquote>Multiline\nblock quote\nwith <b>nested</b>.</blockquote>\n\n"
"<blockquote expandable>Multiline\nexpandable\nblock quote.</blockquote>\n"
'<tg-time unix="964742400">time</tg-time>\n'
'<tg-time unix="964735200" format="r">time_formatted</tg-time>\n'
)
text_html = self.test_message_v2.text_html_urled