Nested field is not being validated correctly
Hello, I'm using marshmallow as a validation and marshalling library. In some validation classes I use Nested field.
Part of my test suite tests that the validations are returning the corrected error when some unexpected data is sent. If I try to send a string to a Nested field I get an exception:
marshmallow/fields.pyc in deserialize(self, data, fields_dict, many, validators, preprocess, postprocess, strict, dict_class)
283 continue
284 key = fields_dict[attr_name].attribute or attr_name
--> 285 raw_value = data.get(attr_name, missing)
286 if raw_value is missing and not field_obj.required:
287 continue
AttributeError: 'str' object has no attribute 'get'
The example code I'm using to replicate this error is:
from marshmallow import Schema, fields, validate
class ValidateClass(Schema):
item = fields.Nested('NestClass', many=True, required=True)
class NestClass(Schema):
item1 = fields.Integer(required=True, validate=validate.Range(min=2, max=24))
item2 = fields.String(required=True, validate=validate.Length(min=0))
ValidateClass().load({'item': 'a'})
I also tried adding a validator to item field where I check that I'm receiving a valid list of objects, but it's still raising the exception.
Any thoughts? Thanks.
Nested objects are expected to be a dictionaries; you are passing a string. The following would be valid according to your ValidateClass:
{'item': [{'item1': 2, 'item2': 'foo'}]}
As a dictionary works great, but what I'm trying to do is break the validation.
If someone sents me an invalid value I should handle it, shouldn't it receive an error similar to the one int returns if you send a string?
from marshmallow import Schema, fields
class Test(Schema):
test_int = fields.Integer(required=True)
print Test().load({'test_int': 'value'}).errors
# Returns {'test_int': [u"invalid literal for int() with base 10: 'value'"]}
Maybe we should return something similar with an error in errors dict, what do you think?
@juanrossi . I agree; a validation error should be raised if an invalid type is passed to a Nested field.
Pull requests welcome!
:+1:
@juanrossi I implemented a very simple fix in https://github.com/marshmallow-code/marshmallow/commit/20c112841c373494a6c628345cacc0063f901ca7. Is this enough to meet your use case and close the issue?
@sloria Thanks! It's working great.
If I found any similar case that is not working correctly I'll reopen the issue.