Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Fixes to dynamodb validation inconsistencies (#1041)
chincharjuin81508be1ecee
diff --git a/ministack/services/dynamodb.py b/ministack/services/dynamodb.pyindex 348beac0..477922ea 100644--- a/ministack/services/dynamodb.py+++ b/ministack/services/dynamodb.py@@ -280,7 +280,7 @@ def _validate_attribute_value(attr_name: str, value: dict) -> tuple | None:return error_response_json("ValidationException",f"One or more parameter values were invalid: Input collection [{', '.join(str(v) for v in vval)}] contains duplicates.", 400)for s in vval:- if not isinstance(s, str) or s == "":+ if not isinstance(s, str):return error_response_json("ValidationException","One or more parameter values were invalid: An string set may not be empty", 400)elif vtype == "NS":@@ -1577,9 +1577,10 @@ def _update_item(data):return error_response_json("ValidationException",f"One or more parameter values were invalid: Cannot update attribute {_kn}. This attribute is part of the key", 400)+ updated_attrs = set()if update_expr:try:- item = _apply_update_expression(item, update_expr, eav, ean)+ item, updated_attrs = _apply_update_expression(item, update_expr, eav, ean)except ValueError as exc:return error_response_json("ValidationException", str(exc), 400)elif attribute_updates:@@ -1587,6 +1588,7 @@ def _update_item(data):item = _apply_attribute_updates(item, attribute_updates)except _AttributeUpdatesValidationError as exc:return error_response_json("ValidationException", str(exc), 400)+ updated_attrs = set(attribute_updates.keys())# AWS rejects any update that would mutate a hash or range key value.for key_name in (table.get("pk_name"), table.get("sk_name")):if key_name and key_name in item and existing is not None:@@ -1594,6 +1596,11 @@ def _update_item(data):return error_response_json("ValidationException",f"One or more parameter values were invalid: Cannot update attribute {key_name}. This attribute is part of the key", 400)+ # AWS rejects updates with invalid values+ err = _validate_item(item, table.get("pk_name"), table.get("sk_name"))+ if err:+ return err+table["items"][pk_val][sk_val] = item_update_counts(table)@@ -1607,11 +1614,11 @@ def _update_item(data):elif rv == "ALL_OLD" and old_item:result["Attributes"] = old_itemelif rv == "UPDATED_OLD" and old_item:- result["Attributes"] = _diff_attributes(old_item, item, return_old=True)+ result["Attributes"] = _diff_attributes(old_item, item, updated_attrs, return_old=True)elif rv == "UPDATED_NEW":# AWS omits Attributes from the response when the only operation was# REMOVE — there are no "new" values to return.- new_attrs = _diff_attributes(old_item or {}, item, return_old=False)+ new_attrs = _diff_attributes(old_item or {}, item, updated_attrs, return_old=False)if new_attrs:result["Attributes"] = new_attrs_add_consumed_capacity(result, data, name, write=True)@@ -2884,7 +2891,7 @@ def _transact_write_items(data):item = copy.deepcopy(old_item) if old_item else dict(key)ue = op.get("UpdateExpression", "")if ue:- item = _apply_update_expression(item, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))+ item, _ = _apply_update_expression(item, ue, op.get("ExpressionAttributeValues", {}), op.get("ExpressionAttributeNames", {}))tbl["items"][pk_val][sk_val] = item_emit_stream_event(table_name, "MODIFY" if old_item else "INSERT", old_item, item)_update_counts(tbl)@@ -4502,18 +4509,20 @@ def _apply_update_expression(item, expr, attr_values, attr_names):if current_clause is not None:clauses[current_clause] = current_tokens+ updated_attrs = set()+if 'SET' in clauses:- _apply_set(item, clauses['SET'], attr_values, attr_names)+ _apply_set(item, clauses['SET'], attr_values, attr_names, updated_attrs)if 'REMOVE' in clauses:- _apply_remove(item, clauses['REMOVE'], attr_names)+ _apply_remove(item, clauses['REMOVE'], attr_names, updated_attrs)if 'ADD' in clauses:- _apply_add(item, clauses['ADD'], attr_values, attr_names)+ _apply_add(item, clauses['ADD'], attr_values, attr_names, updated_attrs)if 'DELETE' in clauses:- _apply_delete(item, clauses['DELETE'], attr_values, attr_names)- return item+ _apply_delete(item, clauses['DELETE'], attr_values, attr_names, updated_attrs)+ return item, updated_attrs-def _apply_set(item, tokens, attr_values, attr_names):+def _apply_set(item, tokens, attr_values, attr_names, updated_attrs):# AWS semantics: all RHS references resolve against the pre-update snapshot# of the item. Resolve every value first, then apply assignments — so# `SET a = b, b = :v` sets `a` to the OLD value of `b`.@@ -4538,6 +4547,7 @@ def _apply_set(item, tokens, attr_values, attr_names):f"The document path provided in the update expression is invalid for update: {'.'.join(str(p) for p in path_parts[:-1])}")pending.append((path_parts, value))+ updated_attrs.add(path_parts[0])for path_parts, value in pending:_set_at_path(item, path_parts, value)@@ -4619,14 +4629,15 @@ def _eval_set_value(tokens, item, attr_values, attr_names):return None-def _apply_remove(item, tokens, attr_names):+def _apply_remove(item, tokens, attr_names, updated_attrs):for path_tokens in _split_by_comma(tokens):path = _parse_path_from_tokens(path_tokens, attr_names)if path:+ updated_attrs.add(path[0])_remove_at_path(item, path)-def _apply_add(item, tokens, attr_values, attr_names):+def _apply_add(item, tokens, attr_values, attr_names, updated_attrs):for part in _split_by_comma(tokens):val_idx = Nonefor i in range(len(part) - 1, -1, -1):@@ -4640,6 +4651,8 @@ def _apply_add(item, tokens, attr_values, attr_names):if not path or add_val is None:continue+ updated_attrs.add(path[0])+existing = _get_at_path(item, path)if "N" in add_val:@@ -4657,7 +4670,7 @@ def _apply_add(item, tokens, attr_values, attr_names):_set_at_path(item, path, {"BS": sorted(cur | set(add_val["BS"]))})-def _apply_delete(item, tokens, attr_values, attr_names):+def _apply_delete(item, tokens, attr_values, attr_names, updated_attrs):for part in _split_by_comma(tokens):val_idx = Nonefor i in range(len(part) - 1, -1, -1):@@ -4671,6 +4684,8 @@ def _apply_delete(item, tokens, attr_values, attr_names):if not path or del_val is None:continue+ updated_attrs.add(path[0])+existing = _get_at_path(item, path)if existing is None:continue@@ -5591,28 +5606,25 @@ def _extract_key_from_item(table, item):return key-def _diff_attributes(old_item, new_item, return_old=True):- """Return only the attributes that changed.+def _diff_attributes(old_item, new_item, updated_attrs, return_old=True):+ """Return the old or new version of attributes that were updated.- - UPDATED_OLD: report the prior value of each attribute that was modified- or removed (omit additions, since there is no prior value).- - UPDATED_NEW: report the new value of each attribute that was created or- modified (omit removals, since there is no new value to report — per- AWS, REMOVE-only updates with UPDATED_NEW omit Attributes entirely).+ - UPDATED_OLD: report the prior value of each updated attribute, omitting+ additions where there was no prior value.+ - UPDATED_NEW: report the new value of each updated attribute, omitting+ removals where there is no new value (per AWS, REMOVE-only updates with+ UPDATED_NEW omit Attributes entirely)."""result = {}- all_keys = set(list(old_item.keys()) + list(new_item.keys()))- for k in all_keys:- ov = old_item.get(k)- nv = new_item.get(k)- if ov == nv:- continue+ for k in updated_attrs:if return_old:- if ov is not None:- result[k] = ov+ v = old_item.get(k)+ if v is not None:+ result[k] = velse:- if nv is not None:- result[k] = nv+ v = new_item.get(k)+ if v is not None:+ result[k] = vreturn resultdiff --git a/tests/test_dynamodb.py b/tests/test_dynamodb.pyindex 456db9e9..fe594de8 100644--- a/tests/test_dynamodb.py+++ b/tests/test_dynamodb.py@@ -1237,6 +1237,150 @@ def test_dynamodb_update_item_updated_old(ddb):)assert resp["Attributes"]["score"]["N"] == "10"++def test_dynamodb_update_set_same_value_returned(ddb):+ """SET that assigns the same value is still reported in UPDATED_NEW/OLD."""+ name = "u-set-same-rv"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "a": {"S": "old"}})+ r_new = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET a = :v",+ ExpressionAttributeValues={":v": {"S": "old"}},+ ReturnValues="UPDATED_NEW",+ )+ assert r_new["Attributes"] == {"a": {"S": "old"}}++ r_old = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET a = :v",+ ExpressionAttributeValues={":v": {"S": "old"}},+ ReturnValues="UPDATED_OLD",+ )+ assert r_old["Attributes"] == {"a": {"S": "old"}}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_remove_return_values(ddb):+ """REMOVE omits the attribute in UPDATED_NEW and returns the old value in UPDATED_OLD."""+ name = "u-remove-rv"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "x": {"S": "X"}})+ r_new = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="REMOVE x",+ ReturnValues="UPDATED_NEW",+ )+ assert "Attributes" not in r_new++ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "x": {"S": "X"}})+ r_old = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="REMOVE x",+ ReturnValues="UPDATED_OLD",+ )+ assert r_old["Attributes"] == {"x": {"S": "X"}}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_add_number_return_values(ddb):+ """ADD on a number returns new and old values for the updated attribute."""+ name = "u-add-num-rv"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "n": {"N": "5"}})+ r_new = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD n :v",+ ExpressionAttributeValues={":v": {"N": "3"}},+ ReturnValues="UPDATED_NEW",+ )+ assert r_new["Attributes"] == {"n": {"N": "8"}}++ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "n": {"N": "5"}})+ r_old = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD n :v",+ ExpressionAttributeValues={":v": {"N": "3"}},+ ReturnValues="UPDATED_OLD",+ )+ assert r_old["Attributes"] == {"n": {"N": "5"}}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_add_set_return_values(ddb):+ """ADD on a string set returns the updated set in UPDATED_NEW/OLD."""+ name = "u-add-ss-rv"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["a"]}})+ r_new = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :v",+ ExpressionAttributeValues={":v": {"SS": ["b"]}},+ ReturnValues="UPDATED_NEW",+ )+ assert sorted(r_new["Attributes"]["tags"]["SS"]) == ["a", "b"]++ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["a"]}})+ r_old = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :v",+ ExpressionAttributeValues={":v": {"SS": ["b"]}},+ ReturnValues="UPDATED_OLD",+ )+ assert r_old["Attributes"] == {"tags": {"SS": ["a"]}}+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_combined_return_values_only_touched(ddb):+ """Combined SET/REMOVE only returns touched attributes; untouched attrs are excluded."""+ name = "u-combo-rv"+ _basic_table(ddb, name)+ try:+ ddb.put_item(+ TableName=name,+ Item={"pk": {"S": "k"}, "a": {"S": "old"}, "b": {"S": "keep"}, "x": {"S": "gone"}},+ )+ r_new = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET a = :v REMOVE x",+ ExpressionAttributeValues={":v": {"S": "new"}},+ ReturnValues="UPDATED_NEW",+ )+ assert r_new["Attributes"] == {"a": {"S": "new"}}++ ddb.put_item(+ TableName=name,+ Item={"pk": {"S": "k"}, "a": {"S": "old"}, "b": {"S": "keep"}, "x": {"S": "gone"}},+ )+ r_old = ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET a = :v REMOVE x",+ ExpressionAttributeValues={":v": {"S": "new"}},+ ReturnValues="UPDATED_OLD",+ )+ assert r_old["Attributes"] == {"a": {"S": "old"}, "x": {"S": "gone"}}+ finally:+ ddb.delete_table(TableName=name)++def test_dynamodb_conditional_put_fails(ddb):"""PutItem with attribute_not_exists condition fails if item already exists."""ddb.create_table(@@ -3106,6 +3250,29 @@ def test_dynamodb_duplicate_ss_values_rejected(ddb):ddb.delete_table(TableName=name)+def test_dynamodb_string_set_with_empty_string_accepted(ddb):+ """A string set containing an empty string must be valid (regression)."""+ name = "ss-empty-str"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": [""]}})+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["tags"]["SS"] == [""]+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_string_set_with_empty_string_and_values_accepted(ddb):+ """A string set containing an empty string alongside other values must be valid."""+ name = "ss-empty-str-mix"+ _basic_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["", "a"]}})+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert sorted(item["tags"]["SS"]) == ["", "a"]+ finally:+ ddb.delete_table(TableName=name)+def test_dynamodb_empty_string_hash_key_rejected(ddb):name = "empty-pk"_basic_table(ddb, name)@@ -5298,33 +5465,270 @@ def test_export_returns_in_progress_then_completed(ddb, s3):pass-def test_import_returns_in_progress_then_completed(ddb, s3):- bucket = f"imp-bucket-{_uuid_mod.uuid4().hex[:8]}"- s3.create_bucket(Bucket=bucket)- tname = f"imp-in-progress-{_uuid_mod.uuid4().hex[:8]}"- try:- resp = ddb.import_table(- S3BucketSource={"S3Bucket": bucket},- InputFormat="DYNAMODB_JSON",- TableCreationParameters={- "TableName": tname,- "KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],- "AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],- "BillingMode": "PAY_PER_REQUEST",- },+# ---------------------------------------------------------------------------+# UpdateItem regression tests — _validate_item enforcement+# ---------------------------------------------------------------------------+# Before the fix, _update_item did not call _validate_item on the resulting+# item, so invalid values (malformed numbers, empty sets, oversized items, ...)+# could be persisted. The tests below exercise the validation path now that it+# is enforced.+++def _create_update_item_table(ddb, name):+ try:+ ddb.delete_table(TableName=name)+ except Exception:+ pass+ ddb.create_table(+ TableName=name,+ KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],+ AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],+ BillingMode="PAY_PER_REQUEST",+ )+++def test_dynamodb_update_item_rejects_malformed_number(ddb):+ """SET with a non-numeric string in a Number value must be rejected."""+ name = "upd-malformed-number"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET num = :v",+ "ExpressionAttributeValues": {":v": {"N": "1.2.3"}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ # The item must not have been modified.+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}}).get("Item", {})+ assert "num" not in item+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_number_out_of_range(ddb):+ """Numbers with magnitude beyond the DynamoDB limits must be rejected."""+ name = "upd-number-range"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET num = :v",+ "ExpressionAttributeValues": {":v": {"N": "1E+130"}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_empty_string_set(ddb):+ """SET with an empty SS value must be rejected."""+ name = "upd-empty-ss"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET tags = :v",+ "ExpressionAttributeValues": {":v": {"SS": []}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_duplicate_set_elements(ddb):+ """SET with duplicate elements in a string set must be rejected."""+ name = "upd-dup-ss"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET tags = :v",+ "ExpressionAttributeValues": {":v": {"SS": ["a", "a"]}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ # The item must not have been modified.+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}}).get("Item", {})+ assert "tags" not in item+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_accepts_string_set_with_empty_string(ddb):+ """SET with a string set containing an empty string must succeed (regression)."""+ name = "upd-ss-empty-str"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET tags = :v",+ ExpressionAttributeValues={":v": {"SS": [""]}},)- import_arn = resp["ImportTableDescription"]["ImportArn"]- assert resp["ImportTableDescription"]["ImportStatus"] == "IN_PROGRESS"+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["tags"]["SS"] == [""]+ finally:+ ddb.delete_table(TableName=name)- first = ddb.describe_import(ImportArn=import_arn)["ImportTableDescription"]- assert first["ImportStatus"] == "IN_PROGRESS"- time.sleep(1.2)- later = ddb.describe_import(ImportArn=import_arn)["ImportTableDescription"]- assert later["ImportStatus"] == "COMPLETED"- assert "EndTime" in later+def test_dynamodb_update_item_adds_empty_string_to_string_set(ddb):+ """ADD of an empty string to an existing string set must succeed."""+ name = "upd-add-ss-empty-str"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "tags": {"SS": ["a"]}})+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="ADD tags :v",+ ExpressionAttributeValues={":v": {"SS": [""]}},+ )+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert sorted(item["tags"]["SS"]) == ["", "a"]finally:- try:- ddb.delete_table(TableName=tname)- except Exception:- pass+ ddb.delete_table(TableName=name)++++def test_dynamodb_update_item_rejects_multi_datatype_attr_value(ddb):+ """An AttributeValue declaring more than one datatype must be rejected."""+ name = "upd-multi-dt"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET x = :v",+ "ExpressionAttributeValues": {":v": {"S": "hello", "N": "42"}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_oversized_item(ddb):+ """An update producing an item larger than 400KB must be rejected."""+ name = "upd-oversized"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}, "small": {"S": "x"}})+ big = "a" * (400 * 1024 + 100)+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET data = :v REMOVE small",+ "ExpressionAttributeValues": {":v": {"S": big}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item.get("small") == {"S": "x"}+ assert "data" not in item+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_empty_number_set(ddb):+ """SET with an empty NS value must be rejected."""+ name = "upd-empty-ns"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET nums = :v",+ "ExpressionAttributeValues": {":v": {"NS": []}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_invalid_number_set(ddb):+ """SET with an NS containing an invalid number must be rejected."""+ name = "upd-invalid-ns"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET nums = :v",+ "ExpressionAttributeValues": {":v": {"NS": ["1", "not-a-number"]}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_rejects_empty_binary_set(ddb):+ """SET with an empty BS value must be rejected."""+ name = "upd-empty-bs"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ code, body = _raw_ddb("UpdateItem", {+ "TableName": name,+ "Key": {"pk": {"S": "k"}},+ "UpdateExpression": "SET blobs = :v",+ "ExpressionAttributeValues": {":v": {"BS": []}},+ })+ assert code == 400+ assert "ValidationException" in body.get("__type", "")+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_attribute_updates_rejects_invalid_value(ddb):+ """Legacy AttributeUpdates path must also validate the resulting item."""+ name = "upd-attr-upd-invalid"+ _create_update_item_table(ddb, name)+ try:+ ddb.put_item(TableName=name, Item={"pk": {"S": "k"}})+ with pytest.raises(ClientError) as exc_info:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ AttributeUpdates={"num": {"Action": "PUT", "Value": {"N": "1.2.3"}}},+ )+ assert exc_info.value.response["Error"]["Code"] == "ValidationException"+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}}).get("Item", {})+ assert "num" not in item+ finally:+ ddb.delete_table(TableName=name)+++def test_dynamodb_update_item_valid_update_still_succeeds(ddb):+ """Sanity check: valid UpdateItem operations continue to work."""+ name = "upd-valid"+ _create_update_item_table(ddb, name)+ try:+ ddb.update_item(+ TableName=name,+ Key={"pk": {"S": "k"}},+ UpdateExpression="SET num = :n, tags = :t",+ ExpressionAttributeValues={":n": {"N": "42"}, ":t": {"SS": ["a", "b"]}},+ )+ item = ddb.get_item(TableName=name, Key={"pk": {"S": "k"}})["Item"]+ assert item["num"] == {"N": "42"}+ assert sorted(item["tags"]["SS"]) == ["a", "b"]+ finally:+ ddb.delete_table(TableName=name)+