-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Expand file tree
/
Copy pathtest_bot.py
More file actions
4186 lines (3629 loc) · 170 KB
/
Copy pathtest_bot.py
File metadata and controls
4186 lines (3629 loc) · 170 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-2024
# 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 socket
import time
from collections import defaultdict
from http import HTTPStatus
from io import BytesIO
from typing import Tuple
import httpx
import pytest
from telegram import (
Bot,
BotCommand,
BotCommandScopeChat,
BotDescription,
BotName,
BotShortDescription,
BusinessConnection,
CallbackQuery,
Chat,
ChatAdministratorRights,
ChatFullInfo,
ChatPermissions,
Dice,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultDocument,
InlineQueryResultsButton,
InlineQueryResultVoice,
InputFile,
InputMediaDocument,
InputMediaPhoto,
InputMessageContent,
InputPollOption,
InputTextMessageContent,
LabeledPrice,
LinkPreviewOptions,
MenuButton,
MenuButtonCommands,
MenuButtonDefault,
MenuButtonWebApp,
Message,
MessageEntity,
Poll,
PollOption,
ReactionTypeCustomEmoji,
ReactionTypeEmoji,
ReplyParameters,
SentWebAppMessage,
ShippingOption,
Update,
User,
WebAppInfo,
)
from telegram._utils.datetime import UTC, from_timestamp, to_timestamp
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.strings import to_camel_case
from telegram.constants import (
ChatAction,
InlineQueryLimit,
InlineQueryResultType,
MenuButtonType,
ParseMode,
ReactionEmoji,
)
from telegram.error import BadRequest, EndPointNotFound, InvalidToken, NetworkError
from telegram.ext import ExtBot, InvalidCallbackData
from telegram.helpers import escape_markdown
from telegram.request import BaseRequest, HTTPXRequest, RequestData
from telegram.warnings import PTBDeprecationWarning, PTBUserWarning
from tests.auxil.bot_method_checks import check_defaults_handling
from tests.auxil.ci_bots import FALLBACKS
from tests.auxil.envvars import GITHUB_ACTION, TEST_WITH_OPT_DEPS
from tests.auxil.files import data_file
from tests.auxil.networking import expect_bad_request
from tests.auxil.pytest_classes import PytestBot, PytestExtBot, make_bot
from tests.auxil.slots import mro_slots
from ._files.test_photo import photo_file
from .auxil.build_messages import make_message
@pytest.fixture()
async def message(bot, chat_id): # mostly used in tests for edit_message
out = await bot.send_message(
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
)
out._unfreeze()
return out
@pytest.fixture(scope="module")
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="module")
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="module")
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, include_camel_case=False, include_do_api_request=False):
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",
]
if not include_do_api_request:
non_api_methods.append("do_api_request")
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
if not include_camel_case and any(x.isupper() for x in name):
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 InputMessageContentLPO(InputMessageContent):
"""
This is here to cover the case of InputMediaContent classes in testing answer_ilq that have
`link_preview_options` but not `parse_mode`. Unlikely to ever happen, but better be save
than sorry …
"""
__slots__ = ("entities", "link_preview_options", "message_text", "parse_mode")
def __init__(
self,
message_text: str,
link_preview_options=DEFAULT_NONE,
*,
api_kwargs=None,
):
super().__init__(api_kwargs=api_kwargs)
self._unfreeze()
self.message_text = message_text
self.link_preview_options = link_preview_options
class TestBotWithoutRequest:
"""
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`
"""
test_flag = None
@pytest.fixture(autouse=True)
def _reset(self):
self.test_flag = None
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
def test_slot_behaviour(self, bot_class, bot):
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_no_token_passed(self):
with pytest.raises(InvalidToken, match="You must pass the token"):
Bot("")
async def test_repr(self):
bot = Bot(token="some_token", base_file_url="")
assert repr(bot) == "Bot[token=some_token]"
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
async def test_initialize_and_shutdown(self, bot: PytestExtBot, monkeypatch):
async def initialize(*args, **kwargs):
self.test_flag = ["initialize"]
async def stop(*args, **kwargs):
self.test_flag.append("stop")
temp_bot = PytestBot(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 = PytestBot(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_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_equality(self):
async with make_bot(token=FALLBACKS[0]["token"]) as a, make_bot(
token=FALLBACKS[0]["token"]
) as b, Bot(token=FALLBACKS[0]["token"]) as c, make_bot(token=FALLBACKS[1]["token"]) as d:
e = Update(123456789)
f = Bot(token=FALLBACKS[0]["token"])
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)
# We cant check equality for unintialized Bot object
assert hash(a) != hash(f)
@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_get_me_and_properties(self, bot):
get_me_bot = await ExtBot(bot.token).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
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)
@pytest.mark.parametrize(
("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")]
)
async def test_bot_method_logging(self, bot: PytestExtBot, cls, logger_name, caplog):
# Second argument makes sure that we ignore logs from e.g. httpx
with caplog.at_level(logging.DEBUG, logger="telegram"):
await cls(bot.token).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) == 2
assert all(caplog.records[i].name == logger_name for i in [-1, 0])
assert (
caplog.records[0]
.getMessage()
.startswith("Calling Bot API endpoint `getMe` with parameters `{}`")
)
assert (
caplog.records[-1]
.getMessage()
.startswith("Call to Bot API endpoint `getMe` finished with return value")
)
@bot_methods()
def test_camel_case_aliases(self, bot_class, bot_method_name, bot_method):
camel_case_name = to_camel_case(bot_method_name)
camel_case_function = getattr(bot_class, camel_case_name, False)
assert camel_case_function is not False, f"{camel_case_name} not found"
assert camel_case_function is bot_method, f"{camel_case_name} is not {bot_method}"
@bot_methods(include_do_api_request=True)
def test_coroutine_functions(self, bot_class, bot_method_name, bot_method):
"""Check that all bot methods are defined as async def ..."""
meth = getattr(bot_method, "__wrapped__", bot_method) # to unwrap the @_log decorator
assert inspect.iscoroutinefunction(meth), f"{bot_method_name} must be a coroutine function"
@bot_methods(include_do_api_request=True)
def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_method):
"""Check that all bot methods have `api_kwargs` and timeout params."""
param_names = inspect.signature(bot_method).parameters.keys()
params = ("pool_timeout", "read_timeout", "connect_timeout", "write_timeout", "api_kwargs")
for param in params:
assert param in param_names, f"{bot_method_name} is missing the parameter `{param}`"
rate_arg = "rate_limit_args"
if bot_method_name.replace("_", "").lower() != "getupdates" and bot_class is ExtBot:
assert rate_arg in param_names, f"{bot_method} is missing the parameter `{rate_arg}`"
@bot_methods(ext_bot=False)
async def test_defaults_handling(
self,
bot_class,
bot_method_name: str,
bot_method,
bot: PytestExtBot,
raw_bot: PytestBot,
):
"""
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.
"""
# 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 if bot_method_name.lower().replace("_", "") == "getme" else 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)
@pytest.mark.parametrize(
("name", "method"), inspect.getmembers(Bot, predicate=inspect.isfunction)
)
def test_ext_bot_signature(self, name, method):
"""
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"}})
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}"
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}
)
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",
},
}
return SentWebAppMessage("321").to_dict()
# 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 ...
monkeypatch.setattr(bot.request, "post", make_assertion)
web_app_msg = await bot.answer_web_app_query("12345", result)
assert params, "something went wrong with passing arguments to the request"
assert isinstance(web_app_msg, SentWebAppMessage)
assert web_app_msg.inline_message_id == "321"
# 1)
# make sure that the results were not edited in-place
assert result == copied_result
assert (
result.input_message_content.parse_mode
== copied_result.input_message_content.parse_mode
)
@pytest.mark.parametrize(
"default_bot",
[{"parse_mode": "Markdown", "disable_web_page_preview": True}],
indirect=True,
)
@pytest.mark.parametrize(
("ilq_result", "expected_params"),
[
(
InlineQueryResultArticle("1", "title", InputTextMessageContent("text")),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"parse_mode": "Markdown",
"link_preview_options": {
"is_disabled": True,
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
(
InlineQueryResultArticle(
"1",
"title",
InputTextMessageContent(
"text", parse_mode="HTML", disable_web_page_preview=False
),
),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"parse_mode": "HTML",
"link_preview_options": {
"is_disabled": False,
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
(
InlineQueryResultArticle(
"1",
"title",
InputTextMessageContent(
"text", parse_mode=None, disable_web_page_preview="False"
),
),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"link_preview_options": {
"is_disabled": "False",
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
],
)
async def test_answer_web_app_query_defaults(
self, default_bot, ilq_result, expected_params, monkeypatch
):
bot = default_bot
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 == expected_params
return SentWebAppMessage("321").to_dict()
monkeypatch.setattr(bot.request, "post", make_assertion)
# We test different result types more thoroughly for answer_inline_query, so we just
# use the one type here
copied_result = copy.copy(ilq_result)
web_app_msg = await bot.answer_web_app_query("12345", ilq_result)
assert params, "something went wrong with passing arguments to the request"
assert isinstance(web_app_msg, SentWebAppMessage)
assert web_app_msg.inline_message_id == "321"
# make sure that the results were not edited in-place
assert ilq_result == copied_result
assert (
ilq_result.input_message_content.parse_mode
== copied_result.input_message_content.parse_mode
)
# TODO: Needs improvement. We need incoming inline query to test answer.
@pytest.mark.parametrize("button_type", ["start", "web_app"])
async def test_answer_inline_query(self, monkeypatch, bot, raw_bot, button_type):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
expected = {
"cache_time": 300,
"results": [
{
"title": "first",
"id": "11",
"type": "article",
"input_message_content": {"message_text": "first"},
},
{
"title": "second",
"id": "12",
"type": "article",
"input_message_content": {"message_text": "second"},
},
{
"title": "test_result",
"id": "123",
"type": "document",
"document_url": (
"https://raw.githubusercontent.com/python-telegram-bot"
"/logos/master/logo/png/ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"input_message_content": {"message_text": "imc"},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
if button_type == "start":
button_dict = {"text": "button_text", "start_parameter": "start_parameter"}
else:
button_dict = {
"text": "button_text",
"web_app": {"url": "https://python-telegram-bot.org"},
}
expected["button"] = button_dict
return request_data.parameters == expected
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputMessageContentLPO("imc"),
),
]
if button_type == "start":
button = InlineQueryResultsButton(
text="button_text", start_parameter="start_parameter"
)
elif button_type == "web_app":
button = InlineQueryResultsButton(
text="button_text", web_app=WebAppInfo("https://python-telegram-bot.org")
)
else:
button = None
copied_results = copy.copy(results)
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 ...
monkeypatch.setattr(bot.request, "post", make_assertion)
assert await bot.answer_inline_query(
1234,
results=results,
cache_time=300,
is_personal=True,
next_offset="42",
button=button,
)
# 1)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
monkeypatch.delattr(bot.request, "post")
async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"cache_time": 300,
"results": [
{
"title": "first",
"id": "11",
"type": "article",
"input_message_content": {"message_text": "first"},
},
{
"title": "second",
"id": "12",
"type": "article",
"input_message_content": {"message_text": "second"},
},
{
"title": "test_result",
"id": "123",
"type": "document",
"document_url": (
"https://raw.githubusercontent.com/"
"python-telegram-bot/logos/master/logo/png/"
"ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"input_message_content": {"message_text": "imc"},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
monkeypatch.setattr(bot.request, "post", make_assertion)
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputMessageContentLPO("imc"),
),
]
copied_results = copy.copy(results)
assert await bot.answer_inline_query(
1234,
results=results,
cache_time=300,
is_personal=True,
next_offset="42",
)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
@pytest.mark.parametrize(
"default_bot",
[{"parse_mode": "Markdown", "disable_web_page_preview": True}],
indirect=True,
)
async def test_answer_inline_query_default_parse_mode(self, monkeypatch, default_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"cache_time": 300,
"results": [
{
"title": "first",
"id": "11",
"type": InlineQueryResultType.ARTICLE,
"input_message_content": {
"message_text": "first",
"parse_mode": "Markdown",
"link_preview_options": {
"is_disabled": True,
},
},
},
{
"title": "second",
"id": "12",
"type": InlineQueryResultType.ARTICLE,
"input_message_content": {
"message_text": "second",
"link_preview_options": {
"is_disabled": True,
},
},
},
{
"title": "test_result",
"id": "123",
"type": InlineQueryResultType.DOCUMENT,
"document_url": (
"https://raw.githubusercontent.com/"
"python-telegram-bot/logos/master/logo/png/"
"ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"parse_mode": "Markdown",
"input_message_content": {
"message_text": "imc",
"link_preview_options": {
"is_disabled": True,
},
"parse_mode": "Markdown",
},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
monkeypatch.setattr(default_bot.request, "post", make_assertion)
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputTextMessageContent("imc"),
),
]
copied_results = copy.copy(results)
assert await default_bot.answer_inline_query(
1234,
results=results,
cache_time=300,
is_personal=True,
next_offset="42",
)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
@pytest.mark.parametrize(
("current_offset", "num_results", "id_offset", "expected_next_offset"),
[
("", InlineQueryLimit.RESULTS, 1, 1),
(1, InlineQueryLimit.RESULTS, 51, 2),
(5, 3, 251, ""),
],
)
async def test_answer_inline_query_current_offset_1(
self,
monkeypatch,
bot,
inline_results,
current_offset,
num_results,
id_offset,
expected_next_offset,
):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length_matches = len(results) == num_results
ids_match = all(int(res["id"]) == id_offset + i for i, res in enumerate(results))
next_offset_matches = data["next_offset"] == str(expected_next_offset)
return length_matches and ids_match and next_offset_matches
monkeypatch.setattr(bot.request, "post", make_assertion)
assert await bot.answer_inline_query(
1234, results=inline_results, current_offset=current_offset