File: test_deserialization.py

package info (click to toggle)
python-marshmallow-polyfield 5.11-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 168 kB
  • sloc: python: 651; sh: 7; makefile: 4
file content (312 lines) | stat: -rw-r--r-- 10,091 bytes parent folder | download | duplicates (2)
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
from marshmallow import Schema, ValidationError, post_load, fields
from marshmallow_polyfield.polyfield import PolyField, PolyFieldBase
import pytest
from tests.shapes import (
    Shape,
    Rectangle,
    Triangle,
    shape_schema_serialization_disambiguation,
    shape_property_schema_serialization_disambiguation,
    shape_schema_deserialization_disambiguation,
    shape_property_schema_deserialization_disambiguation,
    fuzzy_schema_deserialization_disambiguation,
)
from tests.polyclasses import (
    ShapePolyField,
    ShapePropertyPolyField,
    with_all
)


def _bad_deserializer_disambiguation(self, _):
    return 1


class BadClassPolyField(PolyFieldBase):
    def serialization_schema_selector(self, value, obj):
        return _bad_deserializer_disambiguation(value, obj)

    def deserialization_schema_selector(self, value, obj):
        return _bad_deserializer_disambiguation(value, obj)


class TestPolyField(object):

    class BadContrivedClassSchema(Schema):
        main = PolyField(
            serialization_schema_selector=_bad_deserializer_disambiguation,
            deserialization_schema_selector=_bad_deserializer_disambiguation,
            required=True
        )
        others = PolyField(
            serialization_schema_selector=_bad_deserializer_disambiguation,
            deserialization_schema_selector=_bad_deserializer_disambiguation,
            allow_none=True,
            many=True
        )

    class BadContrivedSubclassSchema(Schema):
        main = BadClassPolyField(required=True)
        others = BadClassPolyField(allow_none=True, many=True)

    class ContrivedShapeClass(object):
        def __init__(self, main, others):
            self.main = main
            self.others = others

        def __eq__(self, other):
            return self.__dict__ == other.__dict__

    class ContrivedShapeClassSchema(Schema):
        main = PolyField(
            serialization_schema_selector=shape_schema_serialization_disambiguation,
            deserialization_schema_selector=shape_schema_deserialization_disambiguation,
            required=True
        )
        others = PolyField(
            serialization_schema_selector=shape_schema_serialization_disambiguation,
            deserialization_schema_selector=shape_schema_deserialization_disambiguation,
            allow_none=True,
            many=True
        )

        @post_load
        def make_object(self, data, **_):
            return TestPolyField.ContrivedShapeClass(
                data.get('main'),
                data.get('others')
            )

    class FuzzySchema(Schema):
        data = PolyField(
            deserialization_schema_selector=fuzzy_schema_deserialization_disambiguation,
            many=True
        )

    class ContrivedShapeSubclassSchema(Schema):
        main = ShapePolyField(required=True)
        others = ShapePolyField(allow_none=True, many=True)

        @post_load
        def make_object(self, data, **_):
            return TestPolyField.ContrivedShapeClass(
                data.get('main'),
                data.get('others')
            )

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield(self, schema):
        original = self.ContrivedShapeClass(
            Rectangle('blue', 1, 100),
            [Rectangle('pink', 4, 93), Triangle('red', 8, 45)]
        )

        data = schema().load(
            {'main': {'color': 'blue',
                      'length': 1,
                      'width': 100},
             'others': [
                 {'color': 'pink',
                  'length': 4,
                  'width': 93},
                 {'color': 'red',
                  'base': 8,
                  'height': 45}]}
        )
        assert data == original

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield_none(self, schema):
        original = self.ContrivedShapeClass(
            Rectangle("blue", 1, 100),
            None
        )

        data = schema().load(
            {'main': {'color': 'blue',
                      'length': 1,
                      'width': 100},
             'others': None}
        )
        assert data == original

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserailize_polyfield_none_required(self, schema):
        with pytest.raises(ValidationError):
            schema().load(
                {'main': None,
                 'others': None}
            )

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield_invalid_type_error(self, schema):
        with pytest.raises(ValidationError) as excinfo:
            schema().load(
                {'main': {'color': 'blue', 'something': 4},
                 'others': None}
            )

        assert str(excinfo.value) == str("{'main': ['Could not detect type. "
                                         "Did not have a base or a length. "
                                         "Are you sure this is a shape?']}")

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield_invalid_validation_error(self, schema):
        with pytest.raises(ValidationError) as excinfo:
            schema().load(
                {'main': {'base': -1, 'something': 4},
                 'others': None}
            )

        assert str(excinfo.value) == "{'main': ['Base cannot be negative.']}"

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield_invalid_generic_error(self, schema):
        err_msg = 'Ensure there is a deserialization_schema_selector'
        with pytest.raises(ValidationError, match=err_msg):
            schema().load(
                {'main': {'width': 100, 'length': -1},
                 'others': {'width': 100, 'length': 10}}

            )

    @with_all(
        BadContrivedClassSchema,
        BadContrivedSubclassSchema,
    )
    def test_deserialize_polyfield_invalid_schema_returned_is_invalid(self, schema):
        with pytest.raises(ValidationError):
            schema().load(
                {'main': {'color': 'blue', 'something': 4},
                 'others': None}
            )

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield_errors(self, schema):
        with pytest.raises(ValidationError):
            schema().load(
                {'main': {'color': 'blue', 'length': 'four', 'width': 4},
                 'others': None}
            )

    def test_fuzzy_schema(self):
        color = 'cyan'
        email = 'dummy@example.com'
        expected_data = {'data': [Shape(color), email]}

        data = self.FuzzySchema().load({'data': [{'color': color}, email]})

        assert data == expected_data


class TestPolyFieldDisambiguationByProperty(object):

    class ContrivedShapeClass(object):
        def __init__(self, main, others, type):
            self.main = main
            self.others = others
            self.type = type

        def __eq__(self, other):
            return self.__dict__ == other.__dict__

    class ContrivedShapeClassSchema(Schema):
        main = PolyField(
            serialization_schema_selector=shape_property_schema_serialization_disambiguation,
            deserialization_schema_selector=shape_property_schema_deserialization_disambiguation,
            required=True
        )
        others = PolyField(
            serialization_schema_selector=shape_property_schema_serialization_disambiguation,
            deserialization_schema_selector=shape_property_schema_deserialization_disambiguation,
            allow_none=True,
            many=True
        )
        type = fields.String(required=True)

        @post_load
        def make_object(self, data, **_):
            return TestPolyFieldDisambiguationByProperty.ContrivedShapeClass(
                data.get('main'),
                data.get('others'),
                data.get('type')
            )

    class ContrivedShapeSubclassSchema(Schema):
        main = ShapePropertyPolyField(required=True)
        others = ShapePropertyPolyField(allow_none=True, many=True)
        type = fields.String(required=True)

        @post_load
        def make_object(self, data, **_):
            return TestPolyFieldDisambiguationByProperty.ContrivedShapeClass(
                data.get('main'),
                data.get('others'),
                data.get('type')
            )

    @with_all(
        ContrivedShapeClassSchema,
        ContrivedShapeSubclassSchema,
    )
    def test_deserialize_polyfield(self, schema):
        original = self.ContrivedShapeClass(
            Rectangle('blue', 1, 100),
            [Rectangle('pink', 4, 93), Rectangle('red', 3, 90)],
            'rectangle'
        )

        data = schema().load(
            {'main': {'color': 'blue',
                      'length': 1,
                      'width': 100},
             'others': [
                 {'color': 'pink',
                  'length': 4,
                  'width': 93},
                 {'color': 'red',
                  'length': 3,
                  'width': 90}],
             'type': 'rectangle'}
        )
        assert data == original


def test_deserialize_polyfield_partial_loading():

    class CircleSchema(Schema):
        color = fields.Str(required=True)
        radius = fields.Int(required=True)

    class PartialLoadingShapeSchema(Schema):
        shape = PolyField(
            deserialization_schema_selector=lambda _, __: CircleSchema,
            required=True
        )

    data = {'shape': {'radius': 1}}

    assert PartialLoadingShapeSchema().load(data, partial=True) == data
    assert PartialLoadingShapeSchema(partial=True).load(data) == data
    assert PartialLoadingShapeSchema().load(data, partial=("shape.color", )) == data