From 8af366a73282359c63eab6e81b80fb859604424f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Padilla?= Date: Wed, 19 Aug 2015 11:38:31 -0400 Subject: [PATCH] Raise error when `source=` use on a child. Closes #3292 --- rest_framework/fields.py | 12 ++++++++++++ tests/test_fields.py | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 67b1582c9..e2081abd4 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1381,7 +1381,13 @@ class ListField(Field): def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) + assert not inspect.isclass(self.child), '`child` has not been instantiated.' + assert self.child.source is None, ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + super(ListField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) @@ -1424,7 +1430,13 @@ class DictField(Field): def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) + assert not inspect.isclass(self.child), '`child` has not been instantiated.' + assert self.child.source is None, ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + super(DictField, self).__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) diff --git a/tests/test_fields.py b/tests/test_fields.py index 0fea45a33..58c1c9243 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1416,6 +1416,15 @@ class TestListField(FieldValues): ] field = serializers.ListField(child=serializers.IntegerField()) + def test_no_source_on_child(self): + with pytest.raises(AssertionError) as exc_info: + serializers.ListField(child=serializers.IntegerField(source='other')) + + assert str(exc_info.value) == ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + class TestEmptyListField(FieldValues): """ @@ -1461,6 +1470,15 @@ class TestDictField(FieldValues): ] field = serializers.DictField(child=serializers.CharField()) + def test_no_source_on_child(self): + with pytest.raises(AssertionError) as exc_info: + serializers.DictField(child=serializers.CharField(source='other')) + + assert str(exc_info.value) == ( + "The `source` argument is not meaningful when applied to a `child=` field. " + "Remove `source=` from the field declaration." + ) + class TestUnvalidatedDictField(FieldValues): """