Skip to content

Instantly share code, notes, and snippets.

@mkemmerling
Created August 22, 2015 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkemmerling/c6f532b31c8c41e9b5c8 to your computer and use it in GitHub Desktop.
Save mkemmerling/c6f532b31c8c41e9b5c8 to your computer and use it in GitHub Desktop.
from django.http import QueryDict
from rest_framework import serializers
class TestAllowBlank:
def test_query_dict_without_default(self):
"""
For a non-required CharField that allows blanks an empty string
is omitted from the validated serializer data if passed as
HTML input data.
"""
class TestSerializer(serializers.Serializer):
title = serializers.CharField(required=False, allow_blank=True)
serializer = TestSerializer(data=QueryDict('title='))
assert serializer.is_valid()
assert serializer.validated_data == {}
def test_query_dict_with_default(self):
"""
If the empty string is defined as default value of the CharField
it is included in the validated serializer data.
"""
class TestSerializer(serializers.Serializer):
title = serializers.CharField(required=False, allow_blank=True,
default='')
serializer = TestSerializer(data=QueryDict('title='))
assert serializer.is_valid()
assert serializer.validated_data == {'title': ''}
def test_dict(self):
"""
If the empty string is passed in an ordinary dict (JSON request)
it is included in the validated serializer data, too.
"""
class TestSerializer(serializers.Serializer):
title = serializers.CharField(required=False, allow_blank=True)
serializer = TestSerializer(data={'title': ''})
assert serializer.is_valid()
assert serializer.validated_data == {'title': ''}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment