-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathtest_module.py
1210 lines (986 loc) · 42.7 KB
/
test_module.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 pytest
from ddbcache.cache_client import CacheClient
import boto3
from redis import Redis
import time
from decimal import Decimal
from boto3.dynamodb.types import Binary
from boto3.dynamodb.conditions import Attr, Key
from collections import Counter
REGION = "us-west-2"
REDIS_HOST = "localhost"
# Testing will construct a variety of DynamoDB tables with a variety of schemas
# in the given region.
# Each run uses a different namespace to simulate starting with an empty cache.
@pytest.fixture(scope='module')
def random_namespace():
# Time in milliseconds as a string
yield str(int(round(time.time() * 1000)))
@pytest.fixture(scope='module')
def clients(random_namespace):
redis_client = Redis(host=REDIS_HOST, port=6379, decode_responses=True, ssl=True)
real_client = boto3.client("dynamodb", region_name=REGION)
cache_client = CacheClient(real_client, redis_client, ttl=60, namespace=random_namespace)
real_resource = boto3.resource('dynamodb', region_name=REGION)
cache_resource = boto3.resource('dynamodb', region_name=REGION)
cache_resource.meta.client = CacheClient(cache_resource.meta.client, redis_client, ttl=60, namespace=random_namespace)
yield (real_client, cache_client, real_resource, cache_resource)
def table(pktype, sktype):
dynamodb = boto3.resource('dynamodb', region_name=REGION)
table_name = "CacheTest" + pktype + (sktype if sktype else "")
table_list = [table.name for table in dynamodb.tables.all()]
if table_name in table_list:
print(f"Table {table_name} already exists. Skipping creation.")
else:
key_schema = [{'AttributeName': 'pk', 'KeyType': 'HASH'}]
attribute_definitions = [{'AttributeName': 'pk', 'AttributeType': pktype}]
if sktype:
key_schema.append({'AttributeName': 'sk', 'KeyType': 'RANGE'})
attribute_definitions.append({'AttributeName': 'sk', 'AttributeType': sktype})
# Make a GSI with the same schema as the base table for use with query and scan calls
global_secondary_indexes = [
{
'IndexName': 'GSI1',
'KeySchema': key_schema,
'Projection': {
'ProjectionType': 'ALL'
}
}
]
try:
table = dynamodb.create_table(
TableName=table_name,
KeySchema=key_schema,
AttributeDefinitions=attribute_definitions,
GlobalSecondaryIndexes=global_secondary_indexes,
BillingMode='PAY_PER_REQUEST'
)
# Wait for the table to be created
print(f"Creating table {table_name} in on-demand mode. Please wait...")
table.meta.client.get_waiter('table_exists').wait(TableName=table_name)
print(f"Table {table_name} is now active and ready for use.")
except Exception as e:
print(f"Error creating table: {e}")
return table_name
#dynamodb_client.delete_table(TableName=table_name)
@pytest.fixture(scope='module')
def table_ss():
yield table("S", "S")
@pytest.fixture(scope='module')
def table_bn():
yield table("B", "N")
@pytest.fixture(scope='module')
def table_nb():
yield table("N", "B")
@pytest.fixture(scope='module')
def table_s():
yield table("S", None)
@pytest.fixture(scope='module')
def table_ss_loaded(table_ss):
dynamodb = boto3.resource('dynamodb', region_name=REGION)
table = dynamodb.Table(table_ss)
table.put_item(Item={
"pk": "queryme",
"sk": "x",
"Attribute1": "Hello",
"Attribute2": "World"
})
table.put_item(Item={
"pk": "queryme",
"sk": "y",
"Attribute1": "Hello",
"Attribute2": "Amazon"
})
table.put_item(Item={
"pk": "queryme2",
"sk": "x",
"Attribute1": "Hello",
"Attribute2": "World"
})
table.put_item(Item={
"pk": "queryme2",
"sk": "y",
"Attribute1": "Hello",
"Attribute2": "Amazon"
})
yield table_ss
@pytest.fixture(scope='module')
def table_s_loaded(table_s):
dynamodb = boto3.resource('dynamodb', region_name=REGION)
table = dynamodb.Table(table_s)
table.put_item(Item={
"pk": "cat",
"Attribute1": "Hello",
"Attribute2": "World"
})
table.put_item(Item={
"pk": "dog",
"Attribute1": "Hello",
"Attribute2": "Amazon"
})
table.put_item(Item={
"pk": "cat2",
"Attribute1": "Hello",
"Attribute2": "World"
})
table.put_item(Item={
"pk": "dog2",
"Attribute1": "Hello",
"Attribute2": "Amazon"
})
'''
haveWeAlreadyDoneTheBigLoad = table.get_item(
Key={ "pk": "1" },
ProjectionExpression="pk"
)
if 'Item' not in haveWeAlreadyDoneTheBigLoad:
# Save some huge items
payload = "x" * 398000
with table.batch_writer() as batch:
for i in range(0, 100):
batch.put_item(Item={
"pk": str(i),
"Payload": payload
})
'''
yield table_s
def test_my_function():
assert "Expected Result" == 'Expected Result'
def _compare_serialization(value):
value_after = CacheClient._json_loads(CacheClient._json_dumps(value))
assert value_after == value
if isinstance(value, Decimal):
assert isinstance(value_after, Decimal)
elif isinstance(value, Binary):
assert isinstance(value_after, Binary)
elif isinstance(value, bytes):
assert isinstance(value_after, bytes)
def test_cache_serialization():
for val in (42, 'a', 3.14, True, None, b'abc',
b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
Binary(b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'),
Decimal('3.9'), [1, 2, 3], {'a': 1, 'b': 2}, [b'a', b'b', b'c'],
set(['a', 'b', 'c']), set([1, 2, 3]), set([Decimal('1.1'), Decimal('2.2'), Decimal('3.3')])):
_compare_serialization(val)
def _compare_results(real_response, cache_miss_response, cache_hit_response, cache_sc_response):
if 'Item' in real_response:
#print("real:", real_response['Item'])
#print("miss:", cache_miss_response['Item'])
#print("hit :", cache_hit_response['Item'])
#print("sc :", cache_sc_response['Item'])
assert real_response['Item'] == cache_miss_response['Item'] == cache_hit_response['Item'] == cache_sc_response['Item']
else:
assert 'Item' not in real_response
assert 'Item' not in cache_miss_response
assert 'Item' not in cache_hit_response
assert 'Item' not in cache_sc_response
if 'ConsumedCapacity' in real_response:
assert real_response['ConsumedCapacity'] == cache_miss_response['ConsumedCapacity']
assert real_response['ConsumedCapacity']['CapacityUnits'] * 2 == cache_sc_response['ConsumedCapacity']['CapacityUnits']
assert real_response['ConsumedCapacity'] != cache_hit_response['ConsumedCapacity']
assert real_response['ConsumedCapacity']["CapacityUnits"] == cache_miss_response["ConsumedCapacity"]["CapacityUnits"] > 0
assert cache_hit_response["ConsumedCapacity"]["CapacityUnits"] == 0.0
assert 'ResponseMetadata' in real_response
assert 'ResponseMetadata' in cache_miss_response
assert 'ResponseMetadata' not in cache_hit_response
assert 'ResponseMetadata' in cache_sc_response
assert 'CacheMetadata' not in real_response
assert 'CacheMetadata' not in cache_miss_response
assert 'CacheMetadata' in cache_hit_response
assert 'CacheMetadata' not in cache_sc_response
assert 'CacheHit' in cache_hit_response['CacheMetadata']
assert 'CachedTime' in cache_hit_response['CacheMetadata']
assert 'Client' in cache_hit_response['CacheMetadata']
def _client_get_item_series(dynamodb_client, cache_client, table_name, key, return_consumed_capacity):
real_response = dynamodb_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_miss_response = cache_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_hit_response = cache_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_sc_response = cache_client.get_item(
ConsistentRead=True,
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
_compare_results(real_response, cache_miss_response, cache_hit_response, cache_sc_response)
# Do it with a projection expression also
real_response = dynamodb_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity,
ProjectionExpression="pk"
)
cache_miss_response = cache_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity,
ProjectionExpression="pk"
)
cache_hit_response = cache_client.get_item(
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity,
ProjectionExpression="pk"
)
cache_sc_response = cache_client.get_item(
ConsistentRead=True,
TableName=table_name,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity,
ProjectionExpression="pk"
)
_compare_results(real_response, cache_miss_response, cache_hit_response, cache_sc_response)
def _resource_get_item_series(real_table, cache_table, key, return_consumed_capacity):
real_response = real_table.get_item(
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_miss_response = cache_table.get_item(
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_hit_response = cache_table.get_item(
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
cache_sc_response = cache_table.get_item(
ConsistentRead=True,
Key=key,
ReturnConsumedCapacity=return_consumed_capacity
)
_compare_results(real_response, cache_miss_response, cache_hit_response, cache_sc_response)
def test_client_get_item_SS(clients, table_ss):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_ss
sk = "x" + str(time.time()) # we want different on each run to avoid db side effects
item = {
"pk": {"S": "a"},
"sk": {"S": sk},
"Attribute1": {"N": "42"},
"Attribute2": {"S": "Hello"},
"Attribute3": {"N": "3.9"},
"Attribute4": {"BOOL": True},
"Attribute5": {"NULL": True},
"Attribute6": {"L": [{"N": "1"}, {"N": "2"}]},
"Attribute7": {"M": {"a": {"N": "1"}, "b": {"N": "2"}}},
"Attribute8": {"SS": ["a", "b", "c"]},
"Attribute9": {"NS": ["1", "2", "3"]},
"Attribute10": {"BS": [b"a", b"b", b"c"]},
"Attribute11": {"S": "a" * 10},
"Attribute12": {"B": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'}
}
key = {
"pk": {"S": "a"},
"sk": {"S": sk}
}
# Test in series: item missing, put, updated, batch put, tx updated, deleted, tx put, tx deleted
# After each one we confirm the get-item was invalidated with a cache miss followed by hit
_client_get_item_series(real_client, cache_client, tablename, key, "TOTAL")
cache_client.put_item(
TableName=tablename,
Item=item
)
_client_get_item_series(real_client, cache_client, tablename, key, "INDEXES")
cache_client.update_item(
TableName=tablename,
Key=key,
UpdateExpression="SET extraAttribute = :a",
ExpressionAttributeValues={":a": {"N": "99"}}
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.batch_write_item(
RequestItems={tablename: [{"PutRequest": {"Item": item}}]}
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.transact_write_items(
TransactItems=[
{"Update": {"TableName": tablename, "Key": key,
"UpdateExpression": "SET extraAttribute = :a", "ExpressionAttributeValues": {":a": {"N": "99"}}}}
]
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.delete_item(
TableName=tablename,
Key=key
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.transact_write_items(
TransactItems=[
{"Put": {"TableName": tablename, "Item": item, "ConditionExpression": "attribute_not_exists(pk)"}} # condition just for fun
]
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.transact_write_items(
TransactItems=[
{"Delete": {"TableName": tablename, "Key": key}}
]
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
def test_resource_get_item_SS(clients, table_ss):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_ss
sk = "x" + str(time.time()) # we want different on each run to avoid db side effects
item = {
"pk": "b",
"sk": sk,
"Attribute1": 42,
"Attribute2": "Hello",
"Attribute3": Decimal('3.9'),
"Attribute4": True,
"Attribute5": None,
'Attribute6': [1, 2],
'Attribute7': {'a': 1, 'b': 2},
'Attribute8': set(['a', 'b', 'c']),
'Attribute9': set([1, 2, 3]),
"Attribute10": set([b'a', b'b', b'c']),
'Attribute11': 'a' * 10,
'Attribute12': b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'
}
key = {
"pk": "b",
"sk": sk
}
real_table = real_resource.Table(tablename)
cache_table = cache_resource.Table(tablename)
_resource_get_item_series(real_table, cache_table, key, "TOTAL")
cache_table.put_item(Item=item)
_resource_get_item_series(real_table, cache_table, key, "INDEXES")
cache_table.update_item(
Key=key,
UpdateExpression="SET extraAttribute = :a",
ExpressionAttributeValues={":a": 99}
)
_resource_get_item_series(real_table, cache_table, key, "NONE")
cache_table.delete_item(
Key=key
)
_resource_get_item_series(real_table, cache_table, key, "NONE")
with cache_table.batch_writer() as batch:
batch.put_item(Item=item)
_resource_get_item_series(real_table, cache_table, key, "NONE")
with cache_table.batch_writer() as batch:
batch.delete_item(Key=key)
_resource_get_item_series(real_table, cache_table, key, "NONE")
def test_client_get_item_BN(clients, table_bn):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_bn
sk = time.time() # a float
item = {
"pk": {"B": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'},
"sk": {"N": str(sk)},
"Attribute1": {"S": "extra"}
}
key = {
"pk": {"B": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'},
"sk": {"N": str(sk)}
}
_client_get_item_series(real_client, cache_client, tablename, key, "TOTAL")
cache_client.put_item(
TableName=tablename,
Item=item
)
_client_get_item_series(real_client, cache_client, tablename, key, "INDEXES")
cache_client.update_item(
TableName=tablename,
Key=key,
UpdateExpression="SET extraAttribute = :a",
ExpressionAttributeValues={":a": {"N": "99"}}
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
cache_client.delete_item(
TableName=tablename,
Key=key
)
_client_get_item_series(real_client, cache_client, tablename, key, "NONE")
def test_resource_get_item_BN(clients, table_bn):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_bn
sk = time.time()
item = {
"pk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"sk": Decimal(sk),
"Attribute1": "extra"
}
key = {
"pk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"sk": Decimal(sk),
}
real_table = real_resource.Table(tablename)
cache_table = cache_resource.Table(tablename)
_resource_get_item_series(real_table, cache_table, key, "TOTAL")
cache_table.put_item(Item=item)
_resource_get_item_series(real_table, cache_table, key, "INDEXES")
cache_table.update_item(
Key=key,
UpdateExpression="SET extraAttribute = :a",
ExpressionAttributeValues={":a": 99}
)
_resource_get_item_series(real_table, cache_table, key, "NONE")
cache_table.delete_item(
Key=key
)
_resource_get_item_series(real_table, cache_table, key, "NONE")
def test_client_get_item_NB(clients, table_nb):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_nb
sk = time.time() # a float
item = {
"pk": {"N": str(sk)},
"sk": {"B": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'},
"Attribute1": {"S": "extra"}
}
key = {
"pk": {"N": str(sk)},
"sk": {"B": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'}
}
_client_get_item_series(real_client, cache_client, tablename, key, "TOTAL")
cache_client.put_item(
TableName=tablename,
Item=item
)
_client_get_item_series(real_client, cache_client, tablename, key, "INDEXES")
def test_resource_get_item_NB(clients, table_nb):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_nb
sk = time.time()
item = {
"pk": Decimal(sk),
"sk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"Attribute1": "extra"
}
key = {
"pk": Decimal(sk),
"sk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'
}
real_table = real_resource.Table(tablename)
cache_table = cache_resource.Table(tablename)
_resource_get_item_series(real_table, cache_table, key, "TOTAL")
cache_table.put_item(Item=item)
_resource_get_item_series(real_table, cache_table, key, "INDEXES")
def test_client_get_item_S(clients, table_s):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_s
sk = time.time() # a float
item = {
"pk": {"S": '\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'},
"Attribute1": {"S": "extra"}
}
key = {
"pk": {"S": '\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'}
}
_client_get_item_series(real_client, cache_client, tablename, key, "TOTAL")
cache_client.put_item(
TableName=tablename,
Item=item
)
_client_get_item_series(real_client, cache_client, tablename, key, "INDEXES")
def test_resource_get_item_S(clients, table_s):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_s
sk = time.time()
item = {
"pk": '\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"Attribute1": "extra"
}
key = {
"pk": '\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'
}
real_table = real_resource.Table(tablename)
cache_table = cache_resource.Table(tablename)
_resource_get_item_series(real_table, cache_table, key, "TOTAL")
cache_table.put_item(Item=item)
_resource_get_item_series(real_table, cache_table, key, "INDEXES")
def test_mixed_get_item_BN(clients, table_bn):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_bn
pk = b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81'
sk = Decimal(time.time()) # a float
item = {
"pk": {"B": pk},
"sk": {"N": str(sk)},
"Attribute1": {"S": "extra"}
}
key = {
"pk": {"B": pk},
"sk": {"N": str(sk)}
}
itemResource = {
"pk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"sk": sk,
"Attribute1": "extra"
}
keyResource = {
"pk": b'\x48\x65\x6c\x6c\x6f\x00\x01\x02\xfe\xff\x48\x69\x20\xF0\x9F\x98\x81',
"sk": sk,
}
real_table = real_resource.Table(tablename)
cache_table = cache_resource.Table(tablename)
# Prime the pump by putting the item
cache_table.put_item(Item=itemResource)
# Now the test is that the next client call is a hit, that the caches are shared
cache_client_response = cache_client.get_item(
TableName=tablename,
Key=key
)
cache_client_response = cache_client.get_item(
TableName=tablename,
Key=key
)
cache_resource_response = cache_table.get_item(
Key=keyResource
)
cache_resource_response = cache_table.get_item(
Key=keyResource
)
assert 'CacheMetadata' in cache_client_response
assert 'CacheMetadata' in cache_resource_response
# Now delete the item and make sure it invalidated both client and resource versions
cache_table.delete_item(Key=keyResource)
cache_client_response = cache_client.get_item(
TableName=tablename,
Key=key
)
cache_resource_response = cache_table.get_item(
Key=keyResource
)
assert 'CacheMetadata' not in cache_resource_response
assert 'CacheMetadata' not in cache_client_response
# ----------------------------------------------------
def _compare_query_results(real_response, cache_miss_response, cache_hit_response):
#print("real:", real_response)
#print("miss:", cache_miss_response)
#print("hit :", cache_hit_response)
assert real_response['Count'] == cache_miss_response['Count'] == cache_hit_response['Count']
assert real_response['Items'] == cache_miss_response['Items'] == cache_hit_response['Items']
assert real_response['ScannedCount'] == cache_miss_response['ScannedCount'] == cache_hit_response['ScannedCount']
if 'LastEvaluatedKey' in real_response:
assert real_response['LastEvaluatedKey'] == cache_miss_response['LastEvaluatedKey'] == cache_hit_response['LastEvaluatedKey']
if 'ConsumedCapacity' in real_response:
assert real_response['ConsumedCapacity'] == cache_miss_response['ConsumedCapacity']
assert real_response['ConsumedCapacity'] != cache_hit_response['ConsumedCapacity']
assert real_response['ConsumedCapacity']["CapacityUnits"] == cache_miss_response["ConsumedCapacity"]["CapacityUnits"] > 0
assert cache_hit_response["ConsumedCapacity"]["CapacityUnits"] == 0.0
if 'Table' in real_response['ConsumedCapacity']:
assert real_response['ConsumedCapacity']['Table'] == cache_miss_response['ConsumedCapacity']['Table']
assert cache_hit_response["ConsumedCapacity"]["Table"]["CapacityUnits"] == 0.0
if 'GlobalSecondaryIndexes' in real_response['ConsumedCapacity']:
assert real_response['ConsumedCapacity']['GlobalSecondaryIndexes'] == cache_miss_response['ConsumedCapacity']['GlobalSecondaryIndexes']
inx = cache_hit_response['ConsumedCapacity']['GlobalSecondaryIndexes']
assert all(inx[key]["CapacityUnits"] == 0.0 for key in inx), "Not all hit GSI CapacityUnits are 0.0"
if 'LocalSecondaryIndexes' in real_response['ConsumedCapacity']:
assert real_response['ConsumedCapacity']['LocalSecondaryIndexes'] == cache_miss_response['ConsumedCapacity']['LocalSecondaryIndexes']
inx = cache_hit_response['ConsumedCapacity']['LocalSecondaryIndexes']
assert all(inx[key]["CapacityUnits"] == 0.0 for key in inx), "Not all hit LSI CapacityUnits are 0.0"
assert 'ResponseMetadata' in real_response
assert 'ResponseMetadata' in cache_miss_response
assert 'ResponseMetadata' not in cache_hit_response
assert 'CacheMetadata' not in real_response
assert 'CacheMetadata' not in cache_miss_response
assert 'CacheMetadata' in cache_hit_response
assert 'CacheHit' in cache_hit_response['CacheMetadata']
assert 'CachedTime' in cache_hit_response['CacheMetadata']
assert 'Client' in cache_hit_response['CacheMetadata']
def _client_query_series(dynamodb_client, cache_client, core_values):
real_response = dynamodb_client.query(
**core_values
)
cache_miss_response = cache_client.query(
**core_values
)
cache_hit_response = cache_client.query(
**core_values
)
_compare_query_results(real_response, cache_miss_response, cache_hit_response)
if 'LastEvaluatedKey' in real_response:
lek = real_response['LastEvaluatedKey']
real_response = dynamodb_client.query(
**core_values,
ExclusiveStartKey = lek
)
cache_miss_response = cache_client.query(
**core_values,
ExclusiveStartKey = lek
)
cache_hit_response = cache_client.query(
**core_values,
ExclusiveStartKey = lek
)
_compare_query_results(real_response, cache_miss_response, cache_hit_response)
def test_client_query_SS(clients, table_ss_loaded):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_ss_loaded
core_values = dict(
TableName = tablename,
KeyConditionExpression = "pk = :value",
ExpressionAttributeValues = {':value': {'S': 'queryme'}},
ReturnConsumedCapacity = "INDEXES"
)
_client_query_series(real_client, cache_client, core_values)
# Do with a GSI too
core_values["IndexName"] = "GSI1"
_client_query_series(real_client, cache_client, core_values)
# Add more args
core_values["Limit"] = 1
core_values["ScanIndexForward"] = False
_client_query_series(real_client, cache_client, core_values)
# Add a projection
core_values["ProjectionExpression"] = "pk"
_client_query_series(real_client, cache_client, core_values)
# Add a filter
core_values["FilterExpression"] = "Attribute1 > :val"
core_values["ExpressionAttributeValues"][":val"] = {"S": "A"} # syntax adds to the existing dict
_client_query_series(real_client, cache_client, core_values)
# ----------------------------------------------------
def _resource_query_series(real_table, cache_table, core_values):
real_response = real_table.query(
**core_values
)
cache_miss_response = cache_table.query(
**core_values
)
cache_hit_response = cache_table.query(
**core_values
)
_compare_query_results(real_response, cache_miss_response, cache_hit_response)
if 'LastEvaluatedKey' in real_response:
lek = real_response['LastEvaluatedKey']
real_response = real_table.query(
**core_values,
ExclusiveStartKey = lek
)
cache_miss_response = cache_table.query(
**core_values,
ExclusiveStartKey = lek
)
cache_hit_response = cache_table.query(
**core_values,
ExclusiveStartKey = lek
)
_compare_query_results(real_response, cache_miss_response, cache_hit_response)
def test_resource_query_SS(clients, table_ss_loaded):
real_client, cache_client, real_resource, cache_resource = clients
real_table = real_resource.Table(table_ss_loaded)
cache_table = cache_resource.Table(table_ss_loaded)
core_values = dict(
KeyConditionExpression=Key('pk').eq('queryme'),
ReturnConsumedCapacity = "INDEXES"
)
_resource_query_series(real_table, cache_table, core_values)
# Do with a GSI too
core_values["IndexName"] = "GSI1"
_resource_query_series(real_table, cache_table, core_values)
# Add more args
core_values["Limit"] = 1
core_values["ScanIndexForward"] = False
_resource_query_series(real_table, cache_table, core_values)
# Add a projection
core_values["ProjectionExpression"] = "pk"
_resource_query_series(real_table, cache_table, core_values)
# Add a filter
core_values["FilterExpression"] = Attr("Attribute1").gt("A")
_resource_query_series(real_table, cache_table, core_values)
# Throw a wide variety of conditions that need to be correctly serialized
core_values["FilterExpression"] = Attr('score').gt(50)
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('date').lte('2022-12-31')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('age').between(20, 30)
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('name').begins_with('J')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('description').contains('keyword')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('status').is_in(['new', 'in_progress', 'done'])
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('x').ne('value')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('x').eq('value')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('isActive').eq(True)
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('category').eq('books') & Attr('category').eq('electronics')
_resource_query_series(real_table, cache_table, core_values)
core_values["FilterExpression"] = Attr('category').eq('books') | Attr("Attribute1").gt("B")
_resource_query_series(real_table, cache_table, core_values)
# ----------------------------------------------------
# Scans have the purgatory system so it's two misses before the hit
def _compare_scan_results(real_response, cache_miss_response, cache_purgatory_response, cache_hit_response):
#print("real:", real_response)
#print("miss:", cache_miss_response)
#print("purg:", cache_purgatory_response)
#print("hit :", cache_hit_response)
assert real_response['Count'] == cache_miss_response['Count'] == cache_purgatory_response['Count'] == cache_hit_response['Count']
assert real_response['Items'] == cache_miss_response['Items'] == cache_purgatory_response['Items'] == cache_hit_response['Items']
assert real_response['ScannedCount'] == cache_miss_response['ScannedCount'] == cache_purgatory_response['ScannedCount'] == cache_hit_response['ScannedCount']
if 'LastEvaluatedKey' in real_response:
assert real_response['LastEvaluatedKey'] == cache_miss_response['LastEvaluatedKey'] == cache_purgatory_response['LastEvaluatedKey'] == cache_hit_response['LastEvaluatedKey']
if 'ConsumedCapacity' in real_response:
assert real_response['ConsumedCapacity'] == cache_miss_response['ConsumedCapacity'] == cache_purgatory_response['ConsumedCapacity']
assert real_response['ConsumedCapacity'] != cache_hit_response['ConsumedCapacity']
assert real_response['ConsumedCapacity']["CapacityUnits"] == cache_miss_response["ConsumedCapacity"]["CapacityUnits"] == cache_purgatory_response["ConsumedCapacity"]["CapacityUnits"] > 0
assert cache_hit_response["ConsumedCapacity"]["CapacityUnits"] == 0.0
assert 'ResponseMetadata' in real_response
assert 'ResponseMetadata' in cache_miss_response
assert 'ResponseMetadata' in cache_purgatory_response
assert 'ResponseMetadata' not in cache_hit_response
assert 'CacheMetadata' not in real_response
assert 'CacheMetadata' not in cache_miss_response
assert 'CacheMetadata' not in cache_purgatory_response
assert 'CacheMetadata' in cache_hit_response
assert 'CacheHit' in cache_hit_response['CacheMetadata']
assert 'CachedTime' in cache_hit_response['CacheMetadata']
assert 'Client' in cache_hit_response['CacheMetadata']
def _client_scan_series(dynamodb_client, cache_client, core_values):
real_response = dynamodb_client.scan(
**core_values
)
cache_miss_response = cache_client.scan(
**core_values
)
cache_purgatory_response = cache_client.scan(
**core_values
)
cache_hit_response = cache_client.scan(
**core_values
)
_compare_scan_results(real_response, cache_miss_response, cache_purgatory_response, cache_hit_response)
if 'LastEvaluatedKey' in real_response:
lek = real_response['LastEvaluatedKey']
real_response = dynamodb_client.scan(
**core_values,
ExclusiveStartKey = lek
)
cache_miss_response = cache_client.scan(
**core_values,
ExclusiveStartKey = lek
)
cache_purgatory_response = cache_client.scan(
**core_values,
ExclusiveStartKey = lek
)
cache_hit_response = cache_client.scan(
**core_values,
ExclusiveStartKey = lek
)
_compare_scan_results(real_response, cache_miss_response, cache_purgatory_response, cache_hit_response)
def test_client_scan_SS(clients, table_ss_loaded):
real_client, cache_client, real_resource, cache_resource = clients
tablename = table_ss_loaded
core_values = dict(
TableName = tablename,
ReturnConsumedCapacity = "INDEXES"
)
_client_scan_series(real_client, cache_client, core_values)
# Do with a GSI too
core_values["IndexName"] = "GSI1"
_client_scan_series(real_client, cache_client, core_values)
# Add more args
core_values["Limit"] = 1
_client_scan_series(real_client, cache_client, core_values)
# Add a projection
core_values["ProjectionExpression"] = "pk"
_client_scan_series(real_client, cache_client, core_values) # this one is the one dying
# Add a filter
core_values["FilterExpression"] = "Attribute1 > :val"
core_values["ExpressionAttributeValues"] = {':val': {"S": "A"}}
_client_scan_series(real_client, cache_client, core_values)
def _resource_scan_series(real_table, cache_table, core_values):
real_response = real_table.scan(
**core_values
)
cache_miss_response = cache_table.scan(
**core_values
)
cache_purgatory_response = cache_table.scan(
**core_values
)
cache_hit_response = cache_table.scan(
**core_values
)
_compare_scan_results(real_response, cache_miss_response, cache_purgatory_response, cache_hit_response)
if 'LastEvaluatedKey' in real_response:
lek = real_response['LastEvaluatedKey']