Handle empty data with serializer (#4564)

This commit is contained in:
Tom Christie 2016-10-12 10:47:17 +01:00 committed by GitHub
parent 4c9b14bd97
commit b419970431
3 changed files with 22 additions and 0 deletions

View File

@ -507,6 +507,11 @@ class Serializer(BaseSerializer):
@property
def errors(self):
ret = super(Serializer, self).errors
if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
# Edge case. Provide a more descriptive error than
# "this field may not be null", when no data is passed.
detail = ErrorDetail('No data provided', code='null')
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
return ReturnDict(ret, serializer=self)
@ -700,6 +705,11 @@ class ListSerializer(BaseSerializer):
@property
def errors(self):
ret = super(ListSerializer, self).errors
if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null':
# Edge case. Provide a more descriptive error than
# "this field may not be null", when no data is passed.
detail = ErrorDetail('No data provided', code='null')
ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]}
if isinstance(ret, dict):
return ReturnDict(ret, serializer=self)
return ReturnList(ret, serializer=self)

View File

@ -62,6 +62,12 @@ class TestSerializer:
with pytest.raises(AssertionError):
serializer.save()
def test_validate_none_data(self):
data = None
serializer = self.Serializer(data=data)
assert not serializer.is_valid()
assert serializer.errors == {'non_field_errors': ['No data provided']}
class TestValidateMethod:
def test_non_field_error_validate_method(self):

View File

@ -41,6 +41,12 @@ class TestNestedSerializer:
serializer = self.Serializer()
assert serializer.data == expected_data
def test_nested_serialize_no_data(self):
data = None
serializer = self.Serializer(data=data)
assert not serializer.is_valid()
assert serializer.errors == {'non_field_errors': ['No data provided']}
class TestNotRequiredNestedSerializer:
def setup(self):