-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtest_make.py
More file actions
522 lines (355 loc) · 12.3 KB
/
test_make.py
File metadata and controls
522 lines (355 loc) · 12.3 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
import dataclasses
import datetime
import enum
import sys
import types
import typing as t
import attr
import marshmallow
import pytest
import desert
@attr.s(frozen=True, order=False)
class DataclassModule:
"""Implementation of a dataclass module like attr or dataclasses."""
dataclass = attr.ib()
field = attr.ib()
fields = attr.ib()
@pytest.fixture(
name="module",
params=[
DataclassModule(dataclass=attr.dataclass, fields=attr.fields, field=attr.ib),
DataclassModule(
dataclass=dataclasses.dataclass,
fields=dataclasses.fields,
field=dataclasses.field,
),
],
ids=["attrs", "dataclasses"],
)
def dataclass_param(request):
"""Parametrize over both implementations of the @dataclass decorator."""
return request.param
def _assert_load(
schema: t.Type[marshmallow.Schema], loaded: t.Any, dumped: t.Dict[t.Any, t.Any]
) -> None:
assert schema.load(dumped) == loaded
def _assert_dump(
schema: t.Type[marshmallow.Schema], loaded: t.Any, dumped: t.Dict[t.Any, t.Any]
) -> None:
assert schema.dump(loaded) == dumped
def _assert_dump_load(
schema: t.Type[marshmallow.Schema], loaded: t.Any, dumped: t.Dict[t.Any, t.Any]
) -> None:
assert schema.loads(schema.dumps(loaded)) == loaded
def _assert_load_dump(
schema: t.Type[marshmallow.Schema], loaded: t.Any, dumped: t.Dict[t.Any, t.Any]
) -> None:
assert schema.dump(schema.load(dumped)) == dumped
def fixture_from_dict(
name: str,
id_to_value: t.Mapping[
str, t.Callable[[t.Type[marshmallow.Schema], t.Dict[t.Any, t.Any], t.Any], None]
],
):
"""
Create fixture parametrized to yield each value and labeled with the
corresponding ID.
Args:
name: Name of the fixture itself
id_to_value: Mapping from ID labels to values
Returns:
The PyTest fixture
"""
@pytest.fixture(name=name, params=id_to_value.values(), ids=id_to_value.keys())
def fixture(request):
return request.param
return fixture
_assert_dump_load = fixture_from_dict(
name="assert_dump_load",
id_to_value={
"load": _assert_load,
"dump": _assert_dump,
"dump load": _assert_dump_load,
"load dump": _assert_load_dump,
},
)
def test_simple(module):
"""Load dict into a dataclass instance."""
@module.dataclass
class A:
x: int
data = desert.schema_class(A)().load(data={"x": 5})
assert data == A(x=5)
def test_validation(module):
"""Passing the wrong keys will raise ValidationError."""
@module.dataclass
class A:
x: int
schema = desert.schema_class(A)()
with pytest.raises(marshmallow.exceptions.ValidationError):
schema.load({"y": 5})
def test_not_a_dataclass(module):
"""Raises when object is not a dataclass."""
class A:
x: int
with pytest.raises(desert.exceptions.NotAnAttrsClassOrDataclass):
desert.schema_class(A)
def test_set_default(module):
"""Setting a default value in the dataclass makes passing it optional."""
@module.dataclass
class A:
x: int = 1
schema = desert.schema_class(A)()
data = schema.load({"x": 1})
assert data == A(1)
data = schema.load({})
assert data == A(1)
def test_list(module):
"""Build a generic list *without* setting a factory on the dataclass."""
@module.dataclass
class A:
y: t.List[int]
schema = desert.schema_class(A)()
data = schema.load({"y": [1]})
assert data == A([1])
def test_dict(module):
"""Build a dict without setting a factory on the dataclass."""
@module.dataclass
class A:
y: t.Dict[int, int]
schema = desert.schema_class(A)()
data = schema.load({"y": {1: 2, 3: 4}})
assert data == A({1: 2, 3: 4})
def test_nested(module):
"""One object can hold instances of another."""
@module.dataclass
class A:
x: int
@module.dataclass
class B:
y: A
data = desert.schema_class(B)().load({"y": {"x": 5}})
assert data == B(A(5))
def test_optional(module):
"""Setting an optional type makes the default None."""
@module.dataclass
class A:
x: t.Optional[int]
data = desert.schema_class(A)().load({})
assert data == A(None)
def test_optional_present(module):
"""Setting an optional type allows passing None."""
@module.dataclass
class A:
x: t.Optional[int]
data = desert.schema_class(A)().load({"x": None})
assert data == A(None)
def test_custom_field(module):
@module.dataclass
class A:
x: str = module.field(
metadata=desert.metadata(marshmallow.fields.NaiveDateTime())
)
timestring = "2019-10-21T10:25:00"
dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=00)
schema = desert.schema(A)
assert schema.load({"x": timestring}) == A(x=dt)
def test_concise_dataclasses_field():
"""Concisely create a dataclasses.Field."""
@dataclasses.dataclass
class A:
x: str = desert.field(marshmallow.fields.NaiveDateTime())
timestring = "2019-10-21T10:25:00"
dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=00)
schema = desert.schema(A)
assert schema.load({"x": timestring}) == A(x=dt)
def test_concise_attrib():
"""Concisely create an attr.ib()"""
@attr.dataclass
class A:
x: str = desert.ib(marshmallow.fields.NaiveDateTime())
timestring = "2019-10-21T10:25:00"
dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=00)
schema = desert.schema(A)
assert schema.load({"x": timestring}) == A(x=dt)
def test_concise_field_metadata():
"""Concisely create a dataclasses.Field with metadata."""
@dataclasses.dataclass
class A:
x: str = desert.field(marshmallow.fields.NaiveDateTime(), metadata={"foo": 1})
timestring = "2019-10-21T10:25:00"
dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=00)
schema = desert.schema(A)
assert schema.load({"x": timestring}) == A(x=dt)
assert dataclasses.fields(A)[0].metadata["foo"] == 1
def test_concise_attrib_metadata():
"""Concisely create an attr.ib() with metadata."""
@attr.dataclass
class A:
x: str = desert.ib(marshmallow.fields.NaiveDateTime(), metadata={"foo": 1})
timestring = "2019-10-21T10:25:00"
dt = datetime.datetime(year=2019, month=10, day=21, hour=10, minute=25, second=00)
schema = desert.schema(A)
assert schema.load({"x": timestring}) == A(x=dt)
assert attr.fields(A).x.metadata["foo"] == 1
@pytest.mark.parametrize(argnames=["value"], argvalues=[["X"], [5]])
def test_union(module, value, assert_dump_load):
"""Deserialize one of several types."""
@module.dataclass
class A:
x: t.Union[int, str]
schema = desert.schema_class(A)()
dumped = {"x": value}
loaded = A(value)
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
def test_enum(module, assert_dump_load):
"""Deserialize an enum object."""
class Color(enum.Enum):
RED = enum.auto()
GREEN = enum.auto()
@module.dataclass
class A:
x: Color
schema = desert.schema_class(A)()
dumped = {"x": "RED"}
loaded = A(Color.RED)
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
def test_tuple(module, assert_dump_load):
"""Round trip a tuple.
The tuple is converted to list only for dumps(), not during dump().
"""
@module.dataclass
class A:
x: t.Tuple[int, bool]
schema = desert.schema_class(A)()
dumped = {"x": (1, False)}
loaded = A(x=(1, False))
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
def test_attr_factory():
"""Attrs default factory instantiates the factory type if no value is passed."""
@attr.dataclass
class A:
x: t.List[int] = attr.ib(factory=list)
data = desert.schema_class(A)().load({})
assert data == A([])
def test_dataclasses_factory():
"""Dataclasses default factory instantiates the factory type if no value is passed."""
@dataclasses.dataclass
class A:
x: t.List[int] = dataclasses.field(default_factory=list)
data = desert.schema_class(A)().load({})
assert data == A([])
def test_newtype(module, assert_dump_load):
"""An instance of NewType delegates to its supertype."""
MyInt = t.NewType("MyInt", int)
@module.dataclass
class A:
x: MyInt
schema = desert.schema_class(A)()
dumped = {"x": 1}
loaded = A(x=1)
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
@pytest.mark.xfail(
strict=True,
reason=(
"Forward references and string annotations are broken. \n"
+ "See https://github.com/lovasoa/marshmallow_dataclass/issues/13"
),
)
def test_forward_reference(module, assert_dump_load):
"""Build schemas from classes that are defined below their containing class."""
@module.dataclass
class A:
x: "B"
@module.dataclass
class B:
y: int
schema = desert.schema_class(A)()
dumped = {"x": {"y": 1}}
loaded = A((B(1)))
assert_dump_load(schema=schema, loaded=loaded, dumped=dumped)
# 3.6.9 is known to work, 3.6.1 is known to fail, not sure attrs vs. dataclasses
@pytest.mark.skipif(
condition=sys.implementation.name == "pypy" and sys.version_info < (3, 6, 9),
reason="Forward references and string annotations are broken.",
)
def test_forward_reference_module_scope():
"""Run the forward reference test at global scope."""
import tests.cases.forward_reference # pylint disable=unused-import,import-outside-toplevel
def test_non_string_metadata_key(module):
"""A non-string key in the attrib metadata comes through in the mm field."""
@module.dataclass
class A:
x: int = module.field(metadata={1: 2})
field = desert.schema(A).fields["x"]
assert field.metadata == {1: 2, desert._make._DESERT_SENTINEL: {}}
def test_non_optional_means_required(module):
"""Non-optional fields are required."""
@module.dataclass
class A:
x: int = module.field(metadata={1: 2})
schema = desert.schema(A)
with pytest.raises(marshmallow.exceptions.ValidationError):
schema.load({})
def test_ignore_unknown_fields(module):
"""Enable unknown fields with meta argument."""
@module.dataclass
class A:
x: int
schema_class = desert.schema_class(A, meta={"unknown": marshmallow.EXCLUDE})
schema = schema_class()
data = schema.load({"x": 1, "y": 2})
assert data == A(x=1)
def test_raise_unknown_type(module):
"""Raise UnknownType for failed inferences."""
@module.dataclass
class A:
x: list
with pytest.raises(desert.exceptions.UnknownType):
desert.schema_class(A)
@pytest.mark.skipif(
sys.version_info[:2] <= (3, 6), reason="3.6 has isinstance(t.Sequence[int], type)."
)
def test_raise_unknown_generic(module):
"""Raise UnknownType for unknown generics."""
@module.dataclass
class A:
x: t.Sequence[int]
with pytest.raises(desert.exceptions.UnknownType):
desert.schema_class(A)
def test_tuple_ellipsis(module):
"""Tuple with ellipsis allows variable length tuple.
See :class:`typing.Tuple`.
"""
@module.dataclass
class A:
x: t.Tuple[int, ...]
schema = desert.schema_class(A)()
dumped = {"x": (1, 2, 3)}
loaded = A(x=(1, 2, 3))
actually_dumped = {"x": [1, 2, 3]}
# TODO: how to use assert_dump_load?
assert schema.load(dumped) == loaded
assert schema.dump(loaded) == actually_dumped
assert schema.loads(schema.dumps(loaded)) == loaded
assert schema.dump(schema.load(actually_dumped)) == actually_dumped
def test_only():
"""only() extracts the only item in an iterable."""
assert desert._make.only([1]) == 1
def test_only_raises():
"""only() raises if the iterable has an unexpected number of entries.'"""
with pytest.raises(ValueError):
desert._make.only([])
with pytest.raises(ValueError):
desert._make.only([1, 2])
def test_takes_self():
"""Attrs default factories are constructed after instance creation."""
@attr.s
class C:
x: int = attr.ib()
y: int = attr.ib()
@y.default
def _(self):
return self.x + 1
schema = desert.schema(C)
assert schema.load({"x": 1}) == C(x=1, y=2)