-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathtest_dynamodb_condition_expressions.py
More file actions
774 lines (685 loc) · 27.4 KB
/
Copy pathtest_dynamodb_condition_expressions.py
File metadata and controls
774 lines (685 loc) · 27.4 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
import re
from decimal import Decimal
from uuid import uuid4
import boto3
import pytest
from botocore.exceptions import ClientError
from moto import mock_aws
@mock_aws
def test_condition_expression_with_dot_in_attr_name():
dynamodb = boto3.resource("dynamodb", region_name="us-east-2")
table_name = f"T{uuid4()}"
dynamodb.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table = dynamodb.Table(table_name)
email_like_str = "test@foo.com"
record = {"id": "key-0", "first": {email_like_str: {"third": {"VALUE"}}}}
table.put_item(Item=record)
table.update_item(
Key={"id": "key-0"},
UpdateExpression="REMOVE #first.#second, #other",
ExpressionAttributeNames={
"#first": "first",
"#second": email_like_str,
"#third": "third",
"#other": "other",
},
ExpressionAttributeValues={":value": "VALUE", ":one": 1},
ConditionExpression="size(#first.#second.#third) = :one AND contains(#first.#second.#third, :value)",
ReturnValues="ALL_NEW",
)
item = table.get_item(Key={"id": "key-0"})["Item"]
assert item == {"id": "key-0", "first": {}}
@mock_aws
def test_condition_expressions():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
# Create the DynamoDB table.
client.create_table(
TableName=table_name,
AttributeDefinitions=[
{"AttributeName": "client", "AttributeType": "S"},
{"AttributeName": "app", "AttributeType": "S"},
],
KeySchema=[
{"AttributeName": "client", "KeyType": "HASH"},
{"AttributeName": "app", "KeyType": "RANGE"},
],
ProvisionedThroughput={"ReadCapacityUnits": 123, "WriteCapacityUnits": 123},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="attribute_exists(#existing) AND attribute_not_exists(#nonexistent) AND #match = :match",
ExpressionAttributeNames={
"#existing": "existing",
"#nonexistent": "nope",
"#match": "match",
},
ExpressionAttributeValues={":match": {"S": "match"}},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="NOT(attribute_exists(#nonexistent1) AND attribute_exists(#nonexistent2))",
ExpressionAttributeNames={"#nonexistent1": "nope", "#nonexistent2": "nope2"},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="attribute_exists(#nonexistent) OR attribute_exists(#existing)",
ExpressionAttributeNames={"#nonexistent": "nope", "#existing": "existing"},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="#client BETWEEN :a AND :z",
ExpressionAttributeNames={"#client": "client"},
ExpressionAttributeValues={":a": {"S": "a"}, ":z": {"S": "z"}},
)
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="#client IN (:client1, :client2)",
ExpressionAttributeNames={"#client": "client"},
ExpressionAttributeValues={
":client1": {"S": "client1"},
":client2": {"S": "client2"},
},
)
with pytest.raises(client.exceptions.ConditionalCheckFailedException):
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="attribute_exists(#nonexistent1) AND attribute_exists(#nonexistent2)",
ExpressionAttributeNames={
"#nonexistent1": "nope",
"#nonexistent2": "nope2",
},
)
with pytest.raises(client.exceptions.ConditionalCheckFailedException):
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="NOT(attribute_not_exists(#nonexistent1) AND attribute_not_exists(#nonexistent2))",
ExpressionAttributeNames={
"#nonexistent1": "nope",
"#nonexistent2": "nope2",
},
)
with pytest.raises(client.exceptions.ConditionalCheckFailedException):
client.put_item(
TableName=table_name,
Item={
"client": {"S": "client1"},
"app": {"S": "app1"},
"match": {"S": "match"},
"existing": {"S": "existing"},
},
ConditionExpression="attribute_exists(#existing) AND attribute_not_exists(#nonexistent) AND #match = :match",
ExpressionAttributeNames={
"#existing": "existing",
"#nonexistent": "nope",
"#match": "match",
},
ExpressionAttributeValues={":match": {"S": "match2"}},
)
# Make sure update_item honors ConditionExpression as well
client.update_item(
TableName=table_name,
Key={"client": {"S": "client1"}, "app": {"S": "app1"}},
UpdateExpression="set #match=:match",
ConditionExpression="attribute_exists(#existing)",
ExpressionAttributeNames={"#existing": "existing", "#match": "match"},
ExpressionAttributeValues={":match": {"S": "match"}},
)
with pytest.raises(client.exceptions.ConditionalCheckFailedException) as exc:
client.update_item(
TableName=table_name,
Key={"client": {"S": "client1"}, "app": {"S": "app1"}},
UpdateExpression="set #match=:match",
ConditionExpression="attribute_not_exists(#existing)",
ExpressionAttributeValues={":match": {"S": "match"}},
ExpressionAttributeNames={"#existing": "existing", "#match": "match"},
)
_assert_conditional_check_failed_exception(exc)
with pytest.raises(client.exceptions.ConditionalCheckFailedException) as exc:
client.update_item(
TableName=table_name,
Key={"client": {"S": "client2"}, "app": {"S": "app1"}},
UpdateExpression="set #match=:match",
ConditionExpression="attribute_exists(#existing)",
ExpressionAttributeValues={":match": {"S": "match"}},
ExpressionAttributeNames={"#existing": "existing", "#match": "match"},
)
_assert_conditional_check_failed_exception(exc)
with pytest.raises(client.exceptions.ConditionalCheckFailedException):
client.delete_item(
TableName=table_name,
Key={"client": {"S": "client1"}, "app": {"S": "app1"}},
ConditionExpression="attribute_not_exists(#existing)",
ExpressionAttributeValues={":match": {"S": "match"}},
ExpressionAttributeNames={"#existing": "existing"},
)
def _assert_conditional_check_failed_exception(exc):
err = exc.value.response["Error"]
assert err["Code"] == "ConditionalCheckFailedException"
assert err["Message"] == "The conditional request failed"
@mock_aws
def test_condition_expression_numerical_attribute():
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
table = dynamodb.create_table(
TableName=f"T{uuid4()}",
KeySchema=[{"AttributeName": "partitionKey", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "partitionKey", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table.put_item(Item={"partitionKey": "pk-pos", "myAttr": 5})
table.put_item(Item={"partitionKey": "pk-neg", "myAttr": -5})
# try to update the item we put in the table using numerical condition expression
# Specifically, verify that we can compare with a zero-value
# First verify that > and >= work on positive numbers
update_numerical_con_expr(
key="pk-pos", con_expr="myAttr > :zero", res="6", table=table
)
update_numerical_con_expr(
key="pk-pos", con_expr="myAttr >= :zero", res="7", table=table
)
# Second verify that < and <= work on negative numbers
update_numerical_con_expr(
key="pk-neg", con_expr="myAttr < :zero", res="-4", table=table
)
update_numerical_con_expr(
key="pk-neg", con_expr="myAttr <= :zero", res="-3", table=table
)
def update_numerical_con_expr(key, con_expr, res, table):
table.update_item(
Key={"partitionKey": key},
UpdateExpression="ADD myAttr :one",
ExpressionAttributeValues={":zero": 0, ":one": 1},
ConditionExpression=con_expr,
)
assert table.get_item(Key={"partitionKey": key})["Item"]["myAttr"] == Decimal(res)
@mock_aws
def test_condition_expression__attr_doesnt_exist():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "forum_name", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "forum_name", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
client.put_item(
TableName=table_name, Item={"forum_name": {"S": "foo"}, "ttl": {"N": "4567.89"}}
)
def update_if_attr_doesnt_exist():
# Test nonexistent top-level attribute.
client.update_item(
TableName=table_name,
Key={"forum_name": {"S": "the-key"}},
UpdateExpression="set #new_state=:new_state, #ttl=:ttl",
ConditionExpression="attribute_not_exists(#new_state)",
ExpressionAttributeNames={"#new_state": "foobar", "#ttl": "ttl"},
ExpressionAttributeValues={
":new_state": {"S": "some-value"},
":ttl": {"N": "12345.67"},
},
ReturnValues="ALL_NEW",
)
update_if_attr_doesnt_exist()
# Second time should fail
with pytest.raises(client.exceptions.ConditionalCheckFailedException) as exc:
update_if_attr_doesnt_exist()
_assert_conditional_check_failed_exception(exc)
@mock_aws
def test_condition_expression__or_order():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "forum_name", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "forum_name", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
# ensure that the RHS of the OR expression is not evaluated if the LHS
# returns true (as it would result an error)
client.update_item(
TableName=table_name,
Key={"forum_name": {"S": "the-key"}},
UpdateExpression="set #ttl=:ttl",
ConditionExpression="attribute_not_exists(#ttl) OR #ttl <= :old_ttl",
ExpressionAttributeNames={"#ttl": "ttl"},
ExpressionAttributeValues={":ttl": {"N": "6"}, ":old_ttl": {"N": "5"}},
)
@mock_aws
def test_condition_expression__and_order():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "forum_name", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "forum_name", "AttributeType": "S"}],
ProvisionedThroughput={"ReadCapacityUnits": 1, "WriteCapacityUnits": 1},
)
# ensure that the RHS of the AND expression is not evaluated if the LHS
# returns true (as it would result an error)
with pytest.raises(client.exceptions.ConditionalCheckFailedException) as exc:
client.update_item(
TableName=table_name,
Key={"forum_name": {"S": "the-key"}},
UpdateExpression="set #ttl=:ttl",
ConditionExpression="attribute_exists(#ttl) AND #ttl <= :old_ttl",
ExpressionAttributeNames={"#ttl": "ttl"},
ExpressionAttributeValues={":ttl": {"N": "6"}, ":old_ttl": {"N": "5"}},
)
_assert_conditional_check_failed_exception(exc)
@mock_aws
def test_condition_expression_with_reserved_keyword_as_attr_name():
dynamodb = boto3.resource("dynamodb", region_name="us-east-2")
table_name = f"T{uuid4()}"
dynamodb.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table = dynamodb.Table(table_name)
email_like_str = "test@foo.com"
record = {"id": "key-0", "first": {email_like_str: {"end": {"VALUE"}}}}
table.put_item(Item=record)
expected_error_message = re.escape(
"An error occurred (ValidationException) when "
"calling the UpdateItem operation: Invalid ConditionExpression: Attribute name "
"is a reserved keyword; reserved keyword: end"
)
with pytest.raises(
dynamodb.meta.client.exceptions.ClientError, match=expected_error_message
):
table.update_item(
Key={"id": "key-0"},
UpdateExpression="REMOVE #first.#second, #other",
ExpressionAttributeNames={
"#first": "first",
"#second": email_like_str,
"#other": "other",
},
ExpressionAttributeValues={":value": "VALUE", ":one": 1},
ConditionExpression="size(#first.#second.end) = :one AND contains(#first.#second.end, :value)",
ReturnValues="ALL_NEW",
)
# table is unchanged
item = table.get_item(Key={"id": "key-0"})["Item"]
assert item == record
# using attribute names solves the issue
table.update_item(
Key={"id": "key-0"},
UpdateExpression="REMOVE #first.#second, #other",
ExpressionAttributeNames={
"#first": "first",
"#second": email_like_str,
"#other": "other",
"#end": "end",
},
ExpressionAttributeValues={":value": "VALUE", ":one": 1},
ConditionExpression="size(#first.#second.#end) = :one AND contains(#first.#second.#end, :value)",
ReturnValues="ALL_NEW",
)
item = table.get_item(Key={"id": "key-0"})["Item"]
assert item == {"id": "key-0", "first": {}}
@mock_aws
def test_condition_expression_parentheses_behavior():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
client.put_item(
TableName=table_name,
Item={
"pk": {"S": "pk"},
"a": {"N": "1"},
"b": {"N": "2"},
"c": {"N": "3"},
"e": {"N": "4"},
},
)
# Test Case 1: #a = :b OR (#c = :d AND #e = :f)
# AWS DDB allows this. Moto should too.
client.update_item(
TableName=table_name,
Key={"pk": {"S": "pk"}},
UpdateExpression="SET z = :z",
ConditionExpression="#a = :b OR (#c = :d AND #e = :f)",
ExpressionAttributeNames={"#a": "pk", "#c": "pk", "#e": "pk"},
ExpressionAttributeValues={
":b": {"S": "pk"},
":d": {"S": "pk"},
":f": {"S": "pk"},
":z": {"S": "updated1"},
},
)
# Test Case 2: (attribute_exists (#0)) AND (((#1 <> :0) AND (#1 <> :1)) AND (#2 = :3))
# AWS DDB allows this. Moto should too.
client.update_item(
TableName=table_name,
Key={"pk": {"S": "pk"}},
UpdateExpression="SET z = :z",
ConditionExpression="(attribute_exists (#0)) AND (((#1 <> :0) AND (#1 <> :1)) AND (#2 = :3))",
ExpressionAttributeNames={"#0": "pk", "#1": "pk", "#2": "pk"},
ExpressionAttributeValues={
":0": {"S": "nope"},
":1": {"S": "nope"},
":3": {"S": "pk"},
":z": {"S": "updated2"},
},
)
# Test Case 3: ((((a < b))))
# AWS DDB fails this. Moto should too.
with pytest.raises(ClientError) as exc:
client.update_item(
TableName=table_name,
Key={"pk": {"S": "pk"}},
UpdateExpression="SET z = :z",
ConditionExpression="((((a < b))))",
ExpressionAttributeValues={":z": {"S": "updated3"}},
)
err = exc.value.response["Error"]
assert err["Code"] == "ValidationException"
assert (
err["Message"]
== "Invalid ConditionExpression: The expression has redundant parentheses;"
)
# Test Case 4: ((#a = :b) OR (#c = :d) AND (#e = :f))
# AWS DDB allows this. Moto should too.
client.update_item(
TableName=table_name,
Key={"pk": {"S": "pk"}},
UpdateExpression="SET z = :z",
ConditionExpression="((#a = :b) OR (#c = :d) AND (#e = :f))",
ExpressionAttributeNames={"#a": "pk", "#c": "pk", "#e": "pk"},
ExpressionAttributeValues={
":b": {"S": "pk"},
":d": {"S": "pk"},
":f": {"S": "pk"},
":z": {"S": "updated4"},
},
)
@mock_aws
def test_condition_expression_allows_required_parentheses():
client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
client.put_item(
TableName=table_name,
Item={
"pk": {"S": "pk"},
"a": {"S": "match"},
"c": {"S": "match"},
"e": {"S": "match"},
},
)
client.update_item(
TableName=table_name,
Key={"pk": {"S": "pk"}},
UpdateExpression="SET #z = :z",
ConditionExpression="#a = :b AND (#c = :d OR #e = :f)",
ExpressionAttributeNames={"#a": "a", "#c": "c", "#e": "e", "#z": "z"},
ExpressionAttributeValues={
":b": {"S": "match"},
":d": {"S": "match"},
":f": {"S": "nope"},
":z": {"S": "updated"},
},
)
item = client.get_item(TableName=table_name, Key={"pk": {"S": "pk"}})["Item"]
assert item["z"] == {"S": "updated"}
@mock_aws
def test_condition_check_failure_exception_is_raised_when_values_are_returned_for_an_item_with_a_top_level_list():
# This explicitly tests for a failure in handling JSONification of DynamoType
# when lists are at the top level of an item.
# This exception should not be raised:
# TypeError: Object of type DynamoType is not JSON serializable
dynamodb_client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
dynamodb_client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
],
BillingMode="PAY_PER_REQUEST",
)
record = {
"id": {"S": "example_id"},
"some_list": {"L": [{"M": {"hello": {"S": "h"}}}]},
}
dynamodb_client.put_item(
TableName=table_name,
Item=record,
)
with pytest.raises(ClientError) as error:
dynamodb_client.update_item(
TableName=table_name,
Key={"id": {"S": "example_id"}},
UpdateExpression="set some_list=list_append(some_list, :w)",
ExpressionAttributeValues={
":w": {"L": [{"M": {"world": {"S": "w"}}}]},
":id": {"S": "incorrect id"},
},
ConditionExpression="id = :id",
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
assert error.type.__name__ == "ConditionalCheckFailedException"
assert error.value.response["Error"] == {
"Message": "The conditional request failed",
"Code": "ConditionalCheckFailedException",
}
assert error.value.response["Item"] == {
"id": {"S": "example_id"},
"some_list": {"L": [{"M": {"hello": {"S": "h"}}}]},
}
@mock_aws
def test_condition_check_failure_exception_is_raised_when_values_are_returned_for_an_item_with_a_top_level_string_set():
# This explicitly tests for a failure in handling JSONification of DynamoType
# when string sets are at the top level of an item.
# These exception should not be raised:
# TypeError: Object of type DynamoType is not JSON serializable
# AttributeError: 'str' object has no attribute 'to_regular_json'
dynamodb_client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
dynamodb_client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
],
BillingMode="PAY_PER_REQUEST",
)
record = {
"id": {"S": "example_id"},
"some_list": {"SS": ["hello"]},
}
dynamodb_client.put_item(
TableName=table_name,
Item=record,
)
with pytest.raises(ClientError) as error:
dynamodb_client.update_item(
TableName=table_name,
Key={"id": {"S": "example_id"}},
UpdateExpression="set some_list=list_append(some_list, :w)",
ExpressionAttributeValues={
":w": {"SS": ["world"]},
":id": {"S": "incorrect id"},
},
ConditionExpression="id = :id",
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
assert error.type.__name__ == "ConditionalCheckFailedException"
assert error.value.response["Error"] == {
"Message": "The conditional request failed",
"Code": "ConditionalCheckFailedException",
}
assert error.value.response["Item"] == {
"id": {"S": "example_id"},
"some_list": {"SS": ["hello"]},
}
@mock_aws
def test_condition_check_failure_exception_is_raised_when_values_are_returned_for_an_item_with_a_list_in_a_map():
# This explicitly tests for a failure in handling JSONification of DynamoType
# when lists are inside a map
dynamodb_client = boto3.client("dynamodb", region_name="us-east-1")
table_name = f"T{uuid4()}"
dynamodb_client.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[
{"AttributeName": "id", "AttributeType": "S"},
],
BillingMode="PAY_PER_REQUEST",
)
record = {
"id": {"S": "example_id"},
"some_list_in_a_map": {
"M": {"some_list": {"L": [{"M": {"hello": {"S": "h"}}}]}}
},
}
dynamodb_client.put_item(TableName=table_name, Item=record)
with pytest.raises(ClientError) as error:
dynamodb_client.update_item(
TableName=table_name,
Key={"id": {"S": "example_id"}},
UpdateExpression="set some_list_in_a_map.some_list=list_append(some_list_in_a_map.some_list, :w)",
ExpressionAttributeValues={
":w": {"L": [{"M": {"world": {"S": "w"}}}]},
":id": {"S": "incorrect id"},
},
ConditionExpression="id = :id",
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
assert error.type.__name__ == "ConditionalCheckFailedException"
assert error.value.response["Error"] == {
"Message": "The conditional request failed",
"Code": "ConditionalCheckFailedException",
}
assert error.value.response["Item"] == {
"id": {"S": "example_id"},
"some_list_in_a_map": {
"M": {"some_list": {"L": [{"M": {"hello": {"S": "h"}}}]}}
},
}
@mock_aws
def test_conditional_check_failed_bytes():
dynamodb = boto3.client("dynamodb", region_name="us-east-1")
dynamodb.create_table(
TableName="test_table_bytes",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
dynamodb.put_item(
TableName="test_table_bytes",
Item={
"pk": {"S": "test"},
"my_bytes": {"B": b"somebytes"},
"my_bytes_set": {"BS": [b"byte1", b"byte2"]},
},
)
with pytest.raises(ClientError) as exc:
dynamodb.update_item(
TableName="test_table_bytes",
Key={"pk": {"S": "test"}},
UpdateExpression="SET my_str = :s",
ConditionExpression="attribute_not_exists(pk)",
ExpressionAttributeValues={":s": {"S": "newstr"}},
ReturnValuesOnConditionCheckFailure="ALL_OLD",
)
assert exc.value.response["Error"]["Code"] == "ConditionalCheckFailedException"
assert "Item" in exc.value.response
assert exc.value.response["Item"]["my_bytes"]["B"] == b"somebytes"
assert exc.value.response["Item"]["my_bytes_set"]["BS"] == [b"byte1", b"byte2"]
@mock_aws
def test_between_condition_includes_zero():
"""
A numeric attribute value of exactly 0 must satisfy a BETWEEN range that
includes it; previously FuncBetween tested the attribute with bare
truthiness, so Decimal("0") was treated as missing and excluded.
"""
dynamodb = boto3.resource("dynamodb", region_name="us-east-2")
table_name = f"T{uuid4()}"
dynamodb.create_table(
TableName=table_name,
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
table = dynamodb.Table(table_name)
table.put_item(Item={"id": "zero", "price": 0})
table.put_item(Item={"id": "five", "price": 5})
result = table.scan(
FilterExpression="price BETWEEN :lo AND :hi",
ExpressionAttributeValues={":lo": 0, ":hi": 100},
)
assert {item["id"] for item in result["Items"]} == {"zero", "five"}
result = table.scan(
FilterExpression="price BETWEEN :lo AND :hi",
ExpressionAttributeValues={":lo": -10, ":hi": 0},
)
assert {item["id"] for item in result["Items"]} == {"zero"}