-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathtest_dynamodb_exceptions.py
More file actions
1419 lines (1247 loc) · 50.8 KB
/
test_dynamodb_exceptions.py
File metadata and controls
1419 lines (1247 loc) · 50.8 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
from unittest import SkipTest
import boto3
import botocore
import pytest
from boto3.dynamodb.conditions import Key
from botocore.exceptions import ClientError
from moto import mock_aws, settings
from .. import dynamodb_aws_verified
table_schema = {
"KeySchema": [{"AttributeName": "partitionKey", "KeyType": "HASH"}],
"GlobalSecondaryIndexes": [
{
"IndexName": "GSI-K1",
"KeySchema": [
{"AttributeName": "gsiK1PartitionKey", "KeyType": "HASH"},
{"AttributeName": "gsiK1SortKey", "KeyType": "RANGE"},
],
"Projection": {"ProjectionType": "KEYS_ONLY"},
}
],
"AttributeDefinitions": [
{"AttributeName": "partitionKey", "AttributeType": "S"},
{"AttributeName": "gsiK1PartitionKey", "AttributeType": "S"},
{"AttributeName": "gsiK1SortKey", "AttributeType": "S"},
],
}
@mock_aws
def test_query_gsi_with_wrong_key_attribute_names_throws_exception():
item = {
"partitionKey": "pk-1",
"gsiK1PartitionKey": "gsi-pk",
"gsiK1SortKey": "gsi-sk",
"someAttribute": "lore ipsum",
}
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
table = dynamodb.Table("test-table")
table.put_item(Item=item)
# check using wrong name for sort key throws exception
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression="gsiK1PartitionKey = :pk AND wrongName = :sk",
ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
IndexName="GSI-K1",
)["Items"]
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"
# check using wrong name for partition key throws exception
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression="wrongName = :pk AND gsiK1SortKey = :sk",
ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
IndexName="GSI-K1",
)["Items"]
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"] == "Query condition missed key schema element: gsiK1PartitionKey"
)
# verify same behaviour for begins_with
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression="gsiK1PartitionKey = :pk AND begins_with ( wrongName , :sk )",
ExpressionAttributeValues={":pk": "gsi-pk", ":sk": "gsi-sk"},
IndexName="GSI-K1",
)["Items"]
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"
# verify same behaviour for between
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression="gsiK1PartitionKey = :pk AND wrongName BETWEEN :sk1 and :sk2",
ExpressionAttributeValues={
":pk": "gsi-pk",
":sk1": "gsi-sk",
":sk2": "gsi-sk2",
},
IndexName="GSI-K1",
)["Items"]
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Query condition missed key schema element: gsiK1SortKey"
@mock_aws
def test_query_table_with_wrong_key_attribute_names_throws_exception():
item = {
"partitionKey": "pk-1",
"someAttribute": "lore ipsum",
}
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
table = dynamodb.Table("test-table")
table.put_item(Item=item)
# check using wrong name for sort key throws exception
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression="wrongName = :pk",
ExpressionAttributeValues={":pk": "pk"},
)["Items"]
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Query condition missed key schema element: partitionKey"
@mock_aws
def test_empty_expressionattributenames():
ddb = boto3.resource("dynamodb", region_name="us-east-1")
ddb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
table = ddb.Table("test-table")
with pytest.raises(ClientError) as exc:
table.get_item(Key={"id": "my_id"}, ExpressionAttributeNames={})
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "ExpressionAttributeNames can only be specified when using expressions"
)
@mock_aws
def test_empty_expressionattributenames_with_empty_projection():
ddb = boto3.resource("dynamodb", region_name="us-east-1")
ddb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
table = ddb.Table("test-table")
with pytest.raises(ClientError) as exc:
table.get_item(
Key={"id": "my_id"}, ProjectionExpression="a", ExpressionAttributeNames={}
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "ExpressionAttributeNames must not be empty"
@mock_aws
def test_empty_expressionattributenames_with_projection():
ddb = boto3.resource("dynamodb", region_name="us-east-1")
ddb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
table = ddb.Table("test-table")
with pytest.raises(ClientError) as exc:
table.get_item(
Key={"id": "my_id"}, ProjectionExpression="id", ExpressionAttributeNames={}
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "ExpressionAttributeNames must not be empty"
@mock_aws
def test_update_item_range_key_set():
ddb = boto3.resource("dynamodb", region_name="us-east-1")
# Create the DynamoDB table.
table = ddb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **table_schema
)
with pytest.raises(ClientError) as exc:
table.update_item(
Key={"partitionKey": "the-key"},
UpdateExpression="ADD x :one SET a = :a ADD y :one",
ExpressionAttributeValues={":one": 1, ":a": "lore ipsum"},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== 'Invalid UpdateExpression: The "ADD" section can only be used once in an update expression;'
)
@mock_aws
def test_batch_get_item_non_existing_table():
client = boto3.client("dynamodb", region_name="us-west-2")
with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
client.batch_get_item(RequestItems={"my-table": {"Keys": [{"id": {"N": "0"}}]}})
err = exc.value.response["Error"]
assert err["Code"] == "ResourceNotFoundException"
assert err["Message"] == "Requested resource not found"
@mock_aws
def test_batch_write_item_non_existing_table():
client = boto3.client("dynamodb", region_name="us-west-2")
with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
# Table my-table does not exist
client.batch_write_item(
RequestItems={"my-table": [{"PutRequest": {"Item": {}}}]}
)
err = exc.value.response["Error"]
assert err["Code"] == "ResourceNotFoundException"
assert err["Message"] == "Requested resource not found"
@mock_aws
def test_create_table_with_redundant_attributes():
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
{"AttributeName": "created_at", "AttributeType": "N"},
],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Number of attributes in KeySchema does not exactly match number of attributes defined in AttributeDefinitions"
)
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
{"AttributeName": "user", "AttributeType": "S"},
{"AttributeName": "created_at", "AttributeType": "N"},
],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
GlobalSecondaryIndexes=[
{
"IndexName": "gsi_user-items",
"KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"},
}
],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Some AttributeDefinitions are not used. AttributeDefinitions: [created_at, id, user], keys used: [id, user]"
)
@mock_aws
def test_create_table_with_missing_attributes():
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
KeySchema=[
{"AttributeName": "id", "KeyType": "HASH"},
{"AttributeName": "created_at", "KeyType": "RANGE"},
],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "Invalid KeySchema: Some index key attribute have no definition"
)
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
GlobalSecondaryIndexes=[
{
"IndexName": "gsi_user-items",
"KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"},
}
],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [user], AttributeDefinitions: [id]"
)
@mock_aws
def test_create_table_with_redundant_and_missing_attributes():
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "created_at", "AttributeType": "N"}
],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [id], AttributeDefinitions: [created_at]"
)
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
{"AttributeName": "created_at", "AttributeType": "N"},
],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
GlobalSecondaryIndexes=[
{
"IndexName": "gsi_user-items",
"KeySchema": [{"AttributeName": "user", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"},
}
],
BillingMode="PAY_PER_REQUEST",
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Some index key attributes are not defined in AttributeDefinitions. Keys: [user], AttributeDefinitions: [created_at, id]"
)
@mock_aws
def test_put_item_wrong_attribute_type():
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
{"AttributeName": "created_at", "AttributeType": "N"},
],
KeySchema=[
{"AttributeName": "id", "KeyType": "HASH"},
{"AttributeName": "created_at", "KeyType": "RANGE"},
],
BillingMode="PAY_PER_REQUEST",
)
item = {
"id": {"N": "1"}, # should be a string
"created_at": {"N": "2"},
"someAttribute": {"S": "lore ipsum"},
}
with pytest.raises(ClientError) as exc:
dynamodb.put_item(TableName="test-table", Item=item)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Type mismatch for key id expected: S actual: N"
)
item = {
"id": {"S": "some id"},
"created_at": {"S": "should be date not string"},
"someAttribute": {"S": "lore ipsum"},
}
with pytest.raises(ClientError) as exc:
dynamodb.put_item(TableName="test-table", Item=item)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Type mismatch for key created_at expected: N actual: S"
)
@mock_aws
# https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_Query.html#DDB-Query-request-KeyConditionExpression
def test_hash_key_cannot_use_begins_with_operations():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "key", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "key", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
items = [
{"key": "prefix-$LATEST", "value": "$LATEST"},
{"key": "prefix-DEV", "value": "DEV"},
{"key": "prefix-PROD", "value": "PROD"},
]
with table.batch_writer() as batch:
for item in items:
batch.put_item(Item=item)
table = dynamodb.Table("test-table")
with pytest.raises(ClientError) as ex:
table.query(KeyConditionExpression=Key("key").begins_with("prefix-"))
assert ex.value.response["Error"]["Code"] == "ValidationException"
assert ex.value.response["Error"]["Message"] == "Query key condition not supported"
# Test this again, but with manually supplying an operator
@mock_aws
@pytest.mark.parametrize("operator", ["<", "<=", ">", ">="])
def test_hash_key_can_only_use_equals_operations(operator):
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
table = dynamodb.Table("test-table")
with pytest.raises(ClientError) as exc:
table.query(
KeyConditionExpression=f"pk {operator} :pk",
ExpressionAttributeValues={":pk": "p"},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Query key condition not supported"
@mock_aws
def test_creating_table_with_0_local_indexes():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
LocalSecondaryIndexes=[],
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: List of LocalSecondaryIndexes is empty"
)
@mock_aws
def test_creating_table_with_0_global_indexes():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
with pytest.raises(ClientError) as exc:
dynamodb.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
GlobalSecondaryIndexes=[],
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: List of GlobalSecondaryIndexes is empty"
)
@mock_aws
def test_multiple_transactions_on_same_item():
schema = {
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
}
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **schema
)
# Insert an item
dynamodb.put_item(TableName="test-table", Item={"id": {"S": "foo"}})
def update_email_transact(email):
return {
"Update": {
"Key": {"id": {"S": "foo"}},
"TableName": "test-table",
"UpdateExpression": "SET #e = :v",
"ExpressionAttributeNames": {"#e": "email_address"},
"ExpressionAttributeValues": {":v": {"S": email}},
}
}
with pytest.raises(ClientError) as exc:
dynamodb.transact_write_items(
TransactItems=[
update_email_transact("test1@moto.com"),
update_email_transact("test2@moto.com"),
]
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "Transaction request cannot include multiple operations on one item"
)
@mock_aws
def test_transact_write_items__too_many_transactions():
schema = {
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
}
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **schema
)
def update_email_transact(email):
return {
"Put": {
"TableName": "test-table",
"Item": {"pk": {"S": ":v"}},
"ExpressionAttributeValues": {":v": {"S": email}},
}
}
update_email_transact("test1@moto.com")
with pytest.raises(ClientError) as exc:
dynamodb.transact_write_items(
TransactItems=[
update_email_transact(f"test{idx}@moto.com") for idx in range(101)
]
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "1 validation error detected at 'transactItems' failed to satisfy constraint: Member must have length less than or equal to 100."
)
@mock_aws
def test_update_item_non_existent_table():
client = boto3.client("dynamodb", region_name="us-west-2")
with pytest.raises(client.exceptions.ResourceNotFoundException) as exc:
client.update_item(
TableName="non-existent",
Key={"forum_name": {"S": "LOLCat Forum"}},
UpdateExpression="set Body=:Body",
ExpressionAttributeValues={":Body": {"S": ""}},
)
err = exc.value.response["Error"]
assert err["Code"] == "ResourceNotFoundException"
assert err["Message"] == "Requested resource not found"
@mock_aws
@pytest.mark.parametrize(
"expression",
[
"set example_column = :example_column, example_column = :example_column",
"set example_column = :example_column ADD x :y set example_column = :example_column",
],
)
def test_update_item_with_duplicate_expressions(expression):
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="example_table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
record = {
"pk": "example_id",
"example_column": "example",
}
table = dynamodb.Table("example_table")
table.put_item(Item=record)
with pytest.raises(ClientError) as exc:
table.update_item(
Key={"pk": "example_id"},
UpdateExpression=expression,
ExpressionAttributeValues={":example_column": "test"},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "Invalid UpdateExpression: Two document paths overlap with each other; must remove or rewrite one of these paths; path one: [example_column], path two: [example_column]"
)
# The item is not updated
item = table.get_item(Key={"pk": "example_id"})["Item"]
assert item == {"pk": "example_id", "example_column": "example"}
@mock_aws
def test_put_item_wrong_datatype():
if settings.TEST_SERVER_MODE:
raise SkipTest("Unable to mock a session with Config in ServerMode")
session = botocore.session.Session()
config = botocore.client.Config(parameter_validation=False)
client = session.create_client("dynamodb", region_name="us-east-1", config=config)
client.create_table(
TableName="test2",
KeySchema=[{"AttributeName": "mykey", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "mykey", "AttributeType": "N"}],
BillingMode="PAY_PER_REQUEST",
)
with pytest.raises(ClientError) as exc:
client.put_item(TableName="test2", Item={"mykey": {"N": 123}})
err = exc.value.response["Error"]
assert err["Code"] == "SerializationException"
assert err["Message"] == "NUMBER_VALUE cannot be converted to String"
# Same thing - but with a non-key, and nested
with pytest.raises(ClientError) as exc:
client.put_item(
TableName="test2",
Item={"mykey": {"N": "123"}, "nested": {"M": {"sth": {"N": 5}}}},
)
err = exc.value.response["Error"]
assert err["Code"] == "SerializationException"
assert err["Message"] == "NUMBER_VALUE cannot be converted to String"
@mock_aws
def test_put_item_empty_set():
client = boto3.client("dynamodb", region_name="us-east-1")
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
client.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "Key", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "Key", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table = dynamodb.Table("test-table")
with pytest.raises(ClientError) as exc:
table.put_item(Item={"Key": "some-irrelevant_key", "attr2": {"SS": set([])}})
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: An number set may not be empty"
)
@mock_aws
def test_put_item_returns_old_item():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table.put_item(Item={"pk": "foo", "bar": "baz"})
with pytest.raises(ClientError) as exc:
table.put_item(
Item={"pk": "foo", "bar": "quuz"},
ConditionExpression="attribute_not_exists(pk)",
)
resp = exc.value.response
assert resp["Error"] == {
"Message": "The conditional request failed",
"Code": "ConditionalCheckFailedException",
}
assert resp["message"] == "The conditional request failed"
assert "Item" not in resp
table.put_item(Item={"pk": "foo", "bar": "baz"})
with pytest.raises(ClientError) as exc:
table.put_item(
Item={"pk": "foo", "bar": "quuz"},
ReturnValuesOnConditionCheckFailure="ALL_OLD",
ConditionExpression="attribute_not_exists(pk)",
)
resp = exc.value.response
assert resp["Error"] == {
"Message": "The conditional request failed",
"Code": "ConditionalCheckFailedException",
}
assert "message" not in resp
assert resp["Item"] == {"pk": {"S": "foo"}, "bar": {"S": "baz"}}
@mock_aws
def test_update_expression_with_trailing_comma():
resource = boto3.resource(service_name="dynamodb", region_name="us-east-1")
table = resource.create_table(
TableName="test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
table.put_item(Item={"pk": "key", "attr2": 2})
with pytest.raises(ClientError) as exc:
table.update_item(
Key={"pk": "key", "sk": "sk"},
# Trailing comma should be invalid
UpdateExpression="SET #attr1 = :val1, #attr2 = :val2,",
ExpressionAttributeNames={"#attr1": "attr1", "#attr2": "attr2"},
ExpressionAttributeValues={":val1": 3, ":val2": 4},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== 'Invalid UpdateExpression: Syntax error; token: "<EOF>", near: ","'
)
@mock_aws
def test_batch_items_should_throw_exception_for_duplicate_request(
ddb_resource, create_user_table, users_table_name
):
# Setup
table = ddb_resource.Table(users_table_name)
test_item = {"forum_name": "test_dupe", "subject": "test1"}
# Execute
with pytest.raises(ClientError) as ex:
with table.batch_writer() as batch:
for i in range(0, 5):
batch.put_item(Item=test_item)
with pytest.raises(ClientError) as ex2:
with table.batch_writer() as batch:
for i in range(0, 5):
batch.delete_item(Key=test_item)
# Verify
err = ex.value.response["Error"]
assert err["Code"] == "ValidationException"
assert err["Message"] == "Provided list of item keys contains duplicates"
err2 = ex2.value.response["Error"]
assert err2["Code"] == "ValidationException"
assert err2["Message"] == "Provided list of item keys contains duplicates"
@mock_aws
def test_batch_put_item_with_empty_value():
ddb = boto3.resource("dynamodb", region_name="us-east-1")
ddb.create_table(
AttributeDefinitions=[
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"},
],
TableName="test-table",
KeySchema=[
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"},
],
ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
)
table = ddb.Table("test-table")
# Empty Partition Key throws an error
with pytest.raises(botocore.exceptions.ClientError) as exc:
with table.batch_writer() as batch:
batch.put_item(Item={"pk": "", "sk": "sth"})
err = exc.value.response["Error"]
assert (
err["Message"]
== "One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: pk"
)
assert err["Code"] == "ValidationException"
# Empty SortKey throws an error
with pytest.raises(botocore.exceptions.ClientError) as exc:
with table.batch_writer() as batch:
batch.put_item(Item={"pk": "sth", "sk": ""})
err = exc.value.response["Error"]
assert (
err["Message"]
== "One or more parameter values are not valid. The AttributeValue for a key attribute cannot contain an empty string value. Key: sk"
)
assert err["Code"] == "ValidationException"
# Empty regular parameter workst just fine though
with table.batch_writer() as batch:
batch.put_item(Item={"pk": "sth", "sk": "else", "par": ""})
@mock_aws
def test_query_begins_with_without_brackets():
client = boto3.client("dynamodb", region_name="us-east-1")
client.create_table(
TableName="test-table",
AttributeDefinitions=[
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"},
],
KeySchema=[
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"},
],
ProvisionedThroughput={"ReadCapacityUnits": 123, "WriteCapacityUnits": 123},
)
with pytest.raises(ClientError) as exc:
client.query(
TableName="test-table",
KeyConditionExpression="pk=:pk AND begins_with sk, :sk ",
ExpressionAttributeValues={":pk": {"S": "test1"}, ":sk": {"S": "test2"}},
)
err = exc.value.response["Error"]
assert err["Message"] == 'Invalid KeyConditionExpression: Syntax error; token: "sk"'
assert err["Code"] == "ValidationException"
@mock_aws
def test_transact_write_items_multiple_operations_fail():
# Setup
schema = {
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
}
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
table_name = "test-table"
dynamodb.create_table(TableName=table_name, BillingMode="PAY_PER_REQUEST", **schema)
# Execute
with pytest.raises(ClientError) as exc:
dynamodb.transact_write_items(
TransactItems=[
{
"Put": {
"Item": {"id": {"S": "test"}},
"TableName": table_name,
},
"Delete": {
"Key": {"id": {"S": "test"}},
"TableName": table_name,
},
}
]
)
# Verify
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "TransactItems can only contain one of Check, Put, Update or Delete"
)
@mock_aws
def test_transact_write_items_with_empty_gsi_key():
client = boto3.client("dynamodb", "us-east-2")
client.create_table(
TableName="test_table",
KeySchema=[{"AttributeName": "unique_code", "KeyType": "HASH"}],
AttributeDefinitions=[
{"AttributeName": "unique_code", "AttributeType": "S"},
{"AttributeName": "unique_id", "AttributeType": "S"},
],
GlobalSecondaryIndexes=[
{
"IndexName": "gsi_index",
"KeySchema": [{"AttributeName": "unique_id", "KeyType": "HASH"}],
"Projection": {"ProjectionType": "ALL"},
}
],
ProvisionedThroughput={"ReadCapacityUnits": 5, "WriteCapacityUnits": 5},
)
transact_items = [
{
"Put": {
"Item": {"unique_code": {"S": "some code"}, "unique_id": {"S": ""}},
"TableName": "test_table",
}
}
]
with pytest.raises(ClientError) as exc:
client.transact_write_items(TransactItems=transact_items)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values are not valid. A value specified for a secondary index key is not supported. The AttributeValue for a key attribute cannot contain an empty string value. IndexName: gsi_index, IndexKey: unique_id"
)
@mock_aws
def test_update_primary_key_with_sortkey():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
schema = {
"KeySchema": [
{"AttributeName": "pk", "KeyType": "HASH"},
{"AttributeName": "sk", "KeyType": "RANGE"},
],
"AttributeDefinitions": [
{"AttributeName": "pk", "AttributeType": "S"},
{"AttributeName": "sk", "AttributeType": "S"},
],
}
dynamodb.create_table(
TableName="test-table", BillingMode="PAY_PER_REQUEST", **schema
)
table = dynamodb.Table("test-table")
base_item = {"pk": "testchangepk", "sk": "else"}
table.put_item(Item=base_item)
with pytest.raises(ClientError) as exc:
table.update_item(
Key={"pk": "n/a", "sk": "else"},
UpdateExpression="SET #attr1 = :val1",
ExpressionAttributeNames={"#attr1": "pk"},
ExpressionAttributeValues={":val1": "different"},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Cannot update attribute pk. This attribute is part of the key"
)
item = table.get_item(Key={"pk": "testchangepk", "sk": "else"})["Item"]
assert item == {"pk": "testchangepk", "sk": "else"}
@mock_aws
def test_update_primary_key():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
schema = {
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
}
dynamodb.create_table(
TableName="without_sk", BillingMode="PAY_PER_REQUEST", **schema
)
table = dynamodb.Table("without_sk")
base_item = {"pk": "testchangepk"}
table.put_item(Item=base_item)
with pytest.raises(ClientError) as exc:
table.update_item(
Key={"pk": "n/a"},
UpdateExpression="SET #attr1 = :val1",
ExpressionAttributeNames={"#attr1": "pk"},
ExpressionAttributeValues={":val1": "different"},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "One or more parameter values were invalid: Cannot update attribute pk. This attribute is part of the key"
)
item = table.get_item(Key={"pk": "testchangepk"})["Item"]
assert item == {"pk": "testchangepk"}
@mock_aws
def test_put_item__string_as_integer_value():
if settings.TEST_SERVER_MODE:
raise SkipTest("Unable to mock a session with Config in ServerMode")
session = botocore.session.Session()