File: test_dynamodb_validation.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (475 lines) | stat: -rw-r--r-- 16,827 bytes parent folder | download
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
import pytest

from moto.dynamodb.exceptions import (
    AttributeDoesNotExist,
    AttributeIsReservedKeyword,
    ExpressionAttributeNameNotDefined,
    ExpressionAttributeValueNotDefined,
    IncorrectOperandType,
    InvalidUpdateExpressionInvalidDocumentPath,
)
from moto.dynamodb.models import DynamoType, Item
from moto.dynamodb.parsing.ast_nodes import (
    DDBTypedValue,
    NodeDepthLeftTypeFetcher,
    UpdateExpressionSetAction,
)
from moto.dynamodb.parsing.expressions import UpdateExpressionParser
from moto.dynamodb.parsing.validators import UpdateExpressionValidator


def test_valid_update_expression(table):
    update_expression = "set forum_desc=:Desc, forum_type=:NewType"
    update_expression_values = {
        ":Desc": {"S": "AmazingForum"},
        ":NewType": {"S": "BASIC"},
    }
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "forum_name"}),
        range_key=DynamoType({"S": "forum_type"}),
        attrs={"forum_name": {"S": "hello"}},
    )
    UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=update_expression_values,
        item=item,
        table=table,
    ).validate()


def test_validation_of_update_expression_with_keyword(table):
    try:
        update_expression = "SET myNum = path + :val"
        update_expression_values = {":val": {"N": "3"}}
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "path": {"N": "3"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values=update_expression_values,
            item=item,
            table=table,
        ).validate()
        raise AssertionError("No exception raised")
    except AttributeIsReservedKeyword as e:
        assert e.keyword == "path"


@pytest.mark.parametrize(
    "update_expression", ["SET a = #b + :val2", "SET a = :val2 + #b"]
)
def test_validation_of_a_set_statement_with_incorrect_passed_value(
    update_expression, table
):
    """
    By running permutations it shows that values are replaced prior to resolving attributes.

    An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
    An expression attribute value used in expression is not defined; attribute value: :val2
    """
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "b": {"N": "3"}},
    )
    try:
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names={"#b": "ok"},
            expression_attribute_values={":val": {"N": "3"}},
            item=item,
            table=table,
        ).validate()
    except ExpressionAttributeValueNotDefined as e:
        assert e.attribute_value == ":val2"


def test_validation_of_update_expression_with_attribute_that_does_not_exist_in_item(
    table,
):
    """
    When an update expression tries to get an attribute that does not exist it must throw the appropriate exception.

    An error occurred (ValidationException) when calling the UpdateItem operation:
    The provided expression refers to an attribute that does not exist in the item
    """
    try:
        update_expression = "SET a = nonexistent"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "path": {"N": "3"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values=None,
            item=item,
            table=table,
        ).validate()
        raise AssertionError("No exception raised")
    except AttributeDoesNotExist:
        assert True


@pytest.mark.parametrize("update_expression", ["SET a = #c", "SET a = #c + #d"])
def test_validation_of_update_expression_with_attribute_name_that_is_not_defined(
    update_expression, table
):
    """
    When an update expression tries to get an attribute name that is not provided it must throw an exception.

    An error occurred (ValidationException) when calling the UpdateItem operation: Invalid UpdateExpression:
    An expression attribute name used in the document path is not defined; attribute name: #c
    """
    try:
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "path": {"N": "3"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names={"#b": "ok"},
            expression_attribute_values=None,
            item=item,
            table=table,
        ).validate()
        raise AssertionError("No exception raised")
    except ExpressionAttributeNameNotDefined as e:
        assert e.not_defined_attribute_name == "#c"


def test_validation_of_if_not_exists_not_existing_invalid_replace_value(table):
    try:
        update_expression = "SET a = if_not_exists(b, a.c)"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "a": {"S": "A"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values=None,
            item=item,
            table=table,
        ).validate()
        raise AssertionError("No exception raised")
    except AttributeDoesNotExist:
        assert True


def get_first_node_of_type(ast, node_type):
    return next(NodeDepthLeftTypeFetcher(node_type, ast))


def get_set_action_value(ast):
    """
    Helper that takes an AST and gets the first UpdateExpressionSetAction and retrieves the value of that action.
    This should only be called on validated expressions.
    Args:
        ast(Node):

    Returns:
        DynamoType: The DynamoType object representing the Dynamo value.
    """
    set_action = get_first_node_of_type(ast, UpdateExpressionSetAction)
    typed_value = set_action.children[1]
    assert isinstance(typed_value, DDBTypedValue)
    dynamo_value = typed_value.children[0]
    assert isinstance(dynamo_value, DynamoType)
    return dynamo_value


def test_validation_of_if_not_exists_not_existing_value(table):
    update_expression = "SET a = if_not_exists(b, a)"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "a": {"S": "A"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=None,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"S": "A"})


def test_validation_of_if_not_exists_with_existing_attribute_should_return_attribute(
    table,
):
    update_expression = "SET a = if_not_exists(b, a)"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "a": {"S": "A"}, "b": {"S": "B"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=None,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"S": "B"})


