-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathtest_synchronizer.py
More file actions
1157 lines (954 loc) · 49.3 KB
/
Copy pathtest_synchronizer.py
File metadata and controls
1157 lines (954 loc) · 49.3 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
"""Synchronizer tests."""
import unittest.mock as mock
import pytest
import queue
import asyncio
from splitio.sync.synchronizer import Synchronizer, SynchronizerAsync, SplitTasks, SplitSynchronizers, LocalhostSynchronizer, LocalhostSynchronizerAsync, RedisSynchronizer, RedisSynchronizerAsync
from splitio.tasks.split_sync import SplitSynchronizationTask, SplitSynchronizationTaskAsync
from splitio.tasks.unique_keys_sync import UniqueKeysSyncTask, ClearFilterSyncTask, UniqueKeysSyncTaskAsync, ClearFilterSyncTaskAsync
from splitio.tasks.segment_sync import SegmentSynchronizationTask, SegmentSynchronizationTaskAsync
from splitio.tasks.impressions_sync import ImpressionsSyncTask, ImpressionsCountSyncTask, ImpressionsCountSyncTaskAsync, ImpressionsSyncTaskAsync
from splitio.tasks.events_sync import EventsSyncTask, EventsSyncTaskAsync
from splitio.sync.split import SplitSynchronizer, SplitSynchronizerAsync, LocalSplitSynchronizer, LocalhostMode, LocalSplitSynchronizerAsync
from splitio.sync.segment import SegmentSynchronizer, SegmentSynchronizerAsync, LocalSegmentSynchronizer, LocalSegmentSynchronizerAsync
from splitio.sync.impression import ImpressionSynchronizer, ImpressionSynchronizerAsync, ImpressionsCountSynchronizer, ImpressionsCountSynchronizerAsync
from splitio.sync.event import EventSynchronizer, EventSynchronizerAsync
from splitio.storage import SegmentStorage, SplitStorage, RuleBasedSegmentsStorage
from splitio.api import APIException, APIUriException
from splitio.models.splits import Split
from splitio.models.segments import Segment
from splitio.storage.inmemmory import InMemorySegmentStorage, InMemorySplitStorage, InMemorySegmentStorageAsync, InMemorySplitStorageAsync, \
InMemoryRuleBasedSegmentStorage, InMemoryRuleBasedSegmentStorageAsync
splits = [{
'changeNumber': 123,
'trafficTypeName': 'user',
'name': 'some_name',
'trafficAllocation': 100,
'trafficAllocationSeed': 123456,
'seed': 321654,
'status': 'ACTIVE',
'killed': False,
'defaultTreatment': 'off',
'algo': 2,
'conditions': [{
'conditionType': 'WHITELIST',
'matcherGroup':{
'combiner': 'AND',
'matchers':[{
'matcherType': 'IN_SEGMENT',
'negate': False,
'userDefinedSegmentMatcherData': {
'segmentName': 'segmentA'
}
}]
},
'partitions': [{
'size': 100,
'treatment': 'on'
}]
}]
}]
class SynchronizerTests(object):
def test_sync_all_failed_splits(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
storage.flag_set_filter = flag_set_filter
storage.flag_set_filter.flag_sets = {}
storage.flag_set_filter.sorted_flag_sets = []
def run(x, y, c):
raise APIException("something broke")
api.fetch_splits.side_effect = run
split_sync = SplitSynchronizer(api, storage, mocker.Mock())
split_synchronizers = SplitSynchronizers(split_sync, mocker.Mock(), mocker.Mock(),
mocker.Mock(), mocker.Mock())
sychronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
sychronizer.synchronize_splits(None) # APIExceptions are handled locally and should not be propagated!
# test forcing to have only one retry attempt and then exit
sychronizer.sync_all(1) # sync_all should not throw!
def test_sync_all_failed_splits_with_flagsets(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
storage.flag_set_filter = flag_set_filter
storage.flag_set_filter.flag_sets = {}
storage.flag_set_filter.sorted_flag_sets = []
def run(x, y, c):
raise APIException("something broke", 414)
api.fetch_splits.side_effect = run
split_sync = SplitSynchronizer(api, storage, mocker.Mock())
split_synchronizers = SplitSynchronizers(split_sync, mocker.Mock(), mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
synchronizer.synchronize_splits(None)
synchronizer.sync_all(3)
assert synchronizer._backoff._attempt == 0
def test_sync_all_failed_segments(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
split_storage = mocker.Mock(spec=SplitStorage)
split_storage.get_segment_names.return_value = ['segmentA']
rbs_storage = mocker.Mock(spec=RuleBasedSegmentsStorage)
rbs_storage.get_segment_names.return_value = []
split_sync = mocker.Mock(spec=SplitSynchronizer)
split_sync.synchronize_splits.return_value = None
def run(x, y, c):
raise APIException("something broke")
api.fetch_segment.side_effect = run
segment_sync = SegmentSynchronizer(api, split_storage, storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
sychronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
sychronizer.sync_all(1) # SyncAll should not throw!
assert not sychronizer._synchronize_segments()
def test_synchronize_splits(self, mocker):
events_queue = queue.Queue()
split_storage = InMemorySplitStorage(events_queue)
rbs_storage = InMemoryRuleBasedSegmentStorage(events_queue)
split_api = mocker.Mock()
split_api.fetch_splits.return_value = {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_sync = SplitSynchronizer(split_api, split_storage, rbs_storage)
segment_storage = InMemorySegmentStorage(events_queue)
segment_api = mocker.Mock()
segment_api.fetch_segment.return_value = {'name': 'segmentA', 'added': ['key1', 'key2',
'key3'], 'removed': [], 'since': 123, 'till': 123}
segment_sync = SegmentSynchronizer(segment_api, split_storage, segment_storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
synchronizer.synchronize_splits(123)
inserted_split = split_storage.get('some_name')
assert isinstance(inserted_split, Split)
assert inserted_split.name == 'some_name'
if not segment_sync._worker_pool.wait_for_completion():
inserted_segment = segment_storage.get('segmentA')
assert inserted_segment.name == 'segmentA'
assert inserted_segment.keys == {'key1', 'key2', 'key3'}
def test_synchronize_splits_calling_segment_sync_once(self, mocker):
events_queue = queue.Queue()
split_storage = InMemorySplitStorage(events_queue)
rbs_storage = InMemoryRuleBasedSegmentStorage(events_queue)
split_api = mocker.Mock()
split_api.fetch_splits.return_value = {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_sync = SplitSynchronizer(split_api, split_storage, rbs_storage)
counts = {'segments': 0}
def sync_segments(*_):
"""Sync Segments."""
counts['segments'] += 1
return True
segment_sync = mocker.Mock()
segment_sync.synchronize_segments.side_effect = sync_segments
segment_sync.segment_exist_in_storage.return_value = False
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
synchronizer.synchronize_splits(123, True)
assert counts['segments'] == 1
def test_sync_all(self, mocker):
split_storage = mocker.Mock(spec=SplitStorage)
rbs_storage = mocker.Mock(spec=RuleBasedSegmentsStorage)
rbs_storage.get_segment_names.return_value = []
split_storage.get_change_number.return_value = 123
split_storage.get_segment_names.return_value = ['segmentA']
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
split_storage.flag_set_filter = flag_set_filter
split_storage.flag_set_filter.flag_sets = {}
split_storage.flag_set_filter.sorted_flag_sets = []
split_api = mocker.Mock()
split_api.fetch_splits.return_value = {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_sync = SplitSynchronizer(split_api, split_storage, rbs_storage)
segment_storage = mocker.Mock(spec=SegmentStorage)
segment_storage.get_change_number.return_value = 123
segment_api = mocker.Mock()
segment_api.fetch_segment.return_value = {'name': 'segmentA', 'added': ['key1', 'key2',
'key3'], 'removed': [], 'since': 123, 'till': 123}
segment_sync = SegmentSynchronizer(segment_api, split_storage, segment_storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = Synchronizer(split_synchronizers, mocker.Mock(spec=SplitTasks))
self.clear = False
def clear():
self.clear = True
split_storage.clear = clear
rbs_storage.clear = clear
synchronizer.sync_all()
inserted_split = split_storage.update.mock_calls[0][1][0][0]
assert isinstance(inserted_split, Split)
assert inserted_split.name == 'some_name'
inserted_segment = segment_storage.update.mock_calls[0][1]
assert inserted_segment[0] == 'segmentA'
assert inserted_segment[1] == ['key1', 'key2', 'key3']
assert inserted_segment[2] == []
def test_start_periodic_fetching(self, mocker):
split_task = mocker.Mock(spec=SplitSynchronizationTask)
segment_task = mocker.Mock(spec=SegmentSynchronizationTask)
split_tasks = SplitTasks(split_task, segment_task, mocker.Mock(), mocker.Mock(),
mocker.Mock())
synchronizer = Synchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_fetching()
assert len(split_task.start.mock_calls) == 1
assert len(segment_task.start.mock_calls) == 1
def test_stop_periodic_fetching(self, mocker):
split_task = mocker.Mock(spec=SplitSynchronizationTask)
segment_task = mocker.Mock(spec=SegmentSynchronizationTask)
segment_sync = mocker.Mock(spec=SegmentSynchronizer)
split_synchronizers = SplitSynchronizers(mocker.Mock(), segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
split_tasks = SplitTasks(split_task, segment_task, mocker.Mock(), mocker.Mock(),
mocker.Mock())
synchronizer = Synchronizer(split_synchronizers, split_tasks)
synchronizer.stop_periodic_fetching()
assert len(split_task.stop.mock_calls) == 1
assert len(segment_task.stop.mock_calls) == 1
assert len(segment_sync.shutdown.mock_calls) == 0
def test_start_periodic_data_recording(self, mocker):
impression_task = mocker.Mock(spec=ImpressionsSyncTask)
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
event_task = mocker.Mock(spec=EventsSyncTask)
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
split_tasks = SplitTasks(mocker.Mock(), mocker.Mock(), impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = Synchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_data_recording()
assert len(impression_task.start.mock_calls) == 1
assert len(impression_count_task.start.mock_calls) == 1
assert len(event_task.start.mock_calls) == 1
assert len(unique_keys_task.start.mock_calls) == 1
assert len(clear_filter_task.start.mock_calls) == 1
def test_stop_periodic_data_recording(self, mocker):
def stop_mock(event):
event.set()
return
def stop_mock_2():
return
impression_task = mocker.Mock(spec=ImpressionsSyncTask)
impression_task.stop.side_effect = stop_mock
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
impression_count_task.stop.side_effect = stop_mock
event_task = mocker.Mock(spec=EventsSyncTask)
event_task.stop.side_effect = stop_mock
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
unique_keys_task.stop.side_effect = stop_mock
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
clear_filter_task.stop.side_effect = stop_mock
split_tasks = SplitTasks(mocker.Mock(), mocker.Mock(), impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = Synchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.stop_periodic_data_recording(True)
assert len(impression_task.stop.mock_calls) == 1
assert len(impression_count_task.stop.mock_calls) == 1
assert len(event_task.stop.mock_calls) == 1
assert len(unique_keys_task.stop.mock_calls) == 1
assert len(clear_filter_task.stop.mock_calls) == 1
def test_shutdown(self, mocker):
def stop_mock(event):
event.set()
return
def stop_mock_2():
return
split_task = mocker.Mock(spec=SplitSynchronizationTask)
split_task.stop.side_effect = stop_mock_2
segment_task = mocker.Mock(spec=SegmentSynchronizationTask)
segment_task.stop.side_effect = stop_mock_2
impression_task = mocker.Mock(spec=ImpressionsSyncTask)
impression_task.stop.side_effect = stop_mock
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
impression_count_task.stop.side_effect = stop_mock
event_task = mocker.Mock(spec=EventsSyncTask)
event_task.stop.side_effect = stop_mock
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
unique_keys_task.stop.side_effect = stop_mock
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
clear_filter_task.stop.side_effect = stop_mock
segment_sync = mocker.Mock(spec=SegmentSynchronizer)
split_synchronizers = SplitSynchronizers(mocker.Mock(), segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock(), mocker.Mock())
split_tasks = SplitTasks(split_task, segment_task, impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = Synchronizer(split_synchronizers, split_tasks)
synchronizer.shutdown(True)
assert len(split_task.stop.mock_calls) == 1
assert len(segment_task.stop.mock_calls) == 1
assert len(segment_sync.shutdown.mock_calls) == 1
assert len(impression_task.stop.mock_calls) == 1
assert len(impression_count_task.stop.mock_calls) == 1
assert len(event_task.stop.mock_calls) == 1
assert len(unique_keys_task.stop.mock_calls) == 1
assert len(clear_filter_task.stop.mock_calls) == 1
def test_sync_all_ok(self, mocker):
"""Test that 3 attempts are done before failing."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
def sync_splits(*_):
"""Sync Splits."""
counts['splits'] += 1
return []
def sync_segments(*_):
"""Sync Segments."""
counts['segments'] += 1
return True
split_synchronizers.split_sync.synchronize_splits.side_effect = sync_splits
split_synchronizers.segment_sync.synchronize_segments.side_effect = sync_segments
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = Synchronizer(split_synchronizers, split_tasks)
synchronizer.sync_all()
assert counts['splits'] == 1
assert counts['segments'] == 1
def test_sync_all_split_attempts(self, mocker):
"""Test that 3 attempts are done before failing."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
def sync_splits(*_):
"""Sync Splits."""
counts['splits'] += 1
raise Exception('sarasa')
split_synchronizers.split_sync.synchronize_splits.side_effect = sync_splits
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = Synchronizer(split_synchronizers, split_tasks)
synchronizer.sync_all(2)
assert counts['splits'] == 3
def test_sync_all_segment_attempts(self, mocker):
"""Test that segments don't trigger retries."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
def sync_segments(*_):
"""Sync Splits."""
counts['segments'] += 1
return False
split_synchronizers.segment_sync.synchronize_segments.side_effect = sync_segments
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = Synchronizer(split_synchronizers, split_tasks)
synchronizer._synchronize_segments()
assert counts['segments'] == 1
class SynchronizerAsyncTests(object):
@pytest.mark.asyncio
async def test_sync_all_failed_splits(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
rbs_storage = mocker.Mock()
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
storage.flag_set_filter = flag_set_filter
storage.flag_set_filter.flag_sets = {}
storage.flag_set_filter.sorted_flag_sets = []
async def run(x, y, c):
raise APIException("something broke")
api.fetch_splits = run
async def get_change_number():
return 1234
storage.get_change_number = get_change_number
rbs_storage.get_change_number = get_change_number
split_sync = SplitSynchronizerAsync(api, storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, mocker.Mock(), mocker.Mock(),
mocker.Mock(), mocker.Mock())
sychronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await sychronizer.synchronize_splits(None) # APIExceptions are handled locally and should not be propagated!
# test forcing to have only one retry attempt and then exit
await sychronizer.sync_all(1) # sync_all should not throw!
@pytest.mark.asyncio
async def test_sync_all_failed_splits_with_flagsets(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
rbs_storage = mocker.Mock()
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
storage.flag_set_filter = flag_set_filter
storage.flag_set_filter.flag_sets = {}
storage.flag_set_filter.sorted_flag_sets = []
async def get_change_number():
pass
storage.get_change_number = get_change_number
rbs_storage.get_change_number = get_change_number
async def run(x, y, c):
raise APIException("something broke", 414)
api.fetch_splits = run
split_sync = SplitSynchronizerAsync(api, storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, mocker.Mock(), mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await synchronizer.synchronize_splits(None) # APIExceptions are handled locally and should not be propagated!
# test forcing to have only one retry attempt and then exit
await synchronizer.sync_all(3) # sync_all should not throw!
assert synchronizer._backoff._attempt == 0
@pytest.mark.asyncio
async def test_sync_all_failed_segments(self, mocker):
api = mocker.Mock()
storage = mocker.Mock()
split_storage = mocker.Mock(spec=SplitStorage)
rbs_storage = mocker.Mock(spec=RuleBasedSegmentsStorage)
split_sync = mocker.Mock(spec=SplitSynchronizer)
split_sync.synchronize_splits.return_value = None
async def run(x, y, c):
raise APIException("something broke")
api.fetch_segment = run
async def get_segment_names():
return ['seg']
split_storage.get_segment_names = get_segment_names
async def get_segment_names_rbs():
return []
rbs_storage.get_segment_names = get_segment_names_rbs
segment_sync = SegmentSynchronizerAsync(api, split_storage, storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
sychronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await sychronizer.sync_all(1) # SyncAll should not throw!
assert not await sychronizer._synchronize_segments()
await segment_sync.shutdown()
@pytest.mark.asyncio
async def test_synchronize_splits(self, mocker):
internal_events_queue = asyncio.Queue()
split_storage = InMemorySplitStorageAsync(internal_events_queue)
rbs_storage = InMemoryRuleBasedSegmentStorageAsync(internal_events_queue)
split_api = mocker.Mock()
async def fetch_splits(change, rb, options):
return {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_api.fetch_splits = fetch_splits
split_sync = SplitSynchronizerAsync(split_api, split_storage, rbs_storage)
segment_storage = InMemorySegmentStorageAsync(internal_events_queue)
segment_api = mocker.Mock()
async def get_change_number():
return 123
split_storage.get_change_number = get_change_number
async def fetch_segment(segment_name, change, options):
return {'name': 'segmentA', 'added': ['key1', 'key2',
'key3'], 'removed': [], 'since': 123, 'till': 123}
segment_api.fetch_segment = fetch_segment
segment_sync = SegmentSynchronizerAsync(segment_api, split_storage, segment_storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await synchronizer.synchronize_splits(123)
inserted_split = await split_storage.get('some_name')
assert isinstance(inserted_split, Split)
assert inserted_split.name == 'some_name'
await segment_sync._jobs.await_completion()
inserted_segment = await segment_storage.get('segmentA')
assert inserted_segment.name == 'segmentA'
assert inserted_segment.keys == {'key1', 'key2', 'key3'}
await segment_sync.shutdown()
@pytest.mark.asyncio
async def test_synchronize_splits_calling_segment_sync_once(self, mocker):
internal_events_queue = asyncio.Queue()
split_storage = InMemorySplitStorageAsync(internal_events_queue)
rbs_storage = InMemoryRuleBasedSegmentStorageAsync(internal_events_queue)
async def get_change_number():
return 123
split_storage.get_change_number = get_change_number
split_api = mocker.Mock()
async def fetch_splits(change, rb, options):
return {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_api.fetch_splits = fetch_splits
split_sync = SplitSynchronizerAsync(split_api, split_storage, rbs_storage)
counts = {'segments': 0}
segment_sync = mocker.Mock()
async def sync_segments(*_):
"""Sync Segments."""
counts['segments'] += 1
return True
segment_sync.synchronize_segments = sync_segments
async def segment_exist_in_storage(segment):
return False
segment_sync.segment_exist_in_storage = segment_exist_in_storage
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await synchronizer.synchronize_splits(123, True)
assert counts['segments'] == 1
@pytest.mark.asyncio
async def test_sync_all(self, mocker):
internal_events_queue = asyncio.Queue()
split_storage = InMemorySplitStorageAsync(internal_events_queue)
rbs_storage = InMemoryRuleBasedSegmentStorageAsync(internal_events_queue)
async def get_change_number():
return 123
split_storage.get_change_number = get_change_number
self.added_split = None
async def update(split, deleted, change_number):
if len(split) > 0:
self.added_split = split
split_storage.update = update
async def get_segment_names():
return ['segmentA']
split_storage.get_segment_names = get_segment_names
class flag_set_filter():
def should_filter():
return False
def intersect(sets):
return True
split_storage.flag_set_filter = flag_set_filter
split_storage.flag_set_filter.flag_sets = {}
split_storage.flag_set_filter.sorted_flag_sets = []
split_api = mocker.Mock()
async def fetch_splits(change, rb, options):
return {'ff': {'d': splits, 's': 123,
't': 123}, 'rbs': {'d': [], 's': -1, 't': -1}}
split_api.fetch_splits = fetch_splits
split_sync = SplitSynchronizerAsync(split_api, split_storage, rbs_storage)
segment_storage = InMemorySegmentStorageAsync(internal_events_queue)
async def get_change_number(segment):
return 123
segment_storage.get_change_number = get_change_number
self.inserted_segment = []
async def update(segment, added, removed, till):
self.inserted_segment.append(segment)
self.inserted_segment.append(added)
self.inserted_segment.append(removed)
segment_storage.update = update
segment_api = mocker.Mock()
async def fetch_segment(segment_name, change, options):
return {'name': 'segmentA', 'added': ['key1', 'key2', 'key3'],
'removed': [], 'since': 123, 'till': 123}
segment_api.fetch_segment = fetch_segment
segment_sync = SegmentSynchronizerAsync(segment_api, split_storage, segment_storage, rbs_storage)
split_synchronizers = SplitSynchronizers(split_sync, segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
synchronizer = SynchronizerAsync(split_synchronizers, mocker.Mock(spec=SplitTasks))
await synchronizer.sync_all()
await segment_sync._jobs.await_completion()
assert isinstance(self.added_split[0], Split)
assert self.added_split[0].name == 'some_name'
assert self.inserted_segment[0] == 'segmentA'
assert self.inserted_segment[1] == ['key1', 'key2', 'key3']
assert self.inserted_segment[2] == []
@pytest.mark.asyncio
async def test_start_periodic_fetching(self, mocker):
split_task = mocker.Mock(spec=SplitSynchronizationTask)
segment_task = mocker.Mock(spec=SegmentSynchronizationTask)
split_tasks = SplitTasks(split_task, segment_task, mocker.Mock(), mocker.Mock(),
mocker.Mock())
synchronizer = SynchronizerAsync(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_fetching()
assert len(split_task.start.mock_calls) == 1
assert len(segment_task.start.mock_calls) == 1
@pytest.mark.asyncio
async def test_stop_periodic_fetching(self, mocker):
split_task = mocker.Mock(spec=SplitSynchronizationTaskAsync)
segment_task = mocker.Mock(spec=SegmentSynchronizationTaskAsync)
segment_sync = mocker.Mock(spec=SegmentSynchronizerAsync)
split_synchronizers = SplitSynchronizers(mocker.Mock(), segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock())
split_tasks = SplitTasks(split_task, segment_task, mocker.Mock(), mocker.Mock(),
mocker.Mock())
synchronizer = SynchronizerAsync(split_synchronizers, split_tasks)
self.split_task_stopped = 0
async def stop_split():
self.split_task_stopped += 1
split_task.stop = stop_split
self.segment_task_stopped = 0
async def stop_segment():
self.segment_task_stopped += 1
segment_task.stop = stop_segment
self.segment_sync_stopped = 0
async def shutdown():
self.segment_sync_stopped += 1
segment_sync.shutdown = shutdown
await synchronizer.stop_periodic_fetching()
assert self.split_task_stopped == 1
assert self.segment_task_stopped == 1
assert self.segment_sync_stopped == 0
def test_start_periodic_data_recording(self, mocker):
impression_task = mocker.Mock(spec=ImpressionsSyncTaskAsync)
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTaskAsync)
event_task = mocker.Mock(spec=EventsSyncTaskAsync)
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTaskAsync)
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTaskAsync)
split_tasks = SplitTasks(None, None, impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = SynchronizerAsync(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_data_recording()
assert len(impression_task.start.mock_calls) == 1
assert len(impression_count_task.start.mock_calls) == 1
assert len(event_task.start.mock_calls) == 1
class RedisSynchronizerTests(object):
def test_start_periodic_data_recording(self, mocker):
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
split_tasks = SplitTasks(None, None, None, None,
impression_count_task,
None,
unique_keys_task,
clear_filter_task
)
synchronizer = RedisSynchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_data_recording()
assert len(impression_count_task.start.mock_calls) == 1
assert len(unique_keys_task.start.mock_calls) == 1
assert len(clear_filter_task.start.mock_calls) == 1
def test_stop_periodic_data_recording(self, mocker):
def stop_mock(event):
event.set()
return
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
impression_count_task.stop.side_effect = stop_mock
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
unique_keys_task.stop.side_effect = stop_mock
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
clear_filter_task.stop.side_effect = stop_mock
split_tasks = SplitTasks(None, None, None, None,
impression_count_task,
None,
unique_keys_task,
clear_filter_task
)
synchronizer = RedisSynchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.stop_periodic_data_recording(True)
assert len(impression_count_task.stop.mock_calls) == 1
assert len(unique_keys_task.stop.mock_calls) == 1
assert len(clear_filter_task.stop.mock_calls) == 1
def test_shutdown(self, mocker):
def stop_mock(event):
event.set()
return
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTask)
impression_count_task.stop.side_effect = stop_mock
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTask)
unique_keys_task.stop.side_effect = stop_mock
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTask)
clear_filter_task.stop.side_effect = stop_mock
segment_sync = mocker.Mock(spec=SegmentSynchronizer)
split_tasks = SplitTasks(None, None, None, None,
impression_count_task,
None,
unique_keys_task,
clear_filter_task
)
synchronizer = RedisSynchronizer(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.shutdown(True)
assert len(impression_count_task.stop.mock_calls) == 1
assert len(unique_keys_task.stop.mock_calls) == 1
assert len(clear_filter_task.stop.mock_calls) == 1
class RedisSynchronizerAsyncTests(object):
@pytest.mark.asyncio
async def test_start_periodic_data_recording(self, mocker):
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTaskAsync)
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTaskAsync)
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTaskAsync)
split_tasks = SplitTasks(None, None, None, None,
impression_count_task,
None,
unique_keys_task,
clear_filter_task
)
synchronizer = RedisSynchronizerAsync(mocker.Mock(spec=SplitSynchronizers), split_tasks)
synchronizer.start_periodic_data_recording()
assert len(impression_count_task.start.mock_calls) == 1
assert len(unique_keys_task.start.mock_calls) == 1
assert len(clear_filter_task.start.mock_calls) == 1
@pytest.mark.asyncio
async def test_stop_periodic_data_recording(self, mocker):
impression_task = mocker.Mock(spec=ImpressionsSyncTaskAsync)
self.stop_imp_calls = 0
async def stop_imp(arg=None):
self.stop_imp_calls += 1
return
impression_task.stop = stop_imp
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTaskAsync)
self.stop_imp_count_calls = 0
async def stop_imp_count(arg=None):
self.stop_imp_count_calls += 1
return
impression_count_task.stop = stop_imp_count
event_task = mocker.Mock(spec=EventsSyncTaskAsync)
self.stop_event_calls = 0
async def stop_event(arg=None):
self.stop_event_calls += 1
return
event_task.stop = stop_event
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTaskAsync)
self.stop_unique_keys_calls = 0
async def stop_unique_keys(arg=None):
self.stop_unique_keys_calls += 1
return
unique_keys_task.stop = stop_unique_keys
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTaskAsync)
self.stop_clear_filter_calls = 0
async def stop_clear_filter(arg=None):
self.stop_clear_filter_calls += 1
return
clear_filter_task.stop = stop_clear_filter
split_tasks = SplitTasks(mocker.Mock(), mocker.Mock(), impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = SynchronizerAsync(mocker.Mock(spec=SplitSynchronizers), split_tasks)
await synchronizer.stop_periodic_data_recording(True)
assert self.stop_imp_count_calls == 1
assert self.stop_imp_calls == 1
assert self.stop_event_calls == 1
assert self.stop_unique_keys_calls == 1
assert self.stop_clear_filter_calls == 1
@pytest.mark.asyncio
async def test_shutdown(self, mocker):
split_task = mocker.Mock(spec=SplitSynchronizationTask)
self.split_task_stopped = 0
async def stop_split():
self.split_task_stopped += 1
split_task.stop = stop_split
segment_task = mocker.Mock(spec=SegmentSynchronizationTask)
self.segment_task_stopped = 0
async def stop_segment():
self.segment_task_stopped += 1
segment_task.stop = stop_segment
impression_task = mocker.Mock(spec=ImpressionsSyncTaskAsync)
self.stop_imp_calls = 0
async def stop_imp(arg=None):
self.stop_imp_calls += 1
return
impression_task.stop = stop_imp
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTaskAsync)
self.stop_imp_count_calls = 0
async def stop_imp_count(arg=None):
self.stop_imp_count_calls += 1
return
impression_count_task.stop = stop_imp_count
event_task = mocker.Mock(spec=EventsSyncTaskAsync)
self.stop_event_calls = 0
async def stop_event(arg=None):
self.stop_event_calls += 1
return
event_task.stop = stop_event
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTaskAsync)
self.stop_unique_keys_calls = 0
async def stop_unique_keys(arg=None):
self.stop_unique_keys_calls += 1
return
unique_keys_task.stop = stop_unique_keys
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTaskAsync)
self.stop_clear_filter_calls = 0
async def stop_clear_filter(arg=None):
self.stop_clear_filter_calls += 1
return
clear_filter_task.stop = stop_clear_filter
segment_sync = mocker.Mock(spec=SegmentSynchronizerAsync)
self.segment_sync_stopped = 0
async def shutdown():
self.segment_sync_stopped += 1
segment_sync.shutdown = shutdown
split_synchronizers = SplitSynchronizers(mocker.Mock(), segment_sync, mocker.Mock(),
mocker.Mock(), mocker.Mock(), mocker.Mock())
split_tasks = SplitTasks(split_task, segment_task, impression_task, event_task,
impression_count_task, unique_keys_task, clear_filter_task)
synchronizer = SynchronizerAsync(split_synchronizers, split_tasks)
await synchronizer.shutdown(True)
assert self.split_task_stopped == 1
assert self.segment_task_stopped == 1
assert self.segment_sync_stopped == 1
assert self.stop_imp_count_calls == 1
assert self.stop_imp_calls == 1
assert self.stop_event_calls == 1
assert self.stop_unique_keys_calls == 1
assert self.stop_clear_filter_calls == 1
@pytest.mark.asyncio
async def test_sync_all_ok(self, mocker):
"""Test that 3 attempts are done before failing."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
async def sync_splits(*_):
"""Sync Splits."""
counts['splits'] += 1
return []
async def sync_segments(*_):
"""Sync Segments."""
counts['segments'] += 1
return True
split_synchronizers.split_sync.synchronize_splits = sync_splits
split_synchronizers.segment_sync.synchronize_segments = sync_segments
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = SynchronizerAsync(split_synchronizers, split_tasks)
await synchronizer.sync_all()
assert counts['splits'] == 1
assert counts['segments'] == 1
@pytest.mark.asyncio
async def test_sync_all_split_attempts(self, mocker):
"""Test that 3 attempts are done before failing."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
async def sync_splits(*_):
"""Sync Splits."""
counts['splits'] += 1
raise Exception('sarasa')
split_synchronizers.split_sync.synchronize_splits = sync_splits
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = SynchronizerAsync(split_synchronizers, split_tasks)
await synchronizer.sync_all(2)
assert counts['splits'] == 3
@pytest.mark.asyncio
async def test_sync_all_segment_attempts(self, mocker):
"""Test that segments don't trigger retries."""
split_synchronizers = mocker.Mock(spec=SplitSynchronizers)
counts = {'splits': 0, 'segments': 0}
async def sync_segments(*_):
"""Sync Segments."""
counts['segments'] += 1
return False
split_synchronizers.segment_sync.synchronize_segments = sync_segments
split_tasks = mocker.Mock(spec=SplitTasks)
synchronizer = SynchronizerAsync(split_synchronizers, split_tasks)
await synchronizer._synchronize_segments()
assert counts['segments'] == 1
impression_count_task = mocker.Mock(spec=ImpressionsCountSyncTaskAsync)
self.imp_count_calls = 0
async def imp_count_stop_mock():
self.imp_count_calls += 1
impression_count_task.stop = imp_count_stop_mock
unique_keys_task = mocker.Mock(spec=UniqueKeysSyncTaskAsync)
self.unique_keys_calls = 0
async def unique_keys_stop_mock():
self.unique_keys_calls += 1
unique_keys_task.stop = unique_keys_stop_mock
clear_filter_task = mocker.Mock(spec=ClearFilterSyncTaskAsync)
self.clear_filter_calls = 0
async def clear_filter_stop_mock():
self.clear_filter_calls += 1
clear_filter_task.stop = clear_filter_stop_mock
split_tasks = SplitTasks(None, None, None, None,
impression_count_task,
None,
unique_keys_task,
clear_filter_task