/
test_bot.py
3251 lines (2832 loc) · 130 KB
/
test_bot.py
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-2022
# 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 asyncio
import copy
import datetime as dtm
import inspect
import logging
import pickle
import re
import socket
import sys
import time
from collections import defaultdict
import pytest
from telegram import (
Bot,
BotCommand,
BotCommandScopeChat,
CallbackQuery,
Chat,
ChatAdministratorRights,
ChatPermissions,
Dice,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultDocument,
InlineQueryResultVoice,
InputFile,
InputMessageContent,
InputTextMessageContent,
LabeledPrice,
MenuButton,
MenuButtonCommands,
MenuButtonDefault,
MenuButtonWebApp,
Message,
MessageEntity,
Poll,
PollOption,
SentWebAppMessage,
ShippingOption,
Update,
User,
WebAppInfo,
)
from telegram._utils.datetime import UTC, from_timestamp, to_timestamp
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram.constants import (
ChatAction,
InlineQueryLimit,
InlineQueryResultType,
MenuButtonType,
ParseMode,
)
from telegram.error import BadRequest, InvalidToken, NetworkError
from telegram.ext import ExtBot, InvalidCallbackData
from telegram.helpers import escape_markdown
from telegram.request import BaseRequest, HTTPXRequest, RequestData
from tests.auxil.bot_method_checks import check_defaults_handling
from tests.bots import FALLBACKS
from tests.conftest import GITHUB_ACTION, data_file, expect_bad_request, make_bot
def to_camel_case(snake_str):
"""https://stackoverflow.com/a/19053800"""
components = snake_str.split("_")
# We capitalize the first letter of each component except the first one
# with the 'title' method and join them together.
return components[0] + "".join(x.title() for x in components[1:])
@pytest.fixture(scope="class")
async def message(bot, chat_id):
to_reply_to = await bot.send_message(
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
)
out = await bot.send_message(
chat_id,
"Text",
reply_to_message_id=to_reply_to.message_id,
disable_web_page_preview=True,
disable_notification=True,
)
out._unfreeze()
return out
@pytest.fixture(scope="class")
async def media_message(bot, chat_id):
with data_file("telegram.ogg").open("rb") as f:
return await bot.send_voice(chat_id, voice=f, caption="my caption", read_timeout=10)
@pytest.fixture(scope="class")
def chat_permissions():
return ChatPermissions(can_send_messages=False, can_change_info=False, can_invite_users=False)
def inline_results_callback(page=None):
if not page:
return [InlineQueryResultArticle(i, str(i), None) for i in range(1, 254)]
if page <= 5:
return [
InlineQueryResultArticle(i, str(i), None)
for i in range(page * 5 + 1, (page + 1) * 5 + 1)
]
return None
@pytest.fixture(scope="class")
def inline_results():
return inline_results_callback()
BASE_GAME_SCORE = 60 # Base game score for game tests
xfail = pytest.mark.xfail(
bool(GITHUB_ACTION), # This condition is only relevant for github actions game tests.
reason="Can fail due to race conditions when multiple test suites "
"with the same bot token are run at the same time",
)
def bot_methods(ext_bot=True):
arg_values = []
ids = []
non_api_methods = [
"de_json",
"de_list",
"to_dict",
"to_json",
"parse_data",
"get_bot",
"set_bot",
"initialize",
"shutdown",
"insert_callback_data",
]
classes = (Bot, ExtBot) if ext_bot else (Bot,)
for cls in classes:
for name, attribute in inspect.getmembers(cls, predicate=inspect.isfunction):
if name.startswith("_") or name in non_api_methods:
continue
arg_values.append((cls, name, attribute))
ids.append(f"{cls.__name__}.{name}")
return pytest.mark.parametrize(
argnames="bot_class, bot_method_name,bot_method", argvalues=arg_values, ids=ids
)
class InputMessageContentDWPP(InputMessageContent):
"""
This is here to cover the case of InputMediaContent classes in testing answer_ilq that have
`disable_web_page_preview` but not `parse_mode`. Unlikely to ever happen, but better be save
than sorry …
"""
__slots__ = ("disable_web_page_preview", "parse_mode", "entities", "message_text")
def __init__(
self,
message_text: str,
disable_web_page_preview=DEFAULT_NONE,
*,
api_kwargs=None,
):
super().__init__(api_kwargs=api_kwargs)
self._unfreeze()
self.message_text = message_text
self.disable_web_page_preview = disable_web_page_preview
class TestBot:
"""
Most are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
Behavior for init of ExtBot with missing optional dependency cachetools (for CallbackDataCache)
is tested in `test_callbackdatacache`
"""
@staticmethod
def localize(dt, tzinfo):
try:
return tzinfo.localize(dt)
except AttributeError:
# We get here if tzinfo is not a pytz timezone but a datetime.timezone class
# This test class should never be run in if pytz is not installed, we intentionally
# fail if this branch is ever reached.
sys.exit(1)
test_flag = None
@pytest.fixture(scope="function", autouse=True)
def reset(self):
self.test_flag = None
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
def test_slot_behaviour(self, bot_class, bot, mro_slots):
inst = bot_class(bot.token)
for attr in inst.__slots__:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
async def test_initialize_and_shutdown(self, bot, monkeypatch):
async def initialize(*args, **kwargs):
self.test_flag = ["initialize"]
async def stop(*args, **kwargs):
self.test_flag.append("stop")
temp_bot = Bot(token=bot.token)
orig_stop = temp_bot.request.shutdown
try:
monkeypatch.setattr(temp_bot.request, "initialize", initialize)
monkeypatch.setattr(temp_bot.request, "shutdown", stop)
await temp_bot.initialize()
assert self.test_flag == ["initialize"]
assert temp_bot.bot == bot.bot
await temp_bot.shutdown()
assert self.test_flag == ["initialize", "stop"]
finally:
await orig_stop()
async def test_multiple_inits_and_shutdowns(self, bot, monkeypatch):
self.received = defaultdict(int)
async def initialize(*args, **kwargs):
self.received["init"] += 1
async def shutdown(*args, **kwargs):
self.received["shutdown"] += 1
monkeypatch.setattr(HTTPXRequest, "initialize", initialize)
monkeypatch.setattr(HTTPXRequest, "shutdown", shutdown)
test_bot = Bot(bot.token)
await test_bot.initialize()
await test_bot.initialize()
await test_bot.initialize()
await test_bot.shutdown()
await test_bot.shutdown()
await test_bot.shutdown()
# 2 instead of 1 since we have to request objects for each bot
assert self.received["init"] == 2
assert self.received["shutdown"] == 2
async def test_multiple_init_cycles(self, bot):
# nothing really to assert - this should just not fail
test_bot = Bot(bot.token)
async with test_bot:
await test_bot.get_me()
async with test_bot:
await test_bot.get_me()
async def test_context_manager(self, monkeypatch, bot):
async def initialize():
self.test_flag = ["initialize"]
async def shutdown(*args):
self.test_flag.append("stop")
monkeypatch.setattr(bot, "initialize", initialize)
monkeypatch.setattr(bot, "shutdown", shutdown)
async with bot:
pass
assert self.test_flag == ["initialize", "stop"]
async def test_context_manager_exception_on_init(self, monkeypatch, bot):
async def initialize():
raise RuntimeError("initialize")
async def shutdown():
self.test_flag = "stop"
monkeypatch.setattr(bot, "initialize", initialize)
monkeypatch.setattr(bot, "shutdown", shutdown)
with pytest.raises(RuntimeError, match="initialize"):
async with bot:
pass
assert self.test_flag == "stop"
async def test_log_decorator(self, bot, caplog):
# Second argument makes sure that we ignore logs from e.g. httpx
with caplog.at_level(logging.DEBUG, logger="telegram"):
await bot.get_me()
# Only for stabilizing this test-
if len(caplog.records) == 4:
for idx, record in enumerate(caplog.records):
print(record)
if record.getMessage().startswith("Task was destroyed but it is pending"):
caplog.records.pop(idx)
if record.getMessage().startswith("Task exception was never retrieved"):
caplog.records.pop(idx)
assert len(caplog.records) == 3
assert caplog.records[0].getMessage().startswith("Entering: get_me")
assert caplog.records[-1].getMessage().startswith("Exiting: get_me")
@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(
"acd_in,maxsize",
[(True, 1024), (False, 1024), (0, 0), (None, None)],
)
async def test_callback_data_maxsize(self, bot, acd_in, maxsize):
async with ExtBot(bot.token, arbitrary_callback_data=acd_in) as acd_bot:
if acd_in is not False:
assert acd_bot.callback_data_cache.maxsize == maxsize
else:
assert acd_bot.callback_data_cache is None
async def test_no_token_passed(self):
with pytest.raises(InvalidToken, match="You must pass the token"):
Bot("")
async def test_invalid_token_server_response(self):
with pytest.raises(InvalidToken, match="The token `12` was rejected by the server."):
async with make_bot(token="12"):
pass
async def test_unknown_kwargs(self, bot, monkeypatch):
async def post(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
if not all([data["unknown_kwarg_1"] == "7", data["unknown_kwarg_2"] == "5"]):
pytest.fail("got wrong parameters")
return True
monkeypatch.setattr(bot.request, "post", post)
await bot.send_message(
123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5}
)
@pytest.mark.flaky(3, 1)
async def test_get_me_and_properties(self, bot: Bot):
get_me_bot = await bot.get_me()
assert isinstance(get_me_bot, User)
assert get_me_bot.id == bot.id
assert get_me_bot.username == bot.username
assert get_me_bot.first_name == bot.first_name
assert get_me_bot.last_name == bot.last_name
assert get_me_bot.name == bot.name
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 f"https://t.me/{get_me_bot.username}" == bot.link
@pytest.mark.parametrize(
"attribute",
[
"id",
"username",
"first_name",
"last_name",
"name",
"can_join_groups",
"can_read_all_group_messages",
"supports_inline_queries",
"link",
],
)
async def test_get_me_and_properties_not_initialized(self, bot: Bot, attribute):
bot = Bot(token=bot.token)
try:
with pytest.raises(RuntimeError, match="not properly initialized"):
bot[attribute]
finally:
await bot.shutdown()
async def test_equality(self):
async with make_bot(token=FALLBACKS[0]["token"]) as a, make_bot(
token=FALLBACKS[0]["token"]
) as b, make_bot(token=FALLBACKS[1]["token"]) as c, Bot(token=FALLBACKS[0]["token"]) as d:
e = Update(123456789)
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)
@pytest.mark.flaky(3, 1)
async def test_to_dict(self, bot):
to_dict_bot = bot.to_dict()
assert isinstance(to_dict_bot, dict)
assert to_dict_bot["id"] == bot.id
assert to_dict_bot["username"] == bot.username
assert to_dict_bot["first_name"] == bot.first_name
if bot.last_name:
assert to_dict_bot["last_name"] == bot.last_name
def test_bot_pickling_error(self, bot):
with pytest.raises(pickle.PicklingError, match="Bot objects cannot be pickled"):
pickle.dumps(bot)
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)
async def test_defaults_handling(
self, bot_class, bot_method_name, bot_method, bot, raw_bot, monkeypatch
):
"""
Here we check that the bot methods handle tg.ext.Defaults correctly. This has two parts:
1. Check that ExtBot actually inserts the defaults values correctly
2. Check that tg.Bot just replaces `DefaultValue(obj)` with `obj`, i.e. that it doesn't
pass any `DefaultValue` instances to Request. See the docstring of
tg.Bot._insert_defaults for details on why we need that
As for most defaults,
we can't really check the effect, we just check if we're passing the correct kwargs to
Request.post. As bot method tests a scattered across the different test files, we do
this here in one place.
The same test is also run for all the shortcuts (Message.reply_text) etc in the
corresponding tests.
Finally, there are some tests for Defaults.{parse_mode, quote, allow_sending_without_reply}
at the appropriate places, as those are the only things we can actually check.
"""
if bot_method_name.lower().replace("_", "") == "getme":
# Mocking get_me within check_defaults_handling messes with the cached values like
# Bot.{bot, username, id, …}` unless we return the expected User object.
return_value = bot.bot
else:
return_value = None
# Check that ExtBot does the right thing
bot_method = getattr(bot, bot_method_name)
raw_bot_method = getattr(raw_bot, bot_method_name)
assert await check_defaults_handling(bot_method, bot, return_value=return_value)
assert await check_defaults_handling(raw_bot_method, raw_bot, return_value=return_value)
def test_ext_bot_signature(self):
"""
Here we make sure that all methods of ext.ExtBot have the same signature as the
corresponding methods of tg.Bot.
"""
# Some methods of ext.ExtBot
global_extra_args = {"rate_limit_args"}
extra_args_per_method = defaultdict(
set, {"__init__": {"arbitrary_callback_data", "defaults", "rate_limiter"}}
)
different_hints_per_method = defaultdict(set, {"__setattr__": {"ext_bot"}})
for name, method in inspect.getmembers(Bot, predicate=inspect.isfunction):
signature = inspect.signature(method)
ext_signature = inspect.signature(getattr(ExtBot, name))
assert (
ext_signature.return_annotation == signature.return_annotation
), f"Wrong return annotation for method {name}"
assert (
set(signature.parameters)
== set(ext_signature.parameters) - global_extra_args - extra_args_per_method[name]
), f"Wrong set of parameters for method {name}"
for param_name, param in signature.parameters.items():
if param_name in different_hints_per_method[name]:
continue
assert (
param.annotation == ext_signature.parameters[param_name].annotation
), f"Wrong annotation for parameter {param_name} of method {name}"
assert (
param.default == ext_signature.parameters[param_name].default
), f"Wrong default value for parameter {param_name} of method {name}"
assert (
param.kind == ext_signature.parameters[param_name].kind
), f"Wrong parameter kind for parameter {param_name} of method {name}"
@pytest.mark.flaky(3, 1)
async def test_forward_message(self, bot, chat_id, message):
forward_message = await bot.forward_message(
chat_id, from_chat_id=chat_id, message_id=message.message_id
)
assert forward_message.text == message.text
assert forward_message.forward_from.username == message.from_user.username
assert isinstance(forward_message.forward_date, dtm.datetime)
async def test_forward_protected_message(self, bot, message, chat_id):
to_forward_protected = await bot.send_message(
chat_id, "cant forward me", protect_content=True
)
assert to_forward_protected.has_protected_content
with pytest.raises(BadRequest, match="can't be forwarded"):
await to_forward_protected.forward(chat_id)
to_forward_unprotected = await bot.send_message(
chat_id, "forward me", protect_content=False
)
assert not to_forward_unprotected.has_protected_content
forwarded_but_now_protected = await to_forward_unprotected.forward(
chat_id, protect_content=True
)
assert forwarded_but_now_protected.has_protected_content
with pytest.raises(BadRequest, match="can't be forwarded"):
await forwarded_but_now_protected.forward(chat_id)
@pytest.mark.flaky(3, 1)
async def test_delete_message(self, bot, chat_id):
message = await bot.send_message(chat_id, text="will be deleted")
await asyncio.sleep(2)
assert await bot.delete_message(chat_id=chat_id, message_id=message.message_id) is True
@pytest.mark.flaky(3, 1)
async def test_delete_message_old_message(self, bot, chat_id):
with pytest.raises(BadRequest):
# Considering that the first message is old enough
await bot.delete_message(chat_id=chat_id, message_id=1)
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice, send_video_note,
# send_media_group and send_animation are tested in their respective test modules. No need to
# duplicate here.
@pytest.mark.flaky(3, 1)
async def test_send_venue(self, bot, chat_id):
longitude = -46.788279
latitude = -23.691288
title = "title"
address = "address"
foursquare_id = "foursquare id"
foursquare_type = "foursquare type"
google_place_id = "google_place id"
google_place_type = "google_place type"
message = await bot.send_venue(
chat_id=chat_id,
title=title,
address=address,
latitude=latitude,
longitude=longitude,
foursquare_id=foursquare_id,
foursquare_type=foursquare_type,
protect_content=True,
)
assert message.venue
assert message.venue.title == title
assert message.venue.address == address
assert message.venue.location.latitude == latitude
assert message.venue.location.longitude == longitude
assert message.venue.foursquare_id == foursquare_id
assert message.venue.foursquare_type == foursquare_type
assert message.venue.google_place_id is None
assert message.venue.google_place_type is None
assert message.has_protected_content
message = await bot.send_venue(
chat_id=chat_id,
title=title,
address=address,
latitude=latitude,
longitude=longitude,
google_place_id=google_place_id,
google_place_type=google_place_type,
protect_content=True,
)
assert message.venue
assert message.venue.title == title
assert message.venue.address == address
assert message.venue.location.latitude == latitude
assert message.venue.location.longitude == longitude
assert message.venue.google_place_id == google_place_id
assert message.venue.google_place_type == google_place_type
assert message.venue.foursquare_id is None
assert message.venue.foursquare_type is None
assert message.has_protected_content
@pytest.mark.flaky(3, 1)
async def test_send_contact(self, bot, chat_id):
phone_number = "+11234567890"
first_name = "Leandro"
last_name = "Toledo"
message = await bot.send_contact(
chat_id=chat_id,
phone_number=phone_number,
first_name=first_name,
last_name=last_name,
protect_content=True,
)
assert message.contact
assert message.contact.phone_number == phone_number
assert message.contact.first_name == first_name
assert message.contact.last_name == last_name
assert message.has_protected_content
# TODO: Add bot to group to test polls too
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize(
"reply_markup",
[
None,
InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
),
InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
).to_dict(),
],
)
async def test_send_and_stop_poll(self, bot, super_group_id, reply_markup):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
message = await bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
is_anonymous=False,
allows_multiple_answers=True,
read_timeout=60,
protect_content=True,
)
assert message.poll
assert message.poll.question == question
assert message.poll.options[0].text == answers[0]
assert message.poll.options[1].text == answers[1]
assert message.poll.options[2].text == answers[2]
assert not message.poll.is_anonymous
assert message.poll.allows_multiple_answers
assert not message.poll.is_closed
assert message.poll.type == Poll.REGULAR
assert message.has_protected_content
# Since only the poll and not the complete message is returned, we can't check that the
# reply_markup is correct. So we just test that sending doesn't give an error.
poll = await bot.stop_poll(
chat_id=super_group_id,
message_id=message.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert isinstance(poll, Poll)
assert poll.is_closed
assert poll.options[0].text == answers[0]
assert poll.options[0].voter_count == 0
assert poll.options[1].text == answers[1]
assert poll.options[1].voter_count == 0
assert poll.options[2].text == answers[2]
assert poll.options[2].voter_count == 0
assert poll.question == question
assert poll.total_voter_count == 0
explanation = "[Here is a link](https://google.com)"
explanation_entities = [
MessageEntity(MessageEntity.TEXT_LINK, 0, 14, url="https://google.com")
]
message_quiz = await bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation,
explanation_parse_mode=ParseMode.MARKDOWN_V2,
)
assert message_quiz.poll.correct_option_id == 2
assert message_quiz.poll.type == Poll.QUIZ
assert message_quiz.poll.is_closed
assert message_quiz.poll.explanation == "Here is a link"
assert message_quiz.poll.explanation_entities == tuple(explanation_entities)
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize(
["open_period", "close_date"], [(5, None), (None, True)], ids=["open_period", "close_date"]
)
async def test_send_open_period(self, bot, super_group_id, open_period, close_date):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
)
if close_date:
close_date = dtm.datetime.utcnow() + dtm.timedelta(seconds=5.05)
message = await bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
is_anonymous=False,
allows_multiple_answers=True,
read_timeout=60,
open_period=open_period,
close_date=close_date,
)
await asyncio.sleep(5.1)
new_message = await bot.edit_message_reply_markup(
chat_id=super_group_id,
message_id=message.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert new_message.poll.id == message.poll.id
assert new_message.poll.is_closed
@pytest.mark.flaky(3, 1)
async def test_send_close_date_default_tz(self, tz_bot, super_group_id):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
)
aware_close_date = dtm.datetime.now(tz=tz_bot.defaults.tzinfo) + dtm.timedelta(seconds=5)
close_date = aware_close_date.replace(tzinfo=None)
msg = await tz_bot.send_poll( # The timezone returned from this is always converted to UTC
chat_id=super_group_id,
question=question,
options=answers,
close_date=close_date,
read_timeout=60,
)
msg.poll._unfreeze()
# Sometimes there can be a few seconds delay, so don't let the test fail due to that-
msg.poll.close_date = msg.poll.close_date.astimezone(aware_close_date.tzinfo)
assert abs(msg.poll.close_date - aware_close_date) <= dtm.timedelta(seconds=5)
await asyncio.sleep(5.1)
new_message = await tz_bot.edit_message_reply_markup(
chat_id=super_group_id,
message_id=msg.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert new_message.poll.id == msg.poll.id
assert new_message.poll.is_closed
@pytest.mark.flaky(3, 1)
async def test_send_poll_explanation_entities(self, bot, chat_id):
test_string = "Italic Bold Code"
entities = [
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.ITALIC, 7, 4),
MessageEntity(MessageEntity.ITALIC, 12, 4),
]
message = await bot.send_poll(
chat_id,
"question",
options=["a", "b"],
correct_option_id=0,
type=Poll.QUIZ,
explanation=test_string,
explanation_entities=entities,
)
assert message.poll.explanation == test_string
assert message.poll.explanation_entities == tuple(entities)
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
async def test_send_poll_default_parse_mode(self, default_bot, super_group_id):
explanation = "Italic Bold Code"
explanation_markdown = "_Italic_ *Bold* `Code`"
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
message = await default_bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation_markdown,
)
assert message.poll.explanation == explanation
assert message.poll.explanation_entities == (
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.BOLD, 7, 4),
MessageEntity(MessageEntity.CODE, 12, 4),
)
message = await default_bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation_markdown,
explanation_parse_mode=None,
)
assert message.poll.explanation == explanation_markdown
assert message.poll.explanation_entities == ()
message = await default_bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation_markdown,
explanation_parse_mode="HTML",
)
assert message.poll.explanation == explanation_markdown
assert message.poll.explanation_entities == ()
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize(
"default_bot,custom",
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_poll_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_poll(
chat_id,
question=question,
options=answers,
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_poll(
chat_id,
question=question,
options=answers,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="message not found"):
await default_bot.send_poll(
chat_id,
question=question,
options=answers,
reply_to_message_id=reply_to_message.message_id,
)
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
async def test_send_poll_default_protect_content(self, chat_id, default_bot):
protected_poll = await default_bot.send_poll(chat_id, "Test", ["1", "2"])
assert protected_poll.has_protected_content
unprotect_poll = await default_bot.send_poll(
chat_id, "test", ["1", "2"], protect_content=False
)
assert not unprotect_poll.has_protected_content
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize("emoji", Dice.ALL_EMOJI + [None])
async def test_send_dice(self, bot, chat_id, emoji):
message = await bot.send_dice(chat_id, emoji=emoji, protect_content=True)
assert message.dice
assert message.has_protected_content
if emoji is None:
assert message.dice.emoji == Dice.DICE
else:
assert message.dice.emoji == emoji
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize(
"default_bot,custom",
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_dice_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_dice(
chat_id,
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_dice(
chat_id,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="message not found"):
await default_bot.send_dice(
chat_id, reply_to_message_id=reply_to_message.message_id
)
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
async def test_send_dice_default_protect_content(self, chat_id, default_bot):
protected_dice = await default_bot.send_dice(chat_id)
assert protected_dice.has_protected_content
unprotected_dice = await default_bot.send_dice(chat_id, protect_content=False)
assert not unprotected_dice.has_protected_content
@pytest.mark.flaky(3, 1)
@pytest.mark.parametrize("chat_action", list(ChatAction))
async def test_send_chat_action(self, bot, chat_id, chat_action):
assert await bot.send_chat_action(chat_id, chat_action)
async def test_wrong_chat_action(self, bot, chat_id):
with pytest.raises(BadRequest, match="Wrong parameter action"):
await bot.send_chat_action(chat_id, "unknown action")
@pytest.mark.asyncio
async def test_answer_web_app_query(self, bot, raw_bot, monkeypatch):
params = False
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
nonlocal params
params = request_data.parameters == {
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
}
web_app_msg = SentWebAppMessage("321").to_dict()
return web_app_msg
# We test different result types more thoroughly for answer_inline_query, so we just
# use the one type here
result = InlineQueryResultArticle("1", "title", InputTextMessageContent("text"))
copied_result = copy.copy(result)
ext_bot = bot
for bot in (ext_bot, raw_bot):
# We need to test 1) below both the bot and raw_bot and setting this up with
# pytest.parametrize appears to be difficult ...