-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
test_application.py
1961 lines (1632 loc) · 69.8 KB
/
test_application.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/].
"""The integration of persistence into the application is tested in test_basepersistence.
"""
import asyncio
import inspect
import logging
import os
import platform
import signal
import threading
import time
from collections import defaultdict
from pathlib import Path
from queue import Queue
from random import randrange
from threading import Thread
import pytest
from telegram import Bot, Chat, Message, MessageEntity, User
from telegram.error import TelegramError
from telegram.ext import (
Application,
ApplicationBuilder,
ApplicationHandlerStop,
BaseHandler,
CallbackContext,
CommandHandler,
ContextTypes,
Defaults,
JobQueue,
MessageHandler,
PicklePersistence,
TypeHandler,
Updater,
filters,
)
from telegram.warnings import PTBUserWarning
from tests.conftest import PROJECT_ROOT_PATH, call_after, make_message_update, send_webhook_message
class CustomContext(CallbackContext):
pass
class TestApplication:
"""The integration of persistence into the application is tested in
test_basepersistence.
"""
message_update = make_message_update(message="Text")
received = None
count = 0
@pytest.fixture(autouse=True, name="reset")
def reset_fixture(self):
self.reset()
def reset(self):
self.received = None
self.count = 0
async def error_handler_context(self, update, context):
self.received = context.error.message
async def error_handler_raise_error(self, update, context):
raise Exception("Failing bigly")
async def callback_increase_count(self, update, context):
self.count += 1
def callback_set_count(self, count, sleep: float = None):
async def callback(update, context):
if sleep:
await asyncio.sleep(sleep)
self.count = count
return callback
def callback_raise_error(self, error_message: str):
async def callback(update, context):
raise TelegramError(error_message)
return callback
async def callback_received(self, update, context):
self.received = update.message
async def callback_context(self, update, context):
if (
isinstance(context, CallbackContext)
and isinstance(context.bot, Bot)
and isinstance(context.update_queue, Queue)
and isinstance(context.job_queue, JobQueue)
and isinstance(context.error, TelegramError)
):
self.received = context.error.message
async def test_slot_behaviour(self, bot, mro_slots):
async with ApplicationBuilder().token(bot.token).build() as app:
for at in app.__slots__:
at = f"_Application{at}" if at.startswith("__") and not at.endswith("__") else at
assert getattr(app, at, "err") != "err", f"got extra slot '{at}'"
assert len(mro_slots(app)) == len(set(mro_slots(app))), "duplicate slot"
def test_manual_init_warning(self, recwarn, updater):
Application(
bot=None,
update_queue=None,
job_queue=None,
persistence=None,
context_types=ContextTypes(),
updater=updater,
concurrent_updates=False,
post_init=None,
post_shutdown=None,
)
assert len(recwarn) == 1
assert (
str(recwarn[-1].message)
== "`Application` instances should be built via the `ApplicationBuilder`."
)
assert recwarn[0].filename == __file__, "stacklevel is incorrect!"
@pytest.mark.parametrize(
"concurrent_updates, expected", [(0, 0), (4, 4), (False, 0), (True, 256)]
)
@pytest.mark.filterwarnings("ignore: `Application` instances should")
def test_init(self, bot, concurrent_updates, expected):
update_queue = asyncio.Queue()
job_queue = JobQueue()
persistence = PicklePersistence("file_path")
context_types = ContextTypes()
updater = Updater(bot=bot, update_queue=update_queue)
async def post_init(application: Application) -> None:
pass
async def post_shutdown(application: Application) -> None:
pass
app = Application(
bot=bot,
update_queue=update_queue,
job_queue=job_queue,
persistence=persistence,
context_types=context_types,
updater=updater,
concurrent_updates=concurrent_updates,
post_init=post_init,
post_shutdown=post_shutdown,
)
assert app.bot is bot
assert app.update_queue is update_queue
assert app.job_queue is job_queue
assert app.persistence is persistence
assert app.context_types is context_types
assert app.updater is updater
assert app.update_queue is updater.update_queue
assert app.bot is updater.bot
assert app.concurrent_updates == expected
assert app.post_init is post_init
assert app.post_shutdown is post_shutdown
# These should be done by the builder
assert app.persistence.bot is None
with pytest.raises(RuntimeError, match="No application was set"):
app.job_queue.application
assert isinstance(app.bot_data, dict)
assert isinstance(app.chat_data[1], dict)
assert isinstance(app.user_data[1], dict)
with pytest.raises(ValueError, match="must be a non-negative"):
Application(
bot=bot,
update_queue=update_queue,
job_queue=job_queue,
persistence=persistence,
context_types=context_types,
updater=updater,
concurrent_updates=-1,
post_init=None,
post_shutdown=None,
)
def test_job_queue(self, bot, app, recwarn):
expected_warning = (
"No `JobQueue` set up. To use `JobQueue`, you must install PTB via "
"`pip install python-telegram-bot[job_queue]`."
)
assert app.job_queue is app._job_queue
application = ApplicationBuilder().token(bot.token).job_queue(None).build()
assert application.job_queue is None
assert len(recwarn) == 1
assert str(recwarn[0].message) == expected_warning
assert recwarn[0].filename == __file__, "wrong stacklevel"
def test_custom_context_init(self, bot):
cc = ContextTypes(
context=CustomContext,
user_data=int,
chat_data=float,
bot_data=complex,
)
application = ApplicationBuilder().token(bot.token).context_types(cc).build()
assert isinstance(application.user_data[1], int)
assert isinstance(application.chat_data[1], float)
assert isinstance(application.bot_data, complex)
@pytest.mark.parametrize("updater", (True, False))
async def test_initialize(self, bot, monkeypatch, updater):
"""Initialization of persistence is tested test_basepersistence"""
self.test_flag = set()
async def after_initialize_bot(*args, **kwargs):
self.test_flag.add("bot")
async def after_initialize_updater(*args, **kwargs):
self.test_flag.add("updater")
monkeypatch.setattr(Bot, "initialize", call_after(Bot.initialize, after_initialize_bot))
monkeypatch.setattr(
Updater, "initialize", call_after(Updater.initialize, after_initialize_updater)
)
if updater:
app = ApplicationBuilder().token(bot.token).build()
await app.initialize()
assert self.test_flag == {"bot", "updater"}
await app.shutdown()
else:
app = ApplicationBuilder().token(bot.token).updater(None).build()
await app.initialize()
assert self.test_flag == {"bot"}
await app.shutdown()
@pytest.mark.parametrize("updater", (True, False))
async def test_shutdown(self, bot, monkeypatch, updater):
"""Shutdown of persistence is tested in test_basepersistence"""
self.test_flag = set()
def after_bot_shutdown(*args, **kwargs):
self.test_flag.add("bot")
def after_updater_shutdown(*args, **kwargs):
self.test_flag.add("updater")
monkeypatch.setattr(Bot, "shutdown", call_after(Bot.shutdown, after_bot_shutdown))
monkeypatch.setattr(
Updater, "shutdown", call_after(Updater.shutdown, after_updater_shutdown)
)
if updater:
async with ApplicationBuilder().token(bot.token).build():
pass
assert self.test_flag == {"bot", "updater"}
else:
async with ApplicationBuilder().token(bot.token).updater(None).build():
pass
assert self.test_flag == {"bot"}
async def test_multiple_inits_and_shutdowns(self, app, monkeypatch):
self.received = defaultdict(int)
async def after_initialize(*args, **kargs):
self.received["init"] += 1
async def after_shutdown(*args, **kwargs):
self.received["shutdown"] += 1
monkeypatch.setattr(
app.bot, "initialize", call_after(app.bot.initialize, after_initialize)
)
monkeypatch.setattr(app.bot, "shutdown", call_after(app.bot.shutdown, after_shutdown))
await app.initialize()
await app.initialize()
await app.initialize()
await app.shutdown()
await app.shutdown()
await app.shutdown()
# 2 instead of 1 since `Updater.initialize` also calls bot.init/shutdown
assert self.received["init"] == 2
assert self.received["shutdown"] == 2
async def test_multiple_init_cycles(self, app):
# nothing really to assert - this should just not fail
async with app:
await app.bot.get_me()
async with app:
await app.bot.get_me()
async def test_start_without_initialize(self, app):
with pytest.raises(RuntimeError, match="not initialized"):
await app.start()
async def test_shutdown_while_running(self, app):
async with app:
await app.start()
with pytest.raises(RuntimeError, match="still running"):
await app.shutdown()
await app.stop()
async def test_start_not_running_after_failure(self, bot, monkeypatch):
def start(_):
raise Exception("Test Exception")
monkeypatch.setattr(JobQueue, "start", start)
app = ApplicationBuilder().token(bot.token).job_queue(JobQueue()).build()
async with app:
with pytest.raises(Exception, match="Test Exception"):
await app.start()
assert app.running is False
async def test_context_manager(self, monkeypatch, app):
self.test_flag = set()
async def after_initialize(*args, **kwargs):
self.test_flag.add("initialize")
async def after_shutdown(*args, **kwargs):
self.test_flag.add("stop")
monkeypatch.setattr(
Application, "initialize", call_after(Application.initialize, after_initialize)
)
monkeypatch.setattr(
Application, "shutdown", call_after(Application.shutdown, after_shutdown)
)
async with app:
pass
assert self.test_flag == {"initialize", "stop"}
async def test_context_manager_exception_on_init(self, monkeypatch, app):
async def after_initialize(*args, **kwargs):
raise RuntimeError("initialize")
async def after_shutdown(*args):
self.test_flag = "stop"
monkeypatch.setattr(
Application, "initialize", call_after(Application.initialize, after_initialize)
)
monkeypatch.setattr(
Application, "shutdown", call_after(Application.shutdown, after_shutdown)
)
with pytest.raises(RuntimeError, match="initialize"):
async with app:
pass
assert self.test_flag == "stop"
@pytest.mark.parametrize("data", ["chat_data", "user_data"])
def test_chat_user_data_read_only(self, app, data):
read_only_data = getattr(app, data)
writable_data = getattr(app, f"_{data}")
writable_data[123] = 321
assert read_only_data == writable_data
with pytest.raises(TypeError):
read_only_data[111] = 123
def test_builder(self, app):
builder_1 = app.builder()
builder_2 = app.builder()
assert isinstance(builder_1, ApplicationBuilder)
assert isinstance(builder_2, ApplicationBuilder)
assert builder_1 is not builder_2
# Make sure that setting a token doesn't raise an exception
# i.e. check that the builders are "empty"/new
builder_1.token(app.bot.token)
builder_2.token(app.bot.token)
@pytest.mark.parametrize("job_queue", (True, False))
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
async def test_start_stop_processing_updates(self, bot, job_queue):
# TODO: repeat a similar test for create_task, persistence processing and job queue
if job_queue:
app = ApplicationBuilder().token(bot.token).build()
else:
app = ApplicationBuilder().token(bot.token).job_queue(None).build()
async def callback(u, c):
self.received = u
assert not app.running
assert not app.updater.running
if job_queue:
assert not app.job_queue.scheduler.running
else:
assert app.job_queue is None
app.add_handler(TypeHandler(object, callback))
await app.update_queue.put(1)
await asyncio.sleep(0.05)
assert not app.update_queue.empty()
assert self.received is None
async with app:
await app.start()
assert app.running
if job_queue:
assert app.job_queue.scheduler.running
else:
assert app.job_queue is None
# app.start() should not start the updater!
assert not app.updater.running
await asyncio.sleep(0.05)
assert app.update_queue.empty()
assert self.received == 1
await app.updater.start_polling()
await app.stop()
assert not app.running
# app.stop() should not stop the updater!
assert app.updater.running
if job_queue:
assert not app.job_queue.scheduler.running
else:
assert app.job_queue is None
await app.update_queue.put(2)
await asyncio.sleep(0.05)
assert not app.update_queue.empty()
assert self.received != 2
assert self.received == 1
await app.updater.stop()
async def test_error_start_stop_twice(self, app):
async with app:
await app.start()
assert app.running
with pytest.raises(RuntimeError, match="already running"):
await app.start()
await app.stop()
assert not app.running
with pytest.raises(RuntimeError, match="not running"):
await app.stop()
async def test_one_context_per_update(self, app):
self.received = None
async def one(update, context):
self.received = context
def two(update, context):
if update.message.text == "test":
if context is not self.received:
pytest.fail("Expected same context object, got different")
else:
if context is self.received:
pytest.fail("First handler was wrongly called")
async with app:
app.add_handler(MessageHandler(filters.Regex("test"), one), group=1)
app.add_handler(MessageHandler(filters.ALL, two), group=2)
u = make_message_update(message="test")
await app.process_update(u)
self.received = None
u.message.text = "something"
await app.process_update(u)
def test_add_handler_errors(self, app):
handler = "not a handler"
with pytest.raises(TypeError, match="handler is not an instance of"):
app.add_handler(handler)
handler = MessageHandler(filters.PHOTO, self.callback_set_count(1))
with pytest.raises(TypeError, match="group is not int"):
app.add_handler(handler, "one")
@pytest.mark.parametrize("group_empty", (True, False))
async def test_add_remove_handler(self, app, group_empty):
handler = MessageHandler(filters.ALL, self.callback_increase_count)
app.add_handler(handler)
if not group_empty:
app.add_handler(handler)
async with app:
await app.start()
await app.update_queue.put(self.message_update)
await asyncio.sleep(0.05)
assert self.count == 1
app.remove_handler(handler)
assert (0 in app.handlers) == (not group_empty)
await app.update_queue.put(self.message_update)
assert self.count == 1
await app.stop()
async def test_add_remove_handler_non_default_group(self, app):
handler = MessageHandler(filters.ALL, self.callback_increase_count)
app.add_handler(handler, group=2)
with pytest.raises(KeyError):
app.remove_handler(handler)
app.remove_handler(handler, group=2)
#
async def test_handler_order_in_group(self, app):
app.add_handler(MessageHandler(filters.PHOTO, self.callback_set_count(1)))
app.add_handler(MessageHandler(filters.ALL, self.callback_set_count(2)))
app.add_handler(MessageHandler(filters.TEXT, self.callback_set_count(3)))
async with app:
await app.start()
await app.update_queue.put(self.message_update)
await asyncio.sleep(0.05)
assert self.count == 2
await app.stop()
async def test_groups(self, app):
app.add_handler(MessageHandler(filters.ALL, self.callback_increase_count))
app.add_handler(MessageHandler(filters.ALL, self.callback_increase_count), group=2)
app.add_handler(MessageHandler(filters.ALL, self.callback_increase_count), group=-1)
async with app:
await app.start()
await app.update_queue.put(self.message_update)
await asyncio.sleep(0.05)
assert self.count == 3
await app.stop()
async def test_add_handlers(self, app):
"""Tests both add_handler & add_handlers together & confirms the correct insertion
order"""
msg_handler_set_count = MessageHandler(filters.TEXT, self.callback_set_count(1))
msg_handler_inc_count = MessageHandler(filters.PHOTO, self.callback_increase_count)
app.add_handler(msg_handler_set_count, 1)
app.add_handlers((msg_handler_inc_count, msg_handler_inc_count), 1)
photo_update = make_message_update(message=Message(2, None, None, photo=True))
async with app:
await app.start()
# Putting updates in the queue calls the callback
await app.update_queue.put(self.message_update)
await app.update_queue.put(photo_update)
await asyncio.sleep(0.05) # sleep is required otherwise there is random behaviour
# Test if handler was added to correct group with correct order-
assert (
self.count == 2
and len(app.handlers[1]) == 3
and app.handlers[1][0] is msg_handler_set_count
)
# Now lets test add_handlers when `handlers` is a dict-
voice_filter_handler_to_check = MessageHandler(
filters.VOICE, self.callback_increase_count
)
app.add_handlers(
handlers={
1: [
MessageHandler(filters.USER, self.callback_increase_count),
voice_filter_handler_to_check,
],
-1: [MessageHandler(filters.CAPTION, self.callback_set_count(2))],
}
)
user_update = make_message_update(
message=Message(3, None, None, from_user=User(1, "s", True))
)
voice_update = make_message_update(message=Message(4, None, None, voice=True))
await app.update_queue.put(user_update)
await app.update_queue.put(voice_update)
await asyncio.sleep(0.05)
assert (
self.count == 4
and len(app.handlers[1]) == 5
and app.handlers[1][-1] is voice_filter_handler_to_check
)
await app.update_queue.put(
make_message_update(message=Message(5, None, None, caption="cap"))
)
await asyncio.sleep(0.05)
assert self.count == 2 and len(app.handlers[-1]) == 1
# Now lets test the errors which can be produced-
with pytest.raises(ValueError, match="The `group` argument"):
app.add_handlers({2: [msg_handler_set_count]}, group=0)
with pytest.raises(ValueError, match="Handlers for group 3"):
app.add_handlers({3: msg_handler_set_count})
with pytest.raises(ValueError, match="The `handlers` argument must be a sequence"):
app.add_handlers({msg_handler_set_count})
await app.stop()
async def test_check_update(self, app):
class TestHandler(BaseHandler):
def check_update(_, update: object):
self.received = object()
def handle_update(
_,
update,
application,
check_result,
context,
):
assert application is app
assert check_result is not self.received
async with app:
app.add_handler(TestHandler("callback"))
await app.start()
await app.update_queue.put(object())
await asyncio.sleep(0.05)
await app.stop()
async def test_flow_stop(self, app, bot):
passed = []
async def start1(b, u):
passed.append("start1")
raise ApplicationHandlerStop
async def start2(b, u):
passed.append("start2")
async def start3(b, u):
passed.append("start3")
update = make_message_update(
message=Message(
1,
None,
None,
None,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
),
)
update.message.set_bot(bot)
async with app:
# If ApplicationHandlerStop raised handlers in other groups should not be called.
passed = []
app.add_handler(CommandHandler("start", start1), 1)
app.add_handler(CommandHandler("start", start3), 1)
app.add_handler(CommandHandler("start", start2), 2)
await app.process_update(update)
assert passed == ["start1"]
async def test_flow_stop_by_error_handler(self, app, bot):
passed = []
exception = Exception("General excepition")
async def start1(b, u):
passed.append("start1")
raise exception
async def start2(b, u):
passed.append("start2")
async def start3(b, u):
passed.append("start3")
async def error(u, c):
passed.append("error")
passed.append(c.error)
raise ApplicationHandlerStop
async with app:
# If ApplicationHandlerStop raised handlers in other groups should not be called.
passed = []
app.add_error_handler(error)
app.add_handler(TypeHandler(object, start1), 1)
app.add_handler(TypeHandler(object, start2), 1)
app.add_handler(TypeHandler(object, start3), 2)
await app.process_update(1)
assert passed == ["start1", "error", exception]
async def test_error_in_handler_part_1(self, app):
app.add_handler(
MessageHandler(
filters.ALL,
self.callback_raise_error(error_message=self.message_update.message.text),
)
)
app.add_handler(MessageHandler(filters.ALL, self.callback_set_count(42)), group=1)
app.add_error_handler(self.error_handler_context)
async with app:
await app.start()
await app.update_queue.put(self.message_update)
await asyncio.sleep(0.05)
await app.stop()
assert self.received == self.message_update.message.text
# Higher groups should still be called
assert self.count == 42
async def test_error_in_handler_part_2(self, app, bot):
passed = []
err = Exception("General exception")
async def start1(u, c):
passed.append("start1")
raise err
async def start2(u, c):
passed.append("start2")
async def start3(u, c):
passed.append("start3")
async def error(u, c):
passed.append("error")
passed.append(c.error)
update = make_message_update(
message=Message(
1,
None,
None,
None,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
),
)
update.message.set_bot(bot)
async with app:
# If an unhandled exception was caught, no further handlers from the same group should
# be called. Also, the error handler should be called and receive the exception
passed = []
app.add_handler(CommandHandler("start", start1), 1)
app.add_handler(CommandHandler("start", start2), 1)
app.add_handler(CommandHandler("start", start3), 2)
app.add_error_handler(error)
await app.process_update(update)
assert passed == ["start1", "error", err, "start3"]
@pytest.mark.parametrize("block", (True, False))
async def test_error_handler(self, app, block):
app.add_error_handler(self.error_handler_context)
app.add_handler(TypeHandler(object, self.callback_raise_error("TestError"), block=block))
async with app:
await app.start()
await app.update_queue.put(1)
await asyncio.sleep(0.05)
assert self.received == "TestError"
# Remove handler
app.remove_error_handler(self.error_handler_context)
self.reset()
await app.update_queue.put(1)
await asyncio.sleep(0.05)
assert self.received is None
await app.stop()
def test_double_add_error_handler(self, app, caplog):
app.add_error_handler(self.error_handler_context)
with caplog.at_level(logging.DEBUG):
app.add_error_handler(self.error_handler_context)
assert len(caplog.records) == 1
assert caplog.records[-1].getMessage().startswith("The callback is already registered")
async def test_error_handler_that_raises_errors(self, app, caplog):
"""Make sure that errors raised in error handlers don't break the main loop of the
application
"""
handler_raise_error = TypeHandler(
int, self.callback_raise_error(error_message="TestError")
)
handler_increase_count = TypeHandler(str, self.callback_increase_count)
app.add_error_handler(self.error_handler_raise_error)
app.add_handler(handler_raise_error)
app.add_handler(handler_increase_count)
with caplog.at_level(logging.ERROR):
async with app:
await app.start()
await app.update_queue.put(1)
await asyncio.sleep(0.05)
assert self.count == 0
assert self.received is None
assert len(caplog.records) > 0
log_messages = (record.getMessage() for record in caplog.records)
assert any(
"uncaught error was raised while handling the error with an error_handler"
in message
for message in log_messages
)
await app.update_queue.put("1")
self.received = None
caplog.clear()
await asyncio.sleep(0.05)
assert self.count == 1
assert self.received is None
assert not caplog.records
await app.stop()
async def test_custom_context_error_handler(self, bot):
async def error_handler(_, context):
self.received = (
type(context),
type(context.user_data),
type(context.chat_data),
type(context.bot_data),
)
application = (
ApplicationBuilder()
.token(bot.token)
.context_types(
ContextTypes(
context=CustomContext, bot_data=int, user_data=float, chat_data=complex
)
)
.build()
)
application.add_error_handler(error_handler)
application.add_handler(
MessageHandler(filters.ALL, self.callback_raise_error("TestError"))
)
async with application:
await application.process_update(self.message_update)
await asyncio.sleep(0.05)
assert self.received == (CustomContext, float, complex, int)
async def test_custom_context_handler_callback(self, bot):
def callback(_, context):
self.received = (
type(context),
type(context.user_data),
type(context.chat_data),
type(context.bot_data),
)
application = (
ApplicationBuilder()
.token(bot.token)
.context_types(
ContextTypes(
context=CustomContext, bot_data=int, user_data=float, chat_data=complex
)
)
.build()
)
application.add_handler(MessageHandler(filters.ALL, callback))
async with application:
await application.process_update(self.message_update)
await asyncio.sleep(0.05)
assert self.received == (CustomContext, float, complex, int)
@pytest.mark.parametrize(
"check,expected",
[(True, True), (None, False), (False, False), ({}, True), ("", True), ("check", True)],
)
async def test_check_update_handling(self, app, check, expected):
class MyHandler(BaseHandler):
def check_update(self, update: object):
return check
async def handle_update(
_,
update,
application,
check_result,
context,
):
await super().handle_update(
update=update,
application=application,
check_result=check_result,
context=context,
)
self.received = check_result
async with app:
app.add_handler(MyHandler(self.callback_increase_count))
await app.process_update(1)
assert self.count == (1 if expected else 0)
if expected:
assert self.received == check
else:
assert self.received is None
async def test_non_blocking_handler(self, app):
event = asyncio.Event()
async def callback(update, context):
await event.wait()
self.count = 42
app.add_handler(TypeHandler(object, callback, block=False))
app.add_handler(TypeHandler(object, self.callback_increase_count), group=1)
async with app:
await app.start()
await app.update_queue.put(1)
task = asyncio.create_task(app.stop())
await asyncio.sleep(0.05)
assert self.count == 1
# Make sure that app stops only once all non blocking callbacks are done
assert not task.done()
event.set()
await asyncio.sleep(0.05)
assert self.count == 42
assert task.done()
async def test_non_blocking_handler_applicationhandlerstop(self, app, recwarn):
async def callback(update, context):
raise ApplicationHandlerStop
app.add_handler(TypeHandler(object, callback, block=False))
async with app:
await app.start()
await app.update_queue.put(1)
await asyncio.sleep(0.05)
await app.stop()
assert len(recwarn) == 1
assert recwarn[0].category is PTBUserWarning
assert (
str(recwarn[0].message)
== "ApplicationHandlerStop is not supported with handlers running non-blocking."
)
assert (
Path(recwarn[0].filename) == PROJECT_ROOT_PATH / "telegram" / "ext" / "_application.py"
), "incorrect stacklevel!"
async def test_non_blocking_no_error_handler(self, app, caplog):
app.add_handler(TypeHandler(object, self.callback_raise_error, block=False))
with caplog.at_level(logging.ERROR):
async with app:
await app.start()
await app.update_queue.put(1)
await asyncio.sleep(0.05)
assert len(caplog.records) == 1
assert (
caplog.records[-1].getMessage().startswith("No error handlers are registered")
)
await app.stop()
@pytest.mark.parametrize("handler_block", (True, False))
async def test_non_blocking_error_handler(self, app, handler_block):
event = asyncio.Event()
async def async_error_handler(update, context):
await event.wait()
self.received = "done"
async def normal_error_handler(update, context):
self.count = 42
app.add_error_handler(async_error_handler, block=False)
app.add_error_handler(normal_error_handler)
app.add_handler(TypeHandler(object, self.callback_raise_error, block=handler_block))
async with app:
await app.start()
await app.update_queue.put(self.message_update)
task = asyncio.create_task(app.stop())
await asyncio.sleep(0.05)
assert self.count == 42