forked from python-telegram-bot/python-telegram-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_basepersistence.py
More file actions
1478 lines (1262 loc) · 58.2 KB
/
test_basepersistence.py
File metadata and controls
1478 lines (1262 loc) · 58.2 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-2022
# Leandro Toledo de Souza <[email protected]>
#
# 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 collections
import copy
import enum
import functools
import logging
import time
from pathlib import Path
from typing import NamedTuple
import pytest
from flaky import flaky
from telegram import Bot, Chat, InlineKeyboardButton, InlineKeyboardMarkup, Update, User
from telegram.ext import (
Application,
ApplicationBuilder,
ApplicationHandlerStop,
BaseHandler,
BasePersistence,
CallbackContext,
ConversationHandler,
ExtBot,
MessageHandler,
PersistenceInput,
filters,
)
from telegram.warnings import PTBUserWarning
from tests.conftest import DictApplication, make_message_update
class HandlerStates(int, enum.Enum):
END = ConversationHandler.END
STATE_1 = 1
STATE_2 = 2
STATE_3 = 3
STATE_4 = 4
def next(self):
cls = self.__class__
members = list(cls)
index = members.index(self) + 1
if index >= len(members):
index = 0
return members[index]
class TrackingPersistence(BasePersistence):
"""A dummy implementation of BasePersistence that will help us a great deal in keeping
the individual tests as short as reasonably possible."""
def __init__(
self,
store_data: PersistenceInput = None,
update_interval: float = 60,
fill_data: bool = False,
):
super().__init__(store_data=store_data, update_interval=update_interval)
self.updated_chat_ids = collections.Counter()
self.updated_user_ids = collections.Counter()
self.refreshed_chat_ids = collections.Counter()
self.refreshed_user_ids = collections.Counter()
self.dropped_chat_ids = collections.Counter()
self.dropped_user_ids = collections.Counter()
self.updated_conversations = collections.defaultdict(collections.Counter)
self.updated_bot_data: bool = False
self.refreshed_bot_data: bool = False
self.updated_callback_data: bool = False
self.flushed = False
self.chat_data = collections.defaultdict(dict)
self.user_data = collections.defaultdict(dict)
self.conversations = collections.defaultdict(dict)
self.bot_data = {}
self.callback_data = ([], {})
if fill_data:
self.fill()
CALLBACK_DATA = (
[("uuid", time.time(), {"uuid4": "callback_data"})],
{"query_id": "keyboard_id"},
)
def fill(self):
self.chat_data[1]["key"] = "value"
self.chat_data[2]["foo"] = "bar"
self.user_data[1]["key"] = "value"
self.user_data[2]["foo"] = "bar"
self.bot_data["key"] = "value"
self.conversations["conv_1"][(1, 1)] = HandlerStates.STATE_1
self.conversations["conv_1"][(2, 2)] = HandlerStates.STATE_2
self.conversations["conv_2"][(3, 3)] = HandlerStates.STATE_3
self.conversations["conv_2"][(4, 4)] = HandlerStates.STATE_4
self.callback_data = self.CALLBACK_DATA
def reset_tracking(self):
self.updated_user_ids.clear()
self.updated_chat_ids.clear()
self.dropped_user_ids.clear()
self.dropped_chat_ids.clear()
self.refreshed_chat_ids = collections.Counter()
self.refreshed_user_ids = collections.Counter()
self.updated_conversations.clear()
self.updated_bot_data = False
self.refreshed_bot_data = False
self.updated_callback_data = False
self.flushed = False
self.chat_data = {}
self.user_data = {}
self.conversations = collections.defaultdict(dict)
self.bot_data = {}
self.callback_data = ([], {})
async def update_bot_data(self, data):
self.updated_bot_data = True
self.bot_data = data
async def update_chat_data(self, chat_id: int, data):
self.updated_chat_ids[chat_id] += 1
self.chat_data[chat_id] = data
async def update_user_data(self, user_id: int, data):
self.updated_user_ids[user_id] += 1
self.user_data[user_id] = data
async def update_conversation(self, name: str, key, new_state):
self.updated_conversations[name][key] += 1
self.conversations[name][key] = new_state
async def update_callback_data(self, data):
self.updated_callback_data = True
self.callback_data = data
async def get_conversations(self, name):
return self.conversations.get(name, {})
async def get_bot_data(self):
return copy.deepcopy(self.bot_data)
async def get_chat_data(self):
return copy.deepcopy(self.chat_data)
async def get_user_data(self):
return copy.deepcopy(self.user_data)
async def get_callback_data(self):
return copy.deepcopy(self.callback_data)
async def drop_chat_data(self, chat_id):
self.dropped_chat_ids[chat_id] += 1
self.chat_data.pop(chat_id, None)
async def drop_user_data(self, user_id):
self.dropped_user_ids[user_id] += 1
self.user_data.pop(user_id, None)
async def refresh_user_data(self, user_id: int, user_data: dict):
self.refreshed_user_ids[user_id] += 1
user_data["refreshed"] = True
async def refresh_chat_data(self, chat_id: int, chat_data: dict):
self.refreshed_chat_ids[chat_id] += 1
chat_data["refreshed"] = True
async def refresh_bot_data(self, bot_data: dict):
self.refreshed_bot_data = True
bot_data["refreshed"] = True
async def flush(self) -> None:
self.flushed = True
class TrackingConversationHandler(ConversationHandler):
def __init__(self, *args, **kwargs):
fallbacks = []
states = {state.value: [self.build_handler(state)] for state in HandlerStates}
entry_points = [self.build_handler(HandlerStates.END)]
super().__init__(
*args, **kwargs, fallbacks=fallbacks, states=states, entry_points=entry_points
)
@staticmethod
async def callback(update, context, state):
return state.next()
@staticmethod
def build_update(state: HandlerStates, chat_id: int):
user = User(id=chat_id, first_name="", is_bot=False)
chat = Chat(id=chat_id, type="")
return make_message_update(message=str(state.value), user=user, chat=chat)
@classmethod
def build_handler(cls, state: HandlerStates, callback=None):
return MessageHandler(
filters.Regex(f"^{state.value}$"),
callback or functools.partial(cls.callback, state=state),
)
class PappInput(NamedTuple):
bot_data: bool = None
chat_data: bool = None
user_data: bool = None
callback_data: bool = None
conversations: bool = True
update_interval: float = None
fill_data: bool = False
def build_papp(
token: str, store_data: dict = None, update_interval: float = None, fill_data: bool = False
) -> Application:
store_data = PersistenceInput(**(store_data or {}))
if update_interval is not None:
persistence = TrackingPersistence(
store_data=store_data, update_interval=update_interval, fill_data=fill_data
)
else:
persistence = TrackingPersistence(store_data=store_data, fill_data=fill_data)
return (
ApplicationBuilder()
.token(token)
.persistence(persistence)
.application_class(DictApplication)
.arbitrary_callback_data(True)
.build()
)
def build_conversation_handler(name: str, persistent: bool = True) -> BaseHandler:
return TrackingConversationHandler(name=name, persistent=persistent)
@pytest.fixture(scope="function")
def papp(request, bot) -> Application:
papp_input = request.param
store_data = {}
if papp_input.bot_data is not None:
store_data["bot_data"] = papp_input.bot_data
if papp_input.chat_data is not None:
store_data["chat_data"] = papp_input.chat_data
if papp_input.user_data is not None:
store_data["user_data"] = papp_input.user_data
if papp_input.callback_data is not None:
store_data["callback_data"] = papp_input.callback_data
app = build_papp(
bot.token,
store_data=store_data,
update_interval=papp_input.update_interval,
fill_data=papp_input.fill_data,
)
app.add_handlers(
[
build_conversation_handler(name="conv_1", persistent=papp_input.conversations),
build_conversation_handler(name="conv_2", persistent=papp_input.conversations),
]
)
return app
# Decorator shortcuts
default_papp = pytest.mark.parametrize("papp", [PappInput()], indirect=True)
filled_papp = pytest.mark.parametrize("papp", [PappInput(fill_data=True)], indirect=True)
papp_store_all_or_none = pytest.mark.parametrize(
"papp",
[
PappInput(),
PappInput(False, False, False, False),
],
ids=(
"all_data",
"no_data",
),
indirect=True,
)
class TestBasePersistence:
"""Tests basic behavior of BasePersistence and (most importantly) the integration of
persistence into the Application."""
def job_callback(self, chat_id: int = None):
async def callback(context):
if context.user_data:
context.user_data["key"] = "value"
if context.chat_data:
context.chat_data["key"] = "value"
context.bot_data["key"] = "value"
if chat_id:
await context.bot.send_message(
chat_id=chat_id,
text="text",
reply_markup=InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="callback_data")
),
)
return callback
def handler_callback(self, chat_id: int = None, sleep: float = None):
async def callback(update, context):
if sleep:
await asyncio.sleep(sleep)
context.user_data["key"] = "value"
context.chat_data["key"] = "value"
context.bot_data["key"] = "value"
if chat_id:
await context.bot.send_message(
chat_id=chat_id,
text="text",
reply_markup=InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="callback_data")
),
)
raise ApplicationHandlerStop
return callback
def test_slot_behaviour(self, mro_slots):
inst = TrackingPersistence()
for attr in inst.__slots__:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
# We're interested in BasePersistence, not in the implementation
slots = mro_slots(inst, only_parents=True)
assert len(slots) == len(set(slots)), "duplicate slot"
@pytest.mark.parametrize("bot_data", (True, False))
@pytest.mark.parametrize("chat_data", (True, False))
@pytest.mark.parametrize("user_data", (True, False))
@pytest.mark.parametrize("callback_data", (True, False))
def test_init_store_data_update_interval(self, bot_data, chat_data, user_data, callback_data):
store_data = PersistenceInput(
bot_data=bot_data,
chat_data=chat_data,
user_data=user_data,
callback_data=callback_data,
)
persistence = TrackingPersistence(store_data=store_data, update_interval=3.14)
assert persistence.store_data.bot_data == bot_data
assert persistence.store_data.chat_data == chat_data
assert persistence.store_data.user_data == user_data
assert persistence.store_data.callback_data == callback_data
def test_abstract_methods(self):
with pytest.raises(
TypeError,
match=(
"drop_chat_data, drop_user_data, flush, get_bot_data, get_callback_data, "
"get_chat_data, get_conversations, "
"get_user_data, refresh_bot_data, refresh_chat_data, "
"refresh_user_data, update_bot_data, update_callback_data, "
"update_chat_data, update_conversation, update_user_data"
),
):
BasePersistence()
@default_papp
def test_update_interval_immutable(self, papp):
with pytest.raises(AttributeError, match="can not assign a new value to update_interval"):
papp.persistence.update_interval = 7
@default_papp
def test_set_bot_error(self, papp):
with pytest.raises(TypeError, match="when using telegram.ext.ExtBot"):
papp.persistence.set_bot(Bot(papp.bot.token))
with pytest.raises(TypeError, match="when using telegram.ext.ExtBot"):
papp.persistence.set_bot(ExtBot(papp.bot.token))
def test_construction_with_bad_persistence(self, caplog, bot):
class MyPersistence:
def __init__(self):
self.store_data = PersistenceInput(False, False, False, False)
with pytest.raises(
TypeError, match="persistence must be based on telegram.ext.BasePersistence"
):
ApplicationBuilder().bot(bot).persistence(MyPersistence()).build()
@pytest.mark.parametrize(
"papp",
[PappInput(fill_data=True), PappInput(False, False, False, False, False, fill_data=True)],
indirect=True,
)
async def test_initialization_basic(self, papp: Application):
# Check that no data is there before init
assert not papp.chat_data
assert not papp.user_data
assert not papp.bot_data
assert papp.bot.callback_data_cache.persistence_data == ([], {})
assert not papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
)
assert not papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_2, chat_id=2)
)
assert not papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_3, chat_id=3)
)
assert not papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_4, chat_id=4)
)
async with papp:
# Check that data is loaded on init
# We check just bot_data because we set all to the same value
if papp.persistence.store_data.bot_data:
assert papp.chat_data[1]["key"] == "value"
assert papp.chat_data[2]["foo"] == "bar"
assert papp.user_data[1]["key"] == "value"
assert papp.user_data[2]["foo"] == "bar"
assert papp.bot_data == {"key": "value"}
assert (
papp.bot.callback_data_cache.persistence_data
== TrackingPersistence.CALLBACK_DATA
)
assert papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
)
assert papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_2, chat_id=2)
)
assert papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_3, chat_id=3)
)
assert papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_4, chat_id=4)
)
else:
assert not papp.chat_data
assert not papp.user_data
assert not papp.bot_data
assert papp.bot.callback_data_cache.persistence_data == ([], {})
assert not papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
)
assert not papp.handlers[0][0].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_2, chat_id=2)
)
assert not papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_3, chat_id=3)
)
assert not papp.handlers[0][1].check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_4, chat_id=4)
)
@pytest.mark.parametrize(
"papp",
[PappInput(fill_data=True)],
indirect=True,
)
async def test_initialization_invalid_bot_data(self, papp: Application, monkeypatch):
async def get_bot_data(*args, **kwargs):
return "invalid"
monkeypatch.setattr(papp.persistence, "get_bot_data", get_bot_data)
with pytest.raises(ValueError, match="bot_data must be"):
await papp.initialize()
@pytest.mark.parametrize(
"papp",
[PappInput(fill_data=True)],
indirect=True,
)
@pytest.mark.parametrize("callback_data", ("invalid", (1, 2, 3)))
async def test_initialization_invalid_callback_data(
self, papp: Application, callback_data, monkeypatch
):
async def get_callback_data(*args, **kwargs):
return callback_data
monkeypatch.setattr(papp.persistence, "get_callback_data", get_callback_data)
with pytest.raises(ValueError, match="callback_data must be"):
await papp.initialize()
@filled_papp
async def test_add_conversation_handler_after_init(self, papp: Application, recwarn):
context = CallbackContext(application=papp)
# Set it up such that the handler has a conversation in progress that's not persisted
papp.persistence.conversations["conv_1"].pop((2, 2))
conversation = build_conversation_handler("conv_1", persistent=True)
update = TrackingConversationHandler.build_update(state=HandlerStates.END, chat_id=2)
check = conversation.check_update(update=update)
await conversation.handle_update(
update=update, check_result=check, application=papp, context=context
)
assert conversation.check_update(
TrackingConversationHandler.build_update(state=HandlerStates.STATE_1, chat_id=2)
)
# and another one that will be overridden
update = TrackingConversationHandler.build_update(state=HandlerStates.END, chat_id=1)
check = conversation.check_update(update=update)
await conversation.handle_update(
update=update, check_result=check, application=papp, context=context
)
update = TrackingConversationHandler.build_update(state=HandlerStates.STATE_1, chat_id=1)
check = conversation.check_update(update=update)
await conversation.handle_update(
update=update, check_result=check, application=papp, context=context
)
assert conversation.check_update(
TrackingConversationHandler.build_update(state=HandlerStates.STATE_2, chat_id=1)
)
async with papp:
papp.add_handler(conversation)
assert len(recwarn) >= 1
found = False
for warning in recwarn:
if "after `Application.initialize` was called" in str(warning.message):
found = True
assert warning.category is PTBUserWarning
assert Path(warning.filename) == Path(__file__), "incorrect stacklevel!"
assert found
await asyncio.sleep(0.05)
# conversation with chat_id 2 must not have been overridden
assert conversation.check_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=2)
)
# conversation with chat_id 1 must have been overridden
assert not conversation.check_update(
TrackingConversationHandler.build_update(state=HandlerStates.STATE_2, chat_id=1)
)
assert conversation.check_update(
TrackingConversationHandler.build_update(state=HandlerStates.STATE_1, chat_id=1)
)
def test_add_conversation_without_persistence(self, app):
with pytest.raises(ValueError, match="if application has no persistence"):
app.add_handler(build_conversation_handler("name", persistent=True))
@default_papp
async def test_add_conversation_handler_without_name(self, papp: Application):
with pytest.raises(ValueError, match="when handler is unnamed"):
papp.add_handler(build_conversation_handler(name=None, persistent=True))
@flaky(3, 1)
@pytest.mark.parametrize(
"papp",
[
PappInput(update_interval=1.5),
],
indirect=True,
)
async def test_update_interval(self, papp: Application, monkeypatch):
"""If we don't want this test to take much longer to run, the accuracy will be a bit low.
A few tenths of seconds are easy to go astray ... That's why it's flaky."""
call_times = []
async def update_persistence(*args, **kwargs):
call_times.append(time.time())
monkeypatch.setattr(papp, "update_persistence", update_persistence)
async with papp:
await papp.start()
await asyncio.sleep(5)
await papp.stop()
# Make assertions before calling shutdown, as that calls update_persistence again!
diffs = [j - i for i, j in zip(call_times[:-1], call_times[1:])]
assert sum(diffs) / len(diffs) == pytest.approx(
papp.persistence.update_interval, rel=1e-1
)
@papp_store_all_or_none
async def test_update_persistence_loop_call_count_update_handling(
self, papp: Application, caplog
):
async with papp:
for _ in range(5):
# second pass processes update in conv_2
await papp.process_update(
TrackingConversationHandler.build_update(HandlerStates.END, chat_id=1)
)
assert not papp.persistence.updated_bot_data
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert not papp.persistence.updated_callback_data
assert not papp.persistence.updated_conversations
await papp.update_persistence()
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
if papp.persistence.store_data.user_data:
assert papp.persistence.updated_user_ids == {1: 1}
else:
assert not papp.persistence.updated_user_ids
if papp.persistence.store_data.chat_data:
assert papp.persistence.updated_chat_ids == {1: 1}
else:
assert not papp.persistence.updated_chat_ids
assert papp.persistence.updated_conversations == {
"conv_1": {(1, 1): 1},
"conv_2": {(1, 1): 1},
}
# Nothing should have been updated after handling nothing
papp.persistence.reset_tracking()
with caplog.at_level(logging.ERROR):
await papp.update_persistence()
# Make sure that "nothing updated" is not just due to an error
assert not caplog.text
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.updated_conversations
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
# Nothing should have been updated after handling an update without associated
# user/chat_data
papp.persistence.reset_tracking()
await papp.process_update("string_update")
with caplog.at_level(logging.ERROR):
await papp.update_persistence()
# Make sure that "nothing updated" is not just due to an error
assert not caplog.text
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.updated_conversations
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
@papp_store_all_or_none
async def test_update_persistence_loop_call_count_job(self, papp: Application, caplog):
async with papp:
await papp.job_queue.start()
papp.job_queue.run_once(self.job_callback(), when=1.5, chat_id=1, user_id=1)
await asyncio.sleep(2.5)
assert not papp.persistence.updated_bot_data
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert not papp.persistence.updated_callback_data
assert not papp.persistence.updated_conversations
await papp.update_persistence()
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
if papp.persistence.store_data.user_data:
assert papp.persistence.updated_user_ids == {1: 1}
else:
assert not papp.persistence.updated_user_ids
if papp.persistence.store_data.chat_data:
assert papp.persistence.updated_chat_ids == {1: 1}
else:
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_conversations
# Nothing should have been updated after no job ran
papp.persistence.reset_tracking()
with caplog.at_level(logging.ERROR):
await papp.update_persistence()
# Make sure that "nothing updated" is not just due to an error
assert not caplog.text
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.updated_conversations
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
# Nothing should have been updated after running job without associated user/chat_data
papp.persistence.reset_tracking()
papp.job_queue.run_once(self.job_callback(), when=0.1)
await asyncio.sleep(0.2)
with caplog.at_level(logging.ERROR):
await papp.update_persistence()
# Make sure that "nothing updated" is not just due to an error
assert not caplog.text
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.updated_conversations
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
@default_papp
async def test_calls_on_shutdown(self, papp, chat_id):
papp.add_handler(
MessageHandler(filters.ALL, callback=self.handler_callback(chat_id=chat_id)), group=-1
)
async with papp:
await papp.process_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
)
assert not papp.persistence.updated_bot_data
assert not papp.persistence.updated_callback_data
assert not papp.persistence.updated_user_ids
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_conversations
assert not papp.persistence.flushed
# Make sure this this outside the context manager, which is where shutdown is called!
assert papp.persistence.updated_bot_data
assert papp.persistence.bot_data == {"key": "value", "refreshed": True}
assert papp.persistence.updated_callback_data
assert papp.persistence.callback_data[1] == {}
assert len(papp.persistence.callback_data[0]) == 1
assert papp.persistence.updated_user_ids == {1: 1}
assert papp.persistence.user_data == {1: {"key": "value", "refreshed": True}}
assert papp.persistence.updated_chat_ids == {1: 1}
assert papp.persistence.chat_data == {1: {"key": "value", "refreshed": True}}
assert not papp.persistence.updated_conversations
assert not papp.persistence.conversations
assert papp.persistence.flushed
@papp_store_all_or_none
async def test_update_persistence_loop_saved_data_update_handling(
self, papp: Application, chat_id
):
papp.add_handler(
MessageHandler(filters.ALL, callback=self.handler_callback(chat_id=chat_id)), group=-1
)
async with papp:
await papp.process_update(
TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
)
assert not papp.persistence.bot_data
assert papp.persistence.bot_data is not papp.bot_data
assert not papp.persistence.chat_data
assert papp.persistence.chat_data is not papp.chat_data
assert not papp.persistence.user_data
assert papp.persistence.user_data is not papp.user_data
assert papp.persistence.callback_data == ([], {})
assert (
papp.persistence.callback_data is not papp.bot.callback_data_cache.persistence_data
)
assert not papp.persistence.conversations
await papp.update_persistence()
assert papp.persistence.bot_data is not papp.bot_data
if papp.persistence.store_data.bot_data:
assert papp.persistence.bot_data == {"key": "value", "refreshed": True}
else:
assert not papp.persistence.bot_data
assert papp.persistence.chat_data is not papp.chat_data
if papp.persistence.store_data.chat_data:
assert papp.persistence.chat_data == {1: {"key": "value", "refreshed": True}}
assert papp.persistence.chat_data[1] is not papp.chat_data[1]
else:
assert not papp.persistence.chat_data
assert papp.persistence.user_data is not papp.user_data
if papp.persistence.store_data.user_data:
assert papp.persistence.user_data == {1: {"key": "value", "refreshed": True}}
assert papp.persistence.user_data[1] is not papp.chat_data[1]
else:
assert not papp.persistence.user_data
assert (
papp.persistence.callback_data is not papp.bot.callback_data_cache.persistence_data
)
if papp.persistence.store_data.callback_data:
assert papp.persistence.callback_data[1] == {}
assert len(papp.persistence.callback_data[0]) == 1
else:
assert papp.persistence.callback_data == ([], {})
assert not papp.persistence.conversations
@papp_store_all_or_none
async def test_update_persistence_loop_saved_data_job(self, papp: Application, chat_id):
papp.add_handler(
MessageHandler(filters.ALL, callback=self.handler_callback(chat_id=chat_id)), group=-1
)
async with papp:
await papp.job_queue.start()
papp.job_queue.run_once(
self.job_callback(chat_id=chat_id), when=1.5, chat_id=1, user_id=1
)
await asyncio.sleep(2.5)
assert not papp.persistence.bot_data
assert papp.persistence.bot_data is not papp.bot_data
assert not papp.persistence.chat_data
assert papp.persistence.chat_data is not papp.chat_data
assert not papp.persistence.user_data
assert papp.persistence.user_data is not papp.user_data
assert papp.persistence.callback_data == ([], {})
assert (
papp.persistence.callback_data is not papp.bot.callback_data_cache.persistence_data
)
assert not papp.persistence.conversations
await papp.update_persistence()
assert papp.persistence.bot_data is not papp.bot_data
if papp.persistence.store_data.bot_data:
assert papp.persistence.bot_data == {"key": "value", "refreshed": True}
else:
assert not papp.persistence.bot_data
assert papp.persistence.chat_data is not papp.chat_data
if papp.persistence.store_data.chat_data:
assert papp.persistence.chat_data == {1: {"key": "value", "refreshed": True}}
assert papp.persistence.chat_data[1] is not papp.chat_data[1]
else:
assert not papp.persistence.chat_data
assert papp.persistence.user_data is not papp.user_data
if papp.persistence.store_data.user_data:
assert papp.persistence.user_data == {1: {"key": "value", "refreshed": True}}
assert papp.persistence.user_data[1] is not papp.chat_data[1]
else:
assert not papp.persistence.user_data
assert (
papp.persistence.callback_data is not papp.bot.callback_data_cache.persistence_data
)
if papp.persistence.store_data.callback_data:
assert papp.persistence.callback_data[1] == {}
assert len(papp.persistence.callback_data[0]) == 1
else:
assert papp.persistence.callback_data == ([], {})
assert not papp.persistence.conversations
@default_papp
@pytest.mark.parametrize("delay_type", ("job", "handler", "task"))
async def test_update_persistence_loop_async_logic(
self, papp: Application, delay_type: str, chat_id
):
"""All three kinds of 'asyncio background processes' should mark things for update once
they're done."""
sleep = 1.5
update = TrackingConversationHandler.build_update(HandlerStates.STATE_1, chat_id=1)
async with papp:
if delay_type == "job":
await papp.job_queue.start()
papp.job_queue.run_once(self.job_callback(), when=sleep, chat_id=1, user_id=1)
elif delay_type == "handler":
papp.add_handler(
MessageHandler(
filters.ALL,
self.handler_callback(sleep=sleep),
block=False,
)
)
await papp.process_update(update)
else:
papp.create_task(asyncio.sleep(sleep), update=update)
await papp.update_persistence()
assert papp.persistence.updated_bot_data
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_user_ids
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert papp.persistence.updated_callback_data
assert not papp.persistence.updated_conversations
# Wait for the asyncio process to be done
await asyncio.sleep(sleep + 1)
await papp.update_persistence()
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.dropped_user_ids
assert papp.persistence.updated_bot_data == papp.persistence.store_data.bot_data
assert (
papp.persistence.updated_callback_data == papp.persistence.store_data.callback_data
)
if papp.persistence.store_data.user_data:
assert papp.persistence.updated_user_ids == {1: 1}
else:
assert not papp.persistence.updated_user_ids
if papp.persistence.store_data.chat_data:
assert papp.persistence.updated_chat_ids == {1: 1}
else:
assert not papp.persistence.updated_chat_ids
assert not papp.persistence.updated_conversations
@filled_papp
async def test_drop_chat_data(self, papp: Application):
async with papp:
assert papp.persistence.chat_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.updated_chat_ids
papp.drop_chat_data(1)
assert papp.persistence.chat_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.updated_chat_ids
await papp.update_persistence()
assert papp.persistence.chat_data == {2: {"foo": "bar"}}
assert papp.persistence.dropped_chat_ids == {1: 1}
assert not papp.persistence.updated_chat_ids
@filled_papp
async def test_drop_user_data(self, papp: Application):
async with papp:
assert papp.persistence.user_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_user_ids
assert not papp.persistence.updated_user_ids
papp.drop_user_data(1)
assert papp.persistence.user_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_user_ids
assert not papp.persistence.updated_user_ids
await papp.update_persistence()
assert papp.persistence.user_data == {2: {"foo": "bar"}}
assert papp.persistence.dropped_user_ids == {1: 1}
assert not papp.persistence.updated_user_ids
@filled_papp
async def test_migrate_chat_data(self, papp: Application):
async with papp:
assert papp.persistence.chat_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.updated_chat_ids
papp.migrate_chat_data(old_chat_id=1, new_chat_id=2)
assert papp.persistence.chat_data == {1: {"key": "value"}, 2: {"foo": "bar"}}
assert not papp.persistence.dropped_chat_ids
assert not papp.persistence.updated_chat_ids
await papp.update_persistence()
assert papp.persistence.chat_data == {2: {"key": "value"}}
assert papp.persistence.dropped_chat_ids == {1: 1}
assert papp.persistence.updated_chat_ids == {2: 1}
async def test_errors_while_persisting(self, bot, caplog):
class ErrorPersistence(TrackingPersistence):