Add validation for fields & exclude type.

This commit is contained in:
BrickXu 2014-12-05 14:50:53 +08:00 committed by xulei
parent 4042180392
commit d68c614504
2 changed files with 68 additions and 0 deletions

View File

@ -759,6 +759,12 @@ class ModelSerializer(Serializer):
depth = getattr(self.Meta, 'depth', 0) depth = getattr(self.Meta, 'depth', 0)
extra_kwargs = getattr(self.Meta, 'extra_kwargs', {}) extra_kwargs = getattr(self.Meta, 'extra_kwargs', {})
if fields and not isinstance(fields, (list, tuple)):
raise TypeError('`fields` must be a list or tuple')
if exclude and not isinstance(exclude, (list, tuple)):
raise TypeError('`exclude` must be a list or tuple')
assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'." assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'."
extra_kwargs = self._include_additional_options(extra_kwargs) extra_kwargs = self._include_additional_options(extra_kwargs)

View File

@ -0,0 +1,62 @@
from django.test import TestCase
from rest_framework import serializers
from .models import BasicModel
class TestSerializerMetaClass(TestCase):
def setUp(self):
class FieldsSerializer(serializers.ModelSerializer):
text = serializers.CharField()
class Meta:
model = BasicModel
fields = ('text')
class ExcludeSerializer(serializers.ModelSerializer):
text = serializers.CharField()
class Meta:
model = BasicModel
exclude = ('text')
class FieldsAndExcludeSerializer(serializers.ModelSerializer):
text = serializers.CharField()
class Meta:
model = BasicModel
fields = ('text',)
exclude = ('text',)
self.fields_serializer = FieldsSerializer
self.exclude_serializer = ExcludeSerializer
self.faeSerializer = FieldsAndExcludeSerializer
def test_meta_class_fields(self):
object = BasicModel(text="Hello World.")
serializer = self.fields_serializer(instance=object)
with self.assertRaises(TypeError) as result:
serializer.data
exception = result.exception
self.assertEqual(str(exception), "`fields` must be a list or tuple")
def test_meta_class_exclude(self):
object = BasicModel(text="Hello World.")
serializer = self.exclude_serializer(instance=object)
with self.assertRaises(TypeError) as result:
serializer.data
exception = result.exception
self.assertEqual(str(exception), "`exclude` must be a list or tuple")
def test_meta_class_fields_and_exclude(self):
object = BasicModel(text="Hello World.")
serializer = self.faeSerializer(instance=object)
with self.assertRaises(AssertionError) as result:
serializer.data
exception = result.exception
self.assertEqual(str(exception), "Cannot set both 'fields' and 'exclude'.")