Skip to content

Drop a value rejected by @validates from valid_data when the field has an attribute - #3088

Open
andrewstellman wants to merge 2 commits into
marshmallow-code:devfrom
andrewstellman:validates-attribute-valid-data
Open

andrewstellman wants to merge 2 commits into
marshmallow-code:devfrom
andrewstellman:validates-attribute-valid-data

Conversation

@andrewstellman

Copy link
Copy Markdown

When a @validates method rejects the value of a field that has attribute set, the rejected value stays in ValidationError.valid_data:

class S(Schema):
    name = fields.Str(attribute="n")
    age = fields.Int()

    @validates("name")
    def validate_name(self, value, **kwargs):
        raise ValidationError("Invalid value.")

S().load({"name": "x", "age": 1})
# ValidationError; valid_data == {"n": "x", "age": 1}, expected {"age": 1}

_invoke_field_validators popped the rejected value by field name, but the loaded data is keyed by attribute. It now pops by attribute, following a dotted attribute into the nested dict. The test is in tests/test_decorators.py.

This builds on #3087, which makes validators run for dotted attributes, so that one should go in first.

Found with the Quality Playbook, an AI code-review tool I maintain; I reproduced it and reviewed the fix myself.

A field with attribute="a.b" is loaded into a nested dict by set_value,
but _invoke_field_validators looked the value up with the literal
attribute string, got a KeyError and skipped the validator. Read the
value along the dotted path instead.
…s an attribute

When a @validates method rejects a field's value, _invoke_field_validators
popped the value from the loaded data by field name, but the loaded data is
keyed by the field's attribute. For a field with attribute set, the rejected
value stayed in ValidationError.valid_data. Pop it by attribute, following a
dotted attribute into the nested dict.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant