-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #9 from ployst/carles/serializer-builder
Add SerializerBuilder
- Loading branch information
Showing
2 changed files
with
63 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,12 +6,17 @@ | |
from ..serializers import ( | ||
DynamicFieldsSerializerMixin, | ||
ExpandableFieldsSerializerMixin, | ||
SubSerializer, | ||
) | ||
|
||
|
||
class CreatorSerializer(serializers.Serializer): | ||
name = fields.CharField() | ||
other = serializers.SerializerMethodField() | ||
nickname = fields.CharField() | ||
|
||
class Meta: | ||
fields = ('name', 'nickname', 'other') | ||
|
||
def get_other(self, *args): | ||
return 'field in expansion' | ||
|
@@ -30,7 +35,7 @@ class TestExpandableFieldsSerializer(TestCase): | |
def test_expands_requested_fields(self): | ||
|
||
class ThingWithCreator(object): | ||
creator = {'name': '[email protected]'} | ||
creator = {'name': '[email protected]', 'nickname': 'jim'} | ||
|
||
request = Mock() | ||
request.query_params.get.return_value = 'creator' | ||
|
@@ -40,7 +45,11 @@ class ThingWithCreator(object): | |
|
||
self.assertDictEqual( | ||
serializer.data['creator'], | ||
{'name': '[email protected]', 'other': 'field in expansion'} | ||
{ | ||
'name': '[email protected]', | ||
'nickname': 'jim', | ||
'other': 'field in expansion' | ||
} | ||
) | ||
|
||
def test_does_not_expand_by_default(self): | ||
|
@@ -105,3 +114,21 @@ class Thing(object): | |
self.assertDictEqual( | ||
serializer.data, {'name': 'Jane', 'nickname': 'thesnake'} | ||
) | ||
|
||
|
||
class TestSerializerBuilder(TestCase): | ||
|
||
def test_only_returns_requested_fields(self): | ||
serializer_class = SubSerializer(CreatorSerializer, ('nickname',)) | ||
self.assertDictEqual(serializer_class.name, 'SubCreatorSerializer') | ||
|
||
def test_only_returns_requested_fields(self): | ||
class Thing(object): | ||
name = 'Only James' | ||
nickname = 'catnip' | ||
|
||
jim = Thing() | ||
serializer_class = SubSerializer(CreatorSerializer, ('nickname',)) | ||
serializer = serializer_class(jim) | ||
|
||
self.assertDictEqual(serializer.data, {'nickname': 'catnip'}) |