def test_validation_of_if_not_exists_with_existing_attribute_should_return_value(table):
    update_expression = "SET a = if_not_exists(b, :val)"
    update_expression_values = {":val": {"N": "4"}}
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "b": {"N": "3"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=update_expression_values,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"N": "3"})


def test_validation_of_if_not_exists_with_non_existing_attribute_should_return_value(
    table,
):
    update_expression = "SET a = if_not_exists(b, :val)"
    update_expression_values = {":val": {"N": "4"}}
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}), range_key=None, attrs={"id": {"S": "1"}}
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=update_expression_values,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"N": "4"})


def test_validation_of_sum_operation(table):
    update_expression = "SET a = a + b"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "a": {"N": "3"}, "b": {"N": "4"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=None,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"N": "7"})


def test_validation_homogeneous_list_append_function(table):
    update_expression = "SET ri = list_append(ri, :vals)"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "ri": {"L": [{"S": "i1"}, {"S": "i2"}]}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values={":vals": {"L": [{"S": "i3"}, {"S": "i4"}]}},
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType(
        {"L": [{"S": "i1"}, {"S": "i2"}, {"S": "i3"}, {"S": "i4"}]}
    )


def test_validation_hetereogenous_list_append_function(table):
    update_expression = "SET ri = list_append(ri, :vals)"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "ri": {"L": [{"S": "i1"}, {"S": "i2"}]}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values={":vals": {"L": [{"N": "3"}]}},
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"L": [{"S": "i1"}, {"S": "i2"}, {"N": "3"}]})


def test_validation_list_append_function_with_non_list_arg(table):
    """
    Must error out:
    Invalid UpdateExpression: Incorrect operand type for operator or function;
     operator or function: list_append, operand type: S'
    Returns:

    """
    try:
        update_expression = "SET ri = list_append(ri, :vals)"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "ri": {"L": [{"S": "i1"}, {"S": "i2"}]}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values={":vals": {"S": "N"}},
            item=item,
            table=table,
        ).validate()
    except IncorrectOperandType as e:
        assert e.operand_type == "S"
        assert e.operator_or_function == "list_append"


def test_sum_with_incompatible_types(table):
    """
    Must error out:
    Invalid UpdateExpression: Incorrect operand type for operator or function; operator or function: +, operand type: S'
    Returns:

    """
    try:
        update_expression = "SET ri = :val + :val2"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "1"}, "ri": {"L": [{"S": "i1"}, {"S": "i2"}]}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values={":val": {"S": "N"}, ":val2": {"N": "3"}},
            item=item,
            table=table,
        ).validate()
    except IncorrectOperandType as e:
        assert e.operand_type == "S"
        assert e.operator_or_function == "+"


def test_validation_of_subraction_operation(table):
    update_expression = "SET ri = :val - :val2"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "1"}, "a": {"N": "3"}, "b": {"N": "4"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values={":val": {"N": "1"}, ":val2": {"N": "3"}},
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"N": "-2"})


def test_cannot_index_into_a_string(table):
    """
    Must error out:
    The document path provided in the update expression is invalid for update'
    """
    try:
        update_expression = "set itemstr[1]=:Item"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "foo2"}, "itemstr": {"S": "somestring"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values={":Item": {"S": "string_update"}},
            item=item,
            table=table,
        ).validate()
        raise AssertionError("Must raise exception")
    except InvalidUpdateExpressionInvalidDocumentPath:
        assert True


def test_validation_set_path_does_not_need_to_be_resolvable_when_setting_a_new_attribute(
    table,
):
    """If this step just passes we are happy enough"""
    update_expression = "set d=a"
    update_expression_ast = UpdateExpressionParser.make(update_expression)
    item = Item(
        hash_key=DynamoType({"S": "id"}),
        range_key=None,
        attrs={"id": {"S": "foo2"}, "a": {"N": "3"}},
    )
    validated_ast = UpdateExpressionValidator(
        update_expression_ast,
        expression_attribute_names=None,
        expression_attribute_values=None,
        item=item,
        table=table,
    ).validate()
    dynamo_value = get_set_action_value(validated_ast)
    assert dynamo_value == DynamoType({"N": "3"})


def test_validation_set_path_does_not_need_to_be_resolvable_but_must_be_creatable_when_setting_a_new_attribute(
    table,
):
    try:
        update_expression = "set d.e=a"
        update_expression_ast = UpdateExpressionParser.make(update_expression)
        item = Item(
            hash_key=DynamoType({"S": "id"}),
            range_key=None,
            attrs={"id": {"S": "foo2"}, "a": {"N": "3"}},
        )
        UpdateExpressionValidator(
            update_expression_ast,
            expression_attribute_names=None,
            expression_attribute_values=None,
            item=item,
            table=table,
        ).validate()
        raise AssertionError("Must raise exception")
    except InvalidUpdateExpressionInvalidDocumentPath:
        assert True