-
Notifications
You must be signed in to change notification settings - Fork 7
/
tests.py
1085 lines (756 loc) · 32.6 KB
/
tests.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
import os
import uuid
import asyncio
import logging, coloredlogs
from aiobotocore import AioSession
from dotenv import load_dotenv
from asynctest import TestCase as AsynTestCase, fail_on
from unittest import skipUnless, TestCase
from kinesis import Consumer, Producer, MemoryCheckPointer, RedisCheckPointer
from kinesis.processors import (
StringProcessor,
JsonProcessor,
JsonLineProcessor,
JsonListProcessor,
MsgpackProcessor,
Processor,
)
from kinesis.aggregators import (
Aggregator,
KPLAggregator,
SimpleAggregator,
NewlineAggregator,
ListAggregator,
NetstringAggregator,
OutputItem,
)
from kinesis.serializers import StringSerializer, JsonSerializer, Serializer
from kinesis import exceptions
coloredlogs.install(level="DEBUG", fmt="%(name)s %(levelname)s %(message)s")
logging.getLogger("botocore").setLevel(logging.WARNING)
logging.getLogger("aiobotocore").setLevel(logging.INFO)
log = logging.getLogger(__name__)
load_dotenv()
# https://github.com/mhart/kinesalite
# ./node_modules/.bin/kinesalite --shardLimit 1000
# see also docker-compose.yaml
ENDPOINT_URL = os.environ.get("ENDPOINT_URL", "http://localhost:4567")
TESTING_USE_AWS_KINESIS = os.environ.get("TESTING_USE_AWS_KINESIS", "0") == "1"
# Use docker-compose one
if "REDIS_PORT" not in os.environ:
os.environ["REDIS_PORT"] = "16379"
class BaseTests:
def random_string(self, length):
from random import choice
from string import ascii_uppercase
return "".join(choice(ascii_uppercase) for i in range(length))
class BaseKinesisTests(AsynTestCase, BaseTests):
async def setUp(self):
self.stream_name = "test_{}".format(str(uuid.uuid4())[0:8])
producer = await Producer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
create_stream=self.stream_name,
create_stream_shards=1,
).__aenter__()
await producer.__aexit__(None, None, None)
async def add_record_delayed(self, msg, producer, delay):
log.debug("Adding record. delay={}".format(delay))
await asyncio.sleep(delay)
await producer.put(msg)
class ProcessorAndAggregatorTests(TestCase, BaseTests):
"""
Processor and Aggregator Tests
"""
def test_aggregator_min_size(self):
with self.assertRaises(exceptions.ValidationError):
Aggregator(max_size=20)
def test_aggregator_max_size(self):
with self.assertRaises(exceptions.ValidationError):
Aggregator(max_size=2000)
def test_processor_exceed_put_limit(self):
processor = StringProcessor()
with self.assertRaises(exceptions.ExceededPutLimit):
list(processor.add_item(self.random_string(1024 * 1024 + 1)))
def test_newline_aggregator(self):
# in reality does not make sense as strings can contain new lines
# so is not a suitable combination to use
class NewlineTestProcessor(NewlineAggregator, StringSerializer):
pass
processor = NewlineTestProcessor()
# Expect nothing as batching
self.assertEqual([], list(processor.add_item(123)))
self.assertEqual([], list(processor.add_item("test")))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 9)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b"123\ntest\n")
self.assertListEqual(list(processor.parse(output[0].data)), ["123", "test"])
def test_list_aggregator(self):
class JsonListTestProcessor(ListAggregator, JsonSerializer):
pass
processor = JsonListTestProcessor()
# Expect nothing as batching
self.assertEqual([], list(processor.add_item(123)))
self.assertEqual([], list(processor.add_item("test")))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 11)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b'[123, "test"]')
self.assertListEqual(next(processor.parse(output[0].data)), [123, "test"])
def test_netstring_aggregator(self):
class NetstringTestProcessor(NetstringAggregator, StringSerializer):
pass
processor = NetstringTestProcessor()
# Expect nothing as batching
self.assertEqual([], list(processor.add_item(123)))
self.assertEqual([], list(processor.add_item("test")))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 13)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b"3:123,4:test,")
self.assertListEqual(list(processor.parse(output[0].data)), ["123", "test"])
def test_kpl_aggregator(self):
class KPLTestProcessor(KPLAggregator, StringSerializer):
pass
processor = KPLTestProcessor()
# Expect nothing as batching
self.assertEqual([], list(processor.add_item(123)))
self.assertEqual([], list(processor.add_item("test")))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].n, 2)
self.assertListEqual(list(processor.parse(output[0].data)), ["123", "test"])
def test_kpl_aggregator_max_size(self):
class BytesSerializer:
def serialize(self, item):
return item
def deserialize(self, data):
return data
class KPLTestProcessor(KPLAggregator, BytesSerializer):
pass
# 100 K max_size
processor = KPLTestProcessor(max_size=1024 * 100)
# Expect nothing as batching first two 40K records
self.assertEqual([], list(processor.add_item(bytes(40 * 1024))))
self.assertEqual([], list(processor.add_item(bytes(40 * 1024))))
# output as we exceed
output = list(processor.add_item(bytes(40 * 1024)))
self.assertEqual(len(output), 1)
self.assertEqual(output[0].n, 2)
def test_string_processor(self):
processor = StringProcessor()
self.assertEquals(processor.max_bytes, 1024 * 25 * 40)
output = list(processor.add_item("test"))
self.assertEqual(len(output), 1)
self.assertIsInstance(output[0], OutputItem)
self.assertEqual(output[0].size, len("test"))
self.assertEqual(output[0].n, 1)
self.assertEqual(output[0].data, b"test")
self.assertFalse(processor.has_items())
def test_json_processor(self):
processor = JsonProcessor()
output = list(processor.add_item({"test": 123}))
self.assertEqual(len(output), 1)
self.assertIsInstance(output[0], OutputItem)
self.assertEqual(output[0].size, 13)
self.assertEqual(output[0].n, 1)
self.assertEqual(output[0].data, b'{"test": 123}')
self.assertFalse(processor.has_items())
self.assertListEqual(list(processor.parse(output[0].data)), [{"test": 123}])
def test_json_line_processor(self):
processor = JsonLineProcessor(max_size=25)
# Expect nothing as batching
self.assertEqual([], list(processor.add_item({"test": 123})))
self.assertEqual([], list(processor.add_item({"test": 456})))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 28)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b'{"test": 123}\n{"test": 456}\n')
self.assertListEqual(
list(processor.parse(output[0].data)),
[{"test": 123}, {"test": 456}],
)
# Expect empty now
self.assertFalse(processor.has_items())
result = []
for x in range(1000):
output = list(processor.add_item({"test": "test with some more data"}))
if output:
self.assertEqual(len(output), 1)
result.append(output[0])
# Expected at least one record to be output
self.assertEqual(len(result), 1)
self.assertEqual(result[0].size, 25567) # expect below 25*1024=25600
self.assertEqual(result[0].n, 691)
# Expect some left
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 11432)
self.assertEqual(output[0].n, 309)
self.assertFalse(processor.has_items())
def test_json_list_processor(self):
processor = JsonListProcessor(max_size=25)
# Expect nothing as batching
self.assertEqual([], list(processor.add_item({"test": 123})))
self.assertEqual([], list(processor.add_item({"test": 456})))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 28)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b'[{"test": 123}, {"test": 456}]')
# Need to use next() otherwise list() creates double nested list
self.assertListEqual(
next(processor.parse(output[0].data)), [{"test": 123}, {"test": 456}]
)
# Expect empty now
self.assertFalse(processor.has_items())
result = []
for x in range(1000):
output = list(processor.add_item({"test": "test with some more data"}))
if output:
self.assertEqual(len(output), 1)
result.append(output[0])
# Expected at least one record to be output
self.assertEqual(len(result), 1)
self.assertEqual(result[0].size, 25567) # expect below 25*1024=25600
self.assertEqual(result[0].n, 691)
# Expect some left
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 11432)
self.assertEqual(output[0].n, 309)
self.assertFalse(processor.has_items())
def test_msgpack_processor(self):
processor = MsgpackProcessor(max_size=25)
# Expect nothing as batching
self.assertEqual([], list(processor.add_item({"test": 123})))
self.assertEqual([], list(processor.add_item({"test": 456})))
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 22)
self.assertEqual(output[0].n, 2)
self.assertEqual(output[0].data, b"7:\x81\xa4test{,9:\x81\xa4test\xcd\x01\xc8,")
self.assertListEqual(
list(processor.parse(output[0].data)), [{"test": 123}, {"test": 456}]
)
# Expect empty now
self.assertFalse(processor.has_items())
result = []
for x in range(1000):
output = list(processor.add_item({"test": "test with some more data"}))
if output:
self.assertEqual(len(output), 1)
result.append(output[0])
# Expected at least one record to be output
self.assertEqual(len(result), 1)
self.assertEqual(result[0].size, 25585) # expect below 25*1024=25600
self.assertEqual(result[0].n, 731)
# Expect some left
self.assertTrue(processor.has_items())
output = list(processor.get_items())
self.assertEqual(len(output), 1)
self.assertEqual(output[0].size, 9411)
self.assertEqual(output[0].n, 269)
self.assertFalse(processor.has_items())
class CheckpointTests(BaseKinesisTests):
"""
Checkpoint Tests
"""
@classmethod
def patch_consumer_fetch(cls, consumer):
async def get_shard_iterator(shard_id, last_sequence_number=None):
log.info(
"getting shard iterator for {} @ {}".format(
shard_id, last_sequence_number
)
)
return True
consumer.get_shard_iterator = get_shard_iterator
async def get_records(shard):
log.info("get records shard={}".format(shard["ShardId"]))
return {}
consumer.get_records = get_records
consumer.is_fetching = True
async def test_memory_checkpoint(self):
# first consumer
checkpointer = MemoryCheckPointer(name="test")
consumer_a = Consumer(
stream_name=None,
checkpointer=checkpointer,
max_shard_consumers=1,
endpoint_url=ENDPOINT_URL,
)
self.patch_consumer_fetch(consumer_a)
consumer_a.shards = [{"ShardId": "test-1"}, {"ShardId": "test-2"}]
await consumer_a.fetch()
shards = [s["ShardId"] for s in consumer_a.shards if s.get("stats")]
# Expect only one shard assigned as max = 1
self.assertEqual(["test-1"], shards)
# second consumer (note: max_shard_consumers needs to be 2 as uses checkpointer to get allocated shards)
consumer_b = Consumer(
stream_name=None,
checkpointer=checkpointer,
max_shard_consumers=2,
endpoint_url=ENDPOINT_URL,
)
self.patch_consumer_fetch(consumer_b)
consumer_b.shards = [{"ShardId": "test-1"}, {"ShardId": "test-2"}]
await consumer_b.fetch()
shards = [s["ShardId"] for s in consumer_b.shards if s.get("stats")]
# Expect only one shard assigned as max = 1
self.assertEqual(["test-2"], shards)
async def test_redis_checkpoint_locking(self):
name = "test-{}".format(str(uuid.uuid4())[0:8])
# first consumer
checkpointer_a = RedisCheckPointer(name=name, id="proc-1")
# second consumer
checkpointer_b = RedisCheckPointer(name=name, id="proc-2")
# try to allocate the same shard
result = await asyncio.gather(
*[checkpointer_a.allocate("test"), checkpointer_b.allocate("test")]
)
result = list(sorted([x[0] for x in result]))
# Expect only one to have succeeded
self.assertEquals([False, True], result)
await checkpointer_a.close()
await checkpointer_b.close()
async def test_redis_checkpoint_reallocate(self):
name = "test-{}".format(str(uuid.uuid4())[0:8])
# first consumer
checkpointer_a = RedisCheckPointer(name=name, id="proc-1")
await checkpointer_a.allocate("test")
# checkpoint
await checkpointer_a.checkpoint("test", "123")
# stop on this shard
await checkpointer_a.deallocate("test")
# second consumer
checkpointer_b = RedisCheckPointer(name=name, id="proc-2")
success, sequence = await checkpointer_b.allocate("test")
self.assertTrue(success)
self.assertEquals("123", sequence)
await checkpointer_b.close()
self.assertEquals(checkpointer_b.get_all_checkpoints(), {})
await checkpointer_a.close()
async def test_redis_checkpoint_hearbeat(self):
name = "test-{}".format(str(uuid.uuid4())[0:8])
checkpointer = RedisCheckPointer(name=name, heartbeat_frequency=0.5)
await checkpointer.allocate("test")
await checkpointer.checkpoint("test", "123")
await asyncio.sleep(1)
await checkpointer.close()
# nothing to assert
self.assertTrue(True)
class KinesisTests(BaseKinesisTests):
"""
Kinesalite Tests
"""
async def test_stream_does_not_exist(self):
await asyncio.sleep(2)
# Producer
with self.assertRaises(exceptions.StreamDoesNotExist):
async with Producer(
session=AioSession(),
stream_name="test_stream_does_not_exist", endpoint_url=ENDPOINT_URL
) as producer:
await producer.put("test")
# Consumer
with self.assertRaises(exceptions.StreamDoesNotExist):
async with Consumer(
stream_name="test_stream_does_not_exist", endpoint_url=ENDPOINT_URL
):
pass
@fail_on(unused_loop=True, active_handles=True)
async def test_producer_put(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
await producer.put("test")
async def test_producer_put_below_limit(self):
async with Producer(
stream_name=self.stream_name,
processor=StringProcessor(),
endpoint_url=ENDPOINT_URL,
) as producer:
# The maximum size of the data payload of a record before base64-encoding is up to 1 MiB.
# Limit is set in aggregators.BaseAggregator (few bytes short of 1MiB)
await producer.put(self.random_string(40 * 25 * 1024))
async def test_producer_put_exceed_batch_size(self):
# Expect to complete by lowering batch size until successful (500 is max)
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL, batch_size=600
) as producer:
for x in range(1000):
await producer.put("test")
async def test_producer_and_consumer(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
pass
async with Consumer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
):
pass
async def test_producer_and_consumer_consume_from_start_flush(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
await producer.put({"test": 123})
await producer.flush()
results = []
async with Consumer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as consumer:
async for item in consumer:
results.append(item)
# Expect to have consumed from start as default iterator_type=TRIM_HORIZON
self.assertEquals([{"test": 123}], results)
async def test_producer_and_consumer_consume_from_start_after(self):
# Don't flush, close producer immediately to test all data is written to stream on exit.
async with Producer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
processor=StringProcessor(),
) as producer:
# Put enough data to ensure it will require more than one put
# ie test overflow behaviour
for _ in range(15):
await producer.put(self.random_string(100 * 1024))
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
processor=StringProcessor(),
) as consumer:
async for item in consumer:
results.append(item)
# Expect to have consumed from start as default iterator_type=TRIM_HORIZON
self.assertEquals(len(results), 15)
async def test_producer_and_consumer_consume_with_json_line_aggregator(self):
processor = JsonLineProcessor()
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL, processor=processor
) as producer:
for x in range(0, 10):
await producer.put({"test": x})
await producer.flush()
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
processor=processor,
) as consumer:
async for item in consumer:
results.append(item)
# Expect to have consumed from start as default iterator_type=TRIM_HORIZON
self.assertEqual(len(results), 10)
self.assertEquals(results[0], {"test": 0})
self.assertEquals(results[-1], {"test": 9})
async def test_producer_and_consumer_consume_with_msgpack_aggregator(self):
processor = MsgpackProcessor()
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL, processor=processor
) as producer:
for x in range(0, 10):
await producer.put({"test": x})
await producer.flush()
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
processor=processor,
) as consumer:
async for item in consumer:
results.append(item)
# Expect to have consumed from start as default iterator_type=TRIM_HORIZON
self.assertEqual(len(results), 10)
self.assertEquals(results[0], {"test": 0})
self.assertEquals(results[-1], {"test": 9})
async def test_producer_and_consumer_consume_with_bytes(self):
class ByteSerializer(Serializer):
def serialize(self, msg):
result = str.encode(msg)
return result
def deserialize(self, data):
return data
class ByteProcessor(Processor, NetstringAggregator, ByteSerializer):
pass
processor = ByteProcessor()
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL, processor=processor
) as producer:
for x in range(0, 2):
await producer.put(f"{x}")
await producer.flush()
results = []
checkpointer = MemoryCheckPointer(name="test")
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
processor=processor,
checkpointer=checkpointer,
) as consumer:
async for item in consumer:
results.append(item)
await checkpointer.checkpoint(
shard_id=consumer.shards[0]["ShardId"], sequence="seq"
)
async for item in consumer:
results.append(item)
self.assertEquals(len(results), 2)
await checkpointer.close()
self.assertEquals(len(checkpointer.get_all_checkpoints()), 1)
async def test_producer_and_consumer_consume_queue_full(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
for i in range(0, 100):
await producer.put("test")
await producer.flush()
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
max_queue_size=20,
) as consumer:
async for item in consumer:
results.append(item)
# Expect 20 only as queue is full and we don't wait on queue
self.assertEqual(20, len(results))
async def test_producer_and_consumer_consume_throttle(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
for i in range(0, 100):
await producer.put("test")
await producer.flush()
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
record_limit=10,
# 2 per second
shard_fetch_rate=2,
) as consumer:
from datetime import datetime
dt = datetime.now()
while (datetime.now() - dt).total_seconds() < 3.05:
async for item in consumer:
results.append(item)
# Expect 2*3*10 = 60 ie at most 6 iterations of 10 records
self.assertGreaterEqual(len(results), 50)
self.assertLessEqual(len(results), 70)
async def test_producer_and_consumer_consume_with_checkpointer_and_latest(self):
async with Producer(
stream_name=self.stream_name, endpoint_url=ENDPOINT_URL
) as producer:
await producer.put("test.A")
results = []
checkpointer = MemoryCheckPointer(name="test")
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
checkpointer=checkpointer,
iterator_type="LATEST",
) as consumer:
async for item in consumer:
results.append(item)
# Expect none as LATEST
self.assertEquals([], results)
checkpoints = checkpointer.get_all_checkpoints()
# Expect 1 as only 1 shard
self.assertEquals(1, len(checkpoints))
# none as no records yet (using LATEST)
self.assertIsNone(checkpoints[list(checkpoints.keys())[0]]["sequence"])
results = []
log.info("checkpointer checkpoints: {}".format(checkpoints))
log.info("Starting consumer again..")
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
checkpointer=checkpointer,
iterator_type="LATEST",
sleep_time_no_records=0.5,
) as consumer:
# Manually start
await consumer.start_consumer()
await producer.put("test.B")
await producer.flush()
log.info("waiting..")
await asyncio.sleep(1)
log.info("about to consume..")
async for item in consumer:
results.append(item)
self.assertEquals(["test.B"], results)
checkpoints = checkpointer.get_all_checkpoints()
log.info("checkpointer checkpoints: {}".format(checkpoints))
# expect not None as has processed records
self.assertIsNotNone(checkpoints[list(checkpoints.keys())[0]]["sequence"])
# now add some records
for i in range(0, 10):
await producer.put("test.{}".format(i))
await producer.flush()
await asyncio.sleep(1)
results = []
async with Consumer(
stream_name=self.stream_name,
endpoint_url=ENDPOINT_URL,
checkpointer=checkpointer,
iterator_type="LATEST",
sleep_time_no_records=0.5,
) as consumer:
async for item in consumer:
results.append(item)
# Expect results as checkpointer resumed from prior sequence
self.assertEquals(10, len(results))
async def test_producer_and_consumer_consume_multiple_shards_with_redis_checkpointer(
self,
):
stream_name = "test_{}".format(str(uuid.uuid4())[0:8])
async with Producer(
stream_name=stream_name,
endpoint_url=ENDPOINT_URL,
create_stream=stream_name,
create_stream_shards=2,
) as producer:
for i in range(0, 100):
await producer.put("test.{}".format(i))
await producer.flush()
results = []
checkpointer = RedisCheckPointer(
name="test-{}".format(str(uuid.uuid4())[0:8]), heartbeat_frequency=3
)
async with Consumer(
stream_name=stream_name,
endpoint_url=ENDPOINT_URL,
checkpointer=checkpointer,
record_limit=10,
) as consumer:
# consumer will stop if no msgs
for i in range(0, 6):
async for item in consumer:
results.append(item)
await asyncio.sleep(0.5)
self.assertEquals(100, len(results))
checkpoints = checkpointer.get_all_checkpoints()
self.assertEquals(2, len(checkpoints))
# Expect both shards to have been used/set
for item in checkpoints.values():
self.assertIsNotNone(item)
class AWSKinesisTests(BaseKinesisTests):
"""
AWS Kinesis Tests
"""
STREAM_NAME_SINGLE_SHARD = "pykinesis-test-single-shard"
STREAM_NAME_MULTI_SHARD = "pykinesis-test-multi-shard"
forbid_get_event_loop = True
@classmethod
def setUpClass(cls):
if not TESTING_USE_AWS_KINESIS:
return
log.info(
"Creating (or ignoring if exists) *Actual* Kinesis stream: {}".format(
cls.STREAM_NAME_SINGLE_SHARD
)
)
async def create(stream_name, shards):
async with Producer(stream_name=stream_name, create_stream=True, create_stream_shards=shards) as producer:
await producer.start()
asyncio.run(create(stream_name=cls.STREAM_NAME_SINGLE_SHARD, shards=1))
@classmethod
def tearDownClass(cls):
if not TESTING_USE_AWS_KINESIS:
return
log.warning(
"Don't forget to delete your $$ streams: {} and {}".format(
cls.STREAM_NAME_SINGLE_SHARD, cls.STREAM_NAME_MULTI_SHARD
)
)
@skipUnless(
TESTING_USE_AWS_KINESIS, "Requires TESTING_USE_AWS_KINESIS flag to be set"
)
async def test_consumer_checkpoint(self):
checkpointer = MemoryCheckPointer(name="test")
results = []
async with Producer(
stream_name=self.STREAM_NAME_SINGLE_SHARD,
processor=StringProcessor(),
) as producer:
async with Consumer(
stream_name=self.STREAM_NAME_SINGLE_SHARD,