aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework/tests/serializer_nested.py
blob: 6a29c65230b425ee51cf9cc76e835ee582974c59 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""
Tests to cover nested serializers.

Doesn't cover model serializers.
"""
from __future__ import unicode_literals
from django.test import TestCase
from rest_framework import serializers


class WritableNestedSerializerBasicTests(TestCase):
    """
    Tests for deserializing nested entities.
    Basic tests that use serializers that simply restore to dicts.
    """

    def setUp(self):
        class TrackSerializer(serializers.Serializer):
            order = serializers.IntegerField()
            title = serializers.CharField(max_length=100)
            duration = serializers.IntegerField()

        class AlbumSerializer(serializers.Serializer):
            album_name = serializers.CharField(max_length=100)
            artist = serializers.CharField(max_length=100)
            tracks = TrackSerializer(many=True)

        self.AlbumSerializer = AlbumSerializer

    def test_nested_validation_success(self):
        """
        Correct nested serialization should return the input data.
        """

        data = {
            'album_name': 'Discovery',
            'artist': 'Daft Punk',
            'tracks': [
                {'order': 1, 'title': 'One More Time', 'duration': 235},
                {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
                {'order': 3, 'title': 'Digital Love', 'duration': 239}
            ]
        }

        serializer = self.AlbumSerializer(data=data)
        self.assertEqual(serializer.is_valid(), True)
        self.assertEqual(serializer.object, data)

    def test_nested_validation_error(self):
        """
        Incorrect nested serialization should return appropriate error data.
        """

        data = {
            'album_name': 'Discovery',
            'artist': 'Daft Punk',
            'tracks': [
                {'order': 1, 'title': 'One More Time', 'duration': 235},
                {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
                {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
            ]
        }
        expected_errors = {
            'tracks': [
                {},
                {},
                {'duration': ['Enter a whole number.']}
            ]
        }

        serializer = self.AlbumSerializer(data=data)
        self.assertEqual(serializer.is_valid(), False)
        self.assertEqual(serializer.errors, expected_errors)

    def test_many_nested_validation_error(self):
        """
        Incorrect nested serialization should return appropriate error data
        when multiple entities are being deserialized.
        """

        data = [
            {
                'album_name': 'Russian Red',
                'artist': 'I Love Your Glasses',
                'tracks': [
                    {'order': 1, 'title': 'Cigarettes', 'duration': 121},
                    {'order': 2, 'title': 'No Past Land', 'duration': 198},
                    {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
                ]
            },
            {
                'album_name': 'Discovery',
                'artist': 'Daft Punk',
                'tracks': [
                    {'order': 1, 'title': 'One More Time', 'duration': 235},
                    {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
                    {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
                ]
            }
        ]
        expected_errors = [
            {},
            {
                'tracks': [
                    {},
                    {},
                    {'duration': ['Enter a whole number.']}
                ]
            }
        ]

        serializer = self.AlbumSerializer(data=data)
        self.assertEqual(serializer.is_valid(), False)
        self.assertEqual(serializer.errors, expected_errors)


class WritableNestedSerializerObjectTests(TestCase):
    """
    Tests for deserializing nested entities.
    These tests use serializers that restore to concrete objects.
    """

    def setUp(self):
        # Couple of concrete objects that we're going to deserialize into
        class Track(object):
            def __init__(self, order, title, duration):
                self.order, self.title, self.duration = order, title, duration

            def __eq__(self, other):
                return (
                    self.order == other.order and
                    self.title == other.title and
                    self.duration == other.duration
                )

        class Album(object):
            def __init__(self, album_name, artist, tracks):
                self.album_name, self.artist, self.tracks = album_name, artist, tracks

            def __eq__(self, other):
                return (
                    self.album_name == other.album_name and
                    self.artist == other.artist and
                    self.tracks == other.tracks
                )

        # And their corresponding serializers
        class TrackSerializer(serializers.Serializer):
            order = serializers.IntegerField()
            title = serializers.CharField(max_length=100)
            duration = serializers.IntegerField()

            def restore_object(self, attrs, instance=None):
                return Track(attrs['order'], attrs['title'], attrs['duration'])

        class AlbumSerializer(serializers.Serializer):
            album_name = serializers.CharField(max_length=100)
            artist = serializers.CharField(max_length=100)
            tracks = TrackSerializer(many=True)

            def restore_object(self, attrs, instance=None):
                return Album(attrs['album_name'], attrs['artist'], attrs['tracks'])

        self.Album, self.Track = Album, Track
        self.AlbumSerializer = AlbumSerializer

    def test_nested_validation_success(self):
        """
        Correct nested serialization should return a restored object
        that corresponds to the input data.
        """

        data = {
            'album_name': 'Discovery',
            'artist': 'Daft Punk',
            'tracks': [
                {'order': 1, 'title': 'One More Time', 'duration': 235},
                {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
                {'order': 3, 'title': 'Digital Love', 'duration': 239}
            ]
        }
        expected_object = self.Album(
            album_name='Discovery',
            artist='Daft Punk',
            tracks=[
                self.Track(order=1, title='One More Time', duration=235),
                self.Track(order=2, title='Aerodynamic', duration=184),
                self.Track(order=3, title='Digital Love', duration=239),
            ]
        )

        serializer = self.AlbumSerializer(data=data)
        self.assertEqual(serializer.is_valid(), True)
        self.assertEqual(serializer.object, expected_object)

    def test_many_nested_validation_success(self):
        """
        Correct nested serialization should return multiple restored objects
        that corresponds to the input data when multiple objects are
        being deserialized.
        """

        data = [
            {
                'album_name': 'Russian Red',
                'artist': 'I Love Your Glasses',
                'tracks': [
                    {'order': 1, 'title': 'Cigarettes', 'duration': 121},
                    {'order': 2, 'title': 'No Past Land', 'duration': 198},
                    {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
                ]
            },
            {
                'album_name': 'Discovery',
                'artist': 'Daft Punk',
                'tracks': [
                    {'order': 1, 'title': 'One More Time', 'duration': 235},
                    {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
                    {'order': 3, 'title': 'Digital Love', 'duration': 239}
                ]
            }
        ]
        expected_object = [
            self.Album(
                album_name='Russian Red',
                artist='I Love Your Glasses',
                tracks=[
                    self.Track(order=1, title='Cigarettes', duration=121),
                    self.Track(order=2, title='No Past Land', duration=198),
                    self.Track(order=3, title='They Don\'t Believe', duration=191),
                ]
            ),
            self.Album(
                album_name='Discovery',
                artist='Daft Punk',
                tracks=[
                    self.Track(order=1, title='One More Time', duration=235),
                    self.Track(order=2, title='Aerodynamic', duration=184),
                    self.Track(order=3, title='Digital Love', duration=239),
                ]
            )
        ]

        serializer = self.AlbumSerializer(data=data)
        self.assertEqual(serializer.is_valid(), True)
        self.assertEqual(serializer.object, expected_object)