-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
test_conversationhandler.py
2199 lines (1936 loc) · 83.9 KB
/
test_conversationhandler.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/].
"""Persistence of conversations is tested in test_basepersistence.py"""
import asyncio
import logging
from warnings import filterwarnings
import pytest
from telegram import (
Bot,
CallbackQuery,
Chat,
ChosenInlineResult,
InlineQuery,
Message,
MessageEntity,
PreCheckoutQuery,
ShippingQuery,
Update,
User,
)
from telegram.ext import (
ApplicationBuilder,
ApplicationHandlerStop,
CallbackContext,
CallbackQueryHandler,
ChosenInlineResultHandler,
CommandHandler,
ConversationHandler,
Defaults,
ExtBot,
InlineQueryHandler,
JobQueue,
MessageHandler,
PollAnswerHandler,
PollHandler,
PreCheckoutQueryHandler,
ShippingQueryHandler,
StringCommandHandler,
StringRegexHandler,
TypeHandler,
filters,
)
from telegram.warnings import PTBUserWarning
from tests.conftest import make_command_message
@pytest.fixture(scope="class")
def user1():
return User(first_name="Misses Test", id=123, is_bot=False)
@pytest.fixture(scope="class")
def user2():
return User(first_name="Mister Test", id=124, is_bot=False)
def raise_ahs(func):
async def decorator(self, *args, **kwargs):
result = await func(self, *args, **kwargs)
if self.raise_app_handler_stop:
raise ApplicationHandlerStop(result)
return result
return decorator
class TestConversationHandler:
"""Persistence of conversations is tested in test_basepersistence.py"""
# State definitions
# At first we're thirsty. Then we brew coffee, we drink it
# and then we can start coding!
END, THIRSTY, BREWING, DRINKING, CODING = range(-1, 4)
# Drinking state definitions (nested)
# At first we're holding the cup. Then we sip coffee, and last we swallow it
HOLDING, SIPPING, SWALLOWING, REPLENISHING, STOPPING = map(chr, range(ord("a"), ord("f")))
current_state, entry_points, states, fallbacks = None, None, None, None
group = Chat(0, Chat.GROUP)
second_group = Chat(1, Chat.GROUP)
raise_app_handler_stop = False
test_flag = False
# Test related
@pytest.fixture(autouse=True)
def reset(self):
self.raise_app_handler_stop = False
self.test_flag = False
self.current_state = {}
self.entry_points = [CommandHandler("start", self.start)]
self.states = {
self.THIRSTY: [CommandHandler("brew", self.brew), CommandHandler("wait", self.start)],
self.BREWING: [CommandHandler("pourCoffee", self.drink)],
self.DRINKING: [
CommandHandler("startCoding", self.code),
CommandHandler("drinkMore", self.drink),
CommandHandler("end", self.end),
],
self.CODING: [
CommandHandler("keepCoding", self.code),
CommandHandler("gettingThirsty", self.start),
CommandHandler("drinkMore", self.drink),
],
}
self.fallbacks = [CommandHandler("eat", self.start)]
self.is_timeout = False
# for nesting tests
self.nested_states = {
self.THIRSTY: [CommandHandler("brew", self.brew), CommandHandler("wait", self.start)],
self.BREWING: [CommandHandler("pourCoffee", self.drink)],
self.CODING: [
CommandHandler("keepCoding", self.code),
CommandHandler("gettingThirsty", self.start),
CommandHandler("drinkMore", self.drink),
],
}
self.drinking_entry_points = [CommandHandler("hold", self.hold)]
self.drinking_states = {
self.HOLDING: [CommandHandler("sip", self.sip)],
self.SIPPING: [CommandHandler("swallow", self.swallow)],
self.SWALLOWING: [CommandHandler("hold", self.hold)],
}
self.drinking_fallbacks = [
CommandHandler("replenish", self.replenish),
CommandHandler("stop", self.stop),
CommandHandler("end", self.end),
CommandHandler("startCoding", self.code),
CommandHandler("drinkMore", self.drink),
]
self.drinking_entry_points.extend(self.drinking_fallbacks)
# Map nested states to parent states:
self.drinking_map_to_parent = {
# Option 1 - Map a fictional internal state to an external parent state
self.REPLENISHING: self.BREWING,
# Option 2 - Map a fictional internal state to the END state on the parent
self.STOPPING: self.END,
# Option 3 - Map the internal END state to an external parent state
self.END: self.CODING,
# Option 4 - Map an external state to the same external parent state
self.CODING: self.CODING,
# Option 5 - Map an external state to the internal entry point
self.DRINKING: self.DRINKING,
}
# State handlers
def _set_state(self, update, state):
self.current_state[update.message.from_user.id] = state
return state
# Actions
@raise_ahs
async def start(self, update, context):
if isinstance(update, Update):
return self._set_state(update, self.THIRSTY)
return self._set_state(context.bot, self.THIRSTY)
@raise_ahs
async def end(self, update, context):
return self._set_state(update, self.END)
@raise_ahs
async def start_end(self, update, context):
return self._set_state(update, self.END)
@raise_ahs
async def start_none(self, update, context):
return self._set_state(update, None)
@raise_ahs
async def brew(self, update, context):
if isinstance(update, Update):
return self._set_state(update, self.BREWING)
return self._set_state(context.bot, self.BREWING)
@raise_ahs
async def drink(self, update, context):
return self._set_state(update, self.DRINKING)
@raise_ahs
async def code(self, update, context):
return self._set_state(update, self.CODING)
@raise_ahs
async def passout(self, update, context):
assert update.message.text == "/brew"
assert isinstance(update, Update)
self.is_timeout = True
@raise_ahs
async def passout2(self, update, context):
assert isinstance(update, Update)
self.is_timeout = True
@raise_ahs
async def passout_context(self, update, context):
assert update.message.text == "/brew"
assert isinstance(context, CallbackContext)
self.is_timeout = True
@raise_ahs
async def passout2_context(self, update, context):
assert isinstance(context, CallbackContext)
self.is_timeout = True
# Drinking actions (nested)
@raise_ahs
async def hold(self, update, context):
return self._set_state(update, self.HOLDING)
@raise_ahs
async def sip(self, update, context):
return self._set_state(update, self.SIPPING)
@raise_ahs
async def swallow(self, update, context):
return self._set_state(update, self.SWALLOWING)
@raise_ahs
async def replenish(self, update, context):
return self._set_state(update, self.REPLENISHING)
@raise_ahs
async def stop(self, update, context):
return self._set_state(update, self.STOPPING)
def test_slot_behaviour(self, mro_slots):
handler = ConversationHandler(entry_points=[], states={}, fallbacks=[])
for attr in handler.__slots__:
assert getattr(handler, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(handler)) == len(set(mro_slots(handler))), "duplicate slot"
def test_init(self):
entry_points = []
states = {}
fallbacks = []
map_to_parent = {}
ch = ConversationHandler(
entry_points=entry_points,
states=states,
fallbacks=fallbacks,
per_chat="per_chat",
per_user="per_user",
per_message="per_message",
persistent="persistent",
name="name",
allow_reentry="allow_reentry",
conversation_timeout=42,
map_to_parent=map_to_parent,
)
assert ch.entry_points is entry_points
assert ch.states is states
assert ch.fallbacks is fallbacks
assert ch.map_to_parent is map_to_parent
assert ch.per_chat == "per_chat"
assert ch.per_user == "per_user"
assert ch.per_message == "per_message"
assert ch.persistent == "persistent"
assert ch.name == "name"
assert ch.allow_reentry == "allow_reentry"
def test_init_persistent_no_name(self):
with pytest.raises(ValueError, match="can't be persistent when handler is unnamed"):
ConversationHandler(
self.entry_points, states=self.states, fallbacks=[], persistent=True
)
async def test_check_update_returns_non(self, app, user1):
"""checks some cases where updates should not be handled"""
conv_handler = ConversationHandler([], {}, [], per_message=True, per_chat=True)
assert not conv_handler.check_update("not an Update")
assert not conv_handler.check_update(Update(0))
assert not conv_handler.check_update(
Update(0, callback_query=CallbackQuery("1", from_user=user1, chat_instance="1"))
)
async def test_handlers_generate_warning(self, recwarn):
"""this function tests all handler + per_* setting combinations."""
# the warning message action needs to be set to always,
# otherwise only the first occurrence will be issued
filterwarnings(action="always", category=PTBUserWarning)
# this class doesn't do anything, its just not the Update class
class NotUpdate:
pass
recwarn.clear()
# this conversation handler has the string, string_regex, Pollhandler and TypeHandler
# which should all generate a warning no matter the per_* setting. TypeHandler should
# not when the class is Update
ConversationHandler(
entry_points=[StringCommandHandler("code", self.code)],
states={
self.BREWING: [
StringRegexHandler("code", self.code),
PollHandler(self.code),
TypeHandler(NotUpdate, self.code),
],
},
fallbacks=[TypeHandler(Update, self.code)],
)
# these handlers should all raise a warning when per_chat is True
ConversationHandler(
entry_points=[ShippingQueryHandler(self.code)],
states={
self.BREWING: [
InlineQueryHandler(self.code),
PreCheckoutQueryHandler(self.code),
PollAnswerHandler(self.code),
],
},
fallbacks=[ChosenInlineResultHandler(self.code)],
per_chat=True,
)
# the CallbackQueryHandler should *not* raise when per_message is True,
# but any other one should
ConversationHandler(
entry_points=[CallbackQueryHandler(self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CallbackQueryHandler(self.code)],
per_message=True,
)
# the CallbackQueryHandler should raise when per_message is False
ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CallbackQueryHandler(self.code)],
per_message=False,
)
# adding a nested conv to a conversation with timeout should warn
child = ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CommandHandler("code", self.code)],
)
ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [child],
},
fallbacks=[CommandHandler("code", self.code)],
conversation_timeout=42,
)
# If per_message is True, per_chat should also be True, since msg ids are not unique
ConversationHandler(
entry_points=[CallbackQueryHandler(self.code, "code")],
states={
self.BREWING: [CallbackQueryHandler(self.code, "code")],
},
fallbacks=[CallbackQueryHandler(self.code, "code")],
per_message=True,
per_chat=False,
)
# the overall number of handlers throwing a warning is 13
assert len(recwarn) == 13
# now we test the messages, they are raised in the order they are inserted
# into the conversation handler
assert str(recwarn[0].message) == (
"The `ConversationHandler` only handles updates of type `telegram.Update`. "
"StringCommandHandler handles updates of type `str`."
)
assert str(recwarn[1].message) == (
"The `ConversationHandler` only handles updates of type `telegram.Update`. "
"StringRegexHandler handles updates of type `str`."
)
assert str(recwarn[2].message) == (
"PollHandler will never trigger in a conversation since it has no information "
"about the chat or the user who voted in it. Do you mean the "
"`PollAnswerHandler`?"
)
assert str(recwarn[3].message) == (
"The `ConversationHandler` only handles updates of type `telegram.Update`. "
"The TypeHandler is set to handle NotUpdate."
)
per_faq_link = (
" Read this FAQ entry to learn more about the per_* settings: "
"https://github.com/python-telegram-bot/python-telegram-bot/wiki"
"/Frequently-Asked-Questions#what-do-the-per_-settings-in-conversationhandler-do."
)
assert str(recwarn[4].message) == (
"Updates handled by ShippingQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[5].message) == (
"Updates handled by ChosenInlineResultHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[6].message) == (
"Updates handled by InlineQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[7].message) == (
"Updates handled by PreCheckoutQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[8].message) == (
"Updates handled by PollAnswerHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[9].message) == (
"If 'per_message=True', all entry points, state handlers, and fallbacks must be "
"'CallbackQueryHandler', since no other handlers have a message context."
+ per_faq_link
)
assert str(recwarn[10].message) == (
"If 'per_message=False', 'CallbackQueryHandler' will not be tracked for "
"every message." + per_faq_link
)
assert str(recwarn[11].message) == (
"Using `conversation_timeout` with nested conversations is currently not "
"supported. You can still try to use it, but it will likely behave differently"
" from what you expect."
)
assert str(recwarn[12].message) == (
"If 'per_message=True' is used, 'per_chat=True' should also be used, "
"since message IDs are not globally unique."
)
# this for loop checks if the correct stacklevel is used when generating the warning
for warning in recwarn:
assert warning.filename == __file__, "incorrect stacklevel!"
@pytest.mark.parametrize(
"attr",
[
"entry_points",
"states",
"fallbacks",
"per_chat",
"per_user",
"per_message",
"name",
"persistent",
"allow_reentry",
"conversation_timeout",
"map_to_parent",
],
indirect=False,
)
def test_immutable(self, attr):
ch = ConversationHandler(entry_points=[], states={}, fallbacks=[])
with pytest.raises(AttributeError, match=f"You can not assign a new value to {attr}"):
setattr(ch, attr, True)
def test_per_all_false(self):
with pytest.raises(ValueError, match="can't all be 'False'"):
ConversationHandler(
entry_points=[],
states={},
fallbacks=[],
per_chat=False,
per_user=False,
per_message=False,
)
@pytest.mark.parametrize("raise_ahs", [True, False])
async def test_basic_and_app_handler_stop(self, app, bot, user1, user2, raise_ahs):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
async def callback(_, __):
self.test_flag = True
app.add_handler(TypeHandler(object, callback), group=100)
self.raise_app_handler_stop = raise_ahs
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
assert self.test_flag == (not raise_ahs)
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
assert self.test_flag == (not raise_ahs)
# Lets see if an invalid command makes sure, no state is changed.
message.text = "/nothing"
message.entities[0].length = len("/nothing")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
assert self.test_flag is True
self.test_flag = False
# Lets see if the state machine still works by pouring coffee.
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert self.test_flag == (not raise_ahs)
# Let's now verify that for another user, who did not start yet,
# the state has not been changed.
message.from_user = user2
await app.process_update(Update(update_id=0, message=message))
with pytest.raises(KeyError):
self.current_state[user2.id]
async def test_conversation_handler_end(self, caplog, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
message.text = "/end"
message.entities[0].length = len("/end")
caplog.clear()
with caplog.at_level(logging.ERROR):
await app.process_update(Update(update_id=0, message=message))
assert len(caplog.records) == 0
assert self.current_state[user1.id] == self.END
# make sure that the conversation has ended by checking that the start command is
# accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(update_id=0, message=message))
async def test_conversation_handler_fallback(self, app, bot, user1, user2):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
# first check if fallback will not trigger start when not started
message = Message(
0,
None,
self.group,
from_user=user1,
text="/eat",
entities=[MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/eat"))],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
with pytest.raises(KeyError):
self.current_state[user1.id]
# User starts the state machine.
message.text = "/start"
message.entities[0].length = len("/start")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
# Now a fallback command is issued
message.text = "/eat"
message.entities[0].length = len("/eat")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
async def test_unknown_state_warning(self, app, bot, user1, recwarn):
def build_callback(state):
async def callback(_, __):
return state
return callback
handler = ConversationHandler(
entry_points=[CommandHandler("start", build_callback(1))],
states={
1: [TypeHandler(Update, build_callback(69))],
2: [TypeHandler(Update, build_callback(42))],
},
fallbacks=self.fallbacks,
name="xyz",
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
try:
await app.process_update(Update(update_id=1, message=message))
except Exception as exc:
print(exc)
raise exc
assert len(recwarn) == 1
assert str(recwarn[0].message) == (
"'callback' returned state 69 which is unknown to the ConversationHandler xyz."
)
async def test_conversation_handler_per_chat(self, app, bot, user1, user2):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
per_user=False,
)
app.add_handler(handler)
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
# Let's now verify that for another user, who did not start yet,
# the state will be changed because they are in the same group.
message.from_user = user2
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
# Check that we're in the DRINKING state by checking that the corresponding command
# is accepted
message.from_user = user1
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
assert handler.check_update(Update(update_id=0, message=message))
message.from_user = user2
assert handler.check_update(Update(update_id=0, message=message))
async def test_conversation_handler_per_user(self, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
per_chat=False,
)
app.add_handler(handler)
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
# First check that updates without user won't be handled
message.from_user = None
assert not handler.check_update(Update(update_id=0, message=message))
message.from_user = user1
async with app:
await app.process_update(Update(update_id=0, message=message))
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
# Let's now verify that for the same user in a different group, the state will still be
# updated
message.chat = self.second_group
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
# Check that we're in the DRINKING state by checking that the corresponding command
# is accepted
message.chat = self.group
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
assert handler.check_update(Update(update_id=0, message=message))
message.chat = self.second_group
assert handler.check_update(Update(update_id=0, message=message))
@pytest.mark.parametrize("inline", [True, False])
@pytest.mark.filterwarnings("ignore: If 'per_message=True' is used, 'per_chat=True'")
async def test_conversation_handler_per_message(self, app, bot, user1, user2, inline):
async def entry(update, context):
return 1
async def one(update, context):
return 2
async def two(update, context):
return ConversationHandler.END
handler = ConversationHandler(
entry_points=[CallbackQueryHandler(entry)],
states={
1: [CallbackQueryHandler(one, pattern="^1$")],
2: [CallbackQueryHandler(two, pattern="^2$")],
},
fallbacks=[],
per_message=True,
per_chat=not inline,
)
app.add_handler(handler)
# User one, starts the state machine.
message = (
Message(0, None, self.group, from_user=user1, text="msg w/ inlinekeyboard")
if not inline
else None
)
if message:
message.set_bot(bot)
inline_message_id = "42" if inline else None
async with app:
cbq_1 = CallbackQuery(
0,
user1,
None,
message=message,
data="1",
inline_message_id=inline_message_id,
)
cbq_1.set_bot(bot)
cbq_2 = CallbackQuery(
0,
user1,
None,
message=message,
data="2",
inline_message_id=inline_message_id,
)
cbq_2.set_bot(bot)
await app.process_update(Update(update_id=0, callback_query=cbq_1))
# Make sure that we're in the correct state
assert handler.check_update(Update(0, callback_query=cbq_1))
assert not handler.check_update(Update(0, callback_query=cbq_2))
await app.process_update(Update(update_id=0, callback_query=cbq_1))
# Make sure that we're in the correct state
assert not handler.check_update(Update(0, callback_query=cbq_1))
assert handler.check_update(Update(0, callback_query=cbq_2))
# Let's now verify that for a different user in the same group, the state will not be
# updated
cbq_2.from_user = user2
await app.process_update(Update(update_id=0, callback_query=cbq_2))
cbq_2.from_user = user1
assert not handler.check_update(Update(0, callback_query=cbq_1))
assert handler.check_update(Update(0, callback_query=cbq_2))
async def test_end_on_first_message(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
app.add_handler(handler)
# User starts the state machine and immediately ends it.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
assert handler.check_update(Update(update_id=0, message=message))
async def test_end_on_first_message_non_blocking_handler(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", callback=self.start_end, block=False)],
states={},
fallbacks=[],
)
app.add_handler(handler)
# User starts the state machine with a non-blocking function that immediately ends the
# conversation. non-blocking results are resolved when the users state is queried next
# time.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
# give the task a chance to finish
await asyncio.sleep(0.1)
# Let's check that processing the same update again is accepted. this confirms that
# a) the pending state is correctly resolved
# b) the conversation has ended
assert handler.check_update(Update(0, message=message))
async def test_none_on_first_message(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, self.start_none)], states={}, fallbacks=[]
)
app.add_handler(handler)
# User starts the state machine and a callback function returns None
message = Message(0, None, self.group, from_user=user1, text="/start")
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
# Check that the same message is accepted again, i.e. the conversation immediately
# ended
assert handler.check_update(Update(0, message=message))
async def test_none_on_first_message_non_blocking_handler(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_none, block=False)],
states={},
fallbacks=[],
)
app.add_handler(handler)
# User starts the state machine with a non-blocking handler that returns None
# non-blocking results are resolved when the users state is queried next time.
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
async with app:
await app.process_update(Update(update_id=0, message=message))
# Give the task a chance to finish
await asyncio.sleep(0.1)
# Let's check that processing the same update again is accepted. this confirms that
# a) the pending state is correctly resolved
# b) the conversation has ended
assert handler.check_update(Update(0, message=message))
async def test_per_chat_message_without_chat(self, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
cbq = CallbackQuery(0, user1, None, None)
cbq.set_bot(bot)
update = Update(0, callback_query=cbq)
assert not handler.check_update(update)
async def test_channel_message_without_chat(self, bot):
handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, self.start_end)], states={}, fallbacks=[]
)
message = Message(0, date=None, chat=Chat(0, Chat.CHANNEL, "Misses Test"))
message.set_bot(bot)
update = Update(0, channel_post=message)
assert not handler.check_update(update)
update = Update(0, edited_channel_post=message)
assert not handler.check_update(update)
async def test_all_update_types(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
message = Message(0, None, self.group, from_user=user1, text="ignore")
message.set_bot(bot)
callback_query = CallbackQuery(0, user1, None, message=message, data="data")
callback_query.set_bot(bot)
chosen_inline_result = ChosenInlineResult(0, user1, "query")
chosen_inline_result.set_bot(bot)
inline_query = InlineQuery(0, user1, "query", offset="")
inline_query.set_bot(bot)
pre_checkout_query = PreCheckoutQuery(0, user1, "USD", 100, [])
pre_checkout_query.set_bot(bot)
shipping_query = ShippingQuery(0, user1, [], None)
shipping_query.set_bot(bot)
assert not handler.check_update(Update(0, callback_query=callback_query))
assert not handler.check_update(Update(0, chosen_inline_result=chosen_inline_result))
assert not handler.check_update(Update(0, inline_query=inline_query))
assert not handler.check_update(Update(0, message=message))
assert not handler.check_update(Update(0, pre_checkout_query=pre_checkout_query))
assert not handler.check_update(Update(0, shipping_query=shipping_query))
@pytest.mark.parametrize("jq", [True, False])
async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
# save app.job_queue in temp variable jqueue
# and then set app.job_queue to None.