Skip to content

Commit

Permalink
Merge pull request #2766 from delinhabit/allow-null-list-serializer
Browse files Browse the repository at this point in the history
Modify subtle ChildSerializer(many=True, allow_null=True) behavior.
  • Loading branch information
tomchristie committed Jul 31, 2015
2 parents 9a661f5 + bbd44ae commit a543fae
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion rest_framework/serializers.py
Expand Up @@ -48,7 +48,7 @@
LIST_SERIALIZER_KWARGS = (
'read_only', 'write_only', 'required', 'default', 'initial', 'source',
'label', 'help_text', 'style', 'error_messages', 'allow_empty',
'instance', 'data', 'partial', 'context'
'instance', 'data', 'partial', 'context', 'allow_null'
)


Expand Down
56 changes: 56 additions & 0 deletions tests/test_serializer_nested.py
Expand Up @@ -69,3 +69,59 @@ def test_multipart_validate(self):
input_data = QueryDict('nested[one]=1')
serializer = self.Serializer(data=input_data)
assert serializer.is_valid()


class TestNestedSerializerWithMany:
def setup(self):
class NestedSerializer(serializers.Serializer):
example = serializers.IntegerField(max_value=10)

class TestSerializer(serializers.Serializer):
allow_null = NestedSerializer(many=True, allow_null=True)
not_allow_null = NestedSerializer(many=True)

self.Serializer = TestSerializer

def test_null_allowed_if_allow_null_is_set(self):
input_data = {
'allow_null': None,
'not_allow_null': [{'example': '2'}, {'example': '3'}]
}
expected_data = {
'allow_null': None,
'not_allow_null': [{'example': 2}, {'example': 3}]
}
serializer = self.Serializer(data=input_data)

assert serializer.is_valid(), serializer.errors
assert serializer.validated_data == expected_data

def test_null_is_not_allowed_if_allow_null_is_not_set(self):
input_data = {
'allow_null': None,
'not_allow_null': None
}
serializer = self.Serializer(data=input_data)

assert not serializer.is_valid()

expected_errors = {'not_allow_null': [serializer.error_messages['null']]}
assert serializer.errors == expected_errors

def test_run_the_field_validation_even_if_the_field_is_null(self):
class TestSerializer(self.Serializer):
validation_was_run = False

def validate_allow_null(self, value):
TestSerializer.validation_was_run = True
return value

input_data = {
'allow_null': None,
'not_allow_null': [{'example': 2}]
}
serializer = TestSerializer(data=input_data)

assert serializer.is_valid()
assert serializer.validated_data == input_data
assert TestSerializer.validation_was_run

0 comments on commit a543fae

Please sign in to comment.