-
-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathtest_hooks.py
More file actions
451 lines (344 loc) · 12.4 KB
/
Copy pathtest_hooks.py
File metadata and controls
451 lines (344 loc) · 12.4 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
# SPDX-License-Identifier: MIT
from __future__ import annotations
from datetime import datetime
import pytest
import attr
class TestTransformHook:
"""
Tests for `attrs(tranform_value_serializer=func)`
"""
def test_hook_applied(self):
"""
The transform hook is applied to all attributes. Types can be missing,
explicitly set, or annotated.
"""
results = []
def hook(cls, attribs):
attr.resolve_types(cls, attribs=attribs)
results[:] = [(a.name, a.type) for a in attribs]
return attribs
@attr.s(field_transformer=hook)
class C:
x = attr.ib()
y = attr.ib(type=int)
z: float = attr.ib()
assert [("x", None), ("y", int), ("z", float)] == results
def test_hook_applied_auto_attrib(self):
"""
The transform hook is applied to all attributes and type annotations
are detected.
"""
results = []
def hook(cls, attribs):
attr.resolve_types(cls, attribs=attribs)
results[:] = [(a.name, a.type) for a in attribs]
return attribs
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int
y: str = attr.ib()
assert [("x", int), ("y", str)] == results
def test_hook_applied_modify_attrib(self):
"""
The transform hook can modify attributes.
"""
def hook(cls, attribs):
attr.resolve_types(cls, attribs=attribs)
return [a.evolve(converter=a.type) for a in attribs]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int = attr.ib(converter=int)
y: float
c = C(x="3", y="3.14")
assert C(x=3, y=3.14) == c
def test_hook_remove_field(self):
"""
It is possible to remove fields via the hook.
"""
def hook(cls, attribs):
attr.resolve_types(cls, attribs=attribs)
return [a for a in attribs if a.type is not int]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int
y: float
assert {"y": 2.7} == attr.asdict(C(2.7))
def test_hook_add_field(self):
"""
It is possible to add fields via the hook.
"""
def hook(cls, attribs):
a1 = attribs[0]
a2 = a1.evolve(name="new")
return [a1, a2]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int
assert {"x": 1, "new": 2} == attr.asdict(C(1, 2))
def test_hook_override_alias(self):
"""
It is possible to set field alias via hook
"""
def use_dataclass_names(cls, attribs):
return [a.evolve(alias=a.name) for a in attribs]
@attr.s(auto_attribs=True, field_transformer=use_dataclass_names)
class NameCase:
public: int
_private: int
__dunder__: int
assert NameCase(public=1, _private=2, __dunder__=3) == NameCase(
1, 2, 3
)
def test_hook_reorder_fields(self):
"""
It is possible to reorder fields via the hook.
"""
def hook(cls, attribs):
return sorted(attribs, key=lambda x: x.metadata["field_order"])
@attr.s(field_transformer=hook)
class C:
x: int = attr.ib(metadata={"field_order": 1})
y: int = attr.ib(metadata={"field_order": 0})
assert {"x": 0, "y": 1} == attr.asdict(C(1, 0))
def test_hook_reorder_fields_before_order_check(self):
"""
It is possible to reorder fields via the hook before order-based errors are raised.
Regression test for #1147.
"""
def hook(cls, attribs):
return sorted(attribs, key=lambda x: x.metadata["field_order"])
@attr.s(field_transformer=hook)
class C:
x: int = attr.ib(metadata={"field_order": 1}, default=0)
y: int = attr.ib(metadata={"field_order": 0})
assert {"x": 0, "y": 1} == attr.asdict(C(1))
def test_hook_conflicting_defaults_after_reorder(self):
"""
Raises `ValueError` if attributes with defaults are followed by
mandatory attributes after the hook reorders fields.
Regression test for #1147.
"""
def hook(cls, attribs):
return sorted(attribs, key=lambda x: x.metadata["field_order"])
with pytest.raises(ValueError) as e:
@attr.s(field_transformer=hook)
class C:
x: int = attr.ib(metadata={"field_order": 1})
y: int = attr.ib(metadata={"field_order": 0}, default=0)
assert (
"No mandatory attributes allowed after an attribute with a "
"default value or factory. Attribute in question: Attribute"
"(name='x', default=NOTHING, validator=None, repr=True, "
"eq=True, eq_key=None, order=True, order_key=None, "
"hash=None, init=True, "
"metadata=mappingproxy({'field_order': 1}), type='int', converter=None, "
"kw_only=False, inherited=False, on_setattr=None, alias='x')",
) == e.value.args
def test_hook_with_inheritance(self):
"""
The hook receives all fields from base classes.
"""
def hook(cls, attribs):
assert ["x", "y"] == [a.name for a in attribs]
# Remove Base' "x"
return attribs[1:]
@attr.s(auto_attribs=True)
class Base:
x: int
@attr.s(auto_attribs=True, field_transformer=hook)
class Sub(Base):
y: int
assert {"y": 2} == attr.asdict(Sub(2))
def test_attrs_attrclass(self):
"""
The list of attrs returned by a field_transformer is converted to
"AttrsClass" again.
Regression test for #821.
"""
@attr.s(auto_attribs=True, field_transformer=lambda c, a: list(a))
class C:
x: int
fields_type = type(attr.fields(C))
assert "CAttributes" == fields_type.__name__
assert issubclass(fields_type, tuple)
def test_hook_generator(self):
"""
field_transfromers can be a generators.
Regression test for #1416.
"""
def hook(cls, attribs):
yield from attribs
@attr.s(auto_attribs=True, field_transformer=hook)
class Base:
x: int
assert ["x"] == [a.name for a in attr.fields(Base)]
def test_hook_alias_available(self):
"""
The field_transformer receives attributes with default aliases
already resolved, not None.
Regression test for #1479.
"""
seen = []
def hook(cls, attribs):
seen[:] = [(a.name, a.alias, a.alias_is_default) for a in attribs]
return attribs
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
_private: int
_explicit: int = attr.ib(alias="_explicit")
public: int
assert [
("_private", "private", True),
("_explicit", "_explicit", False),
("public", "public", True),
] == seen
def test_hook_evolve_name_updates_auto_alias(self):
"""
When a field_transformer evolves a field's name, the alias is
automatically updated if it was auto-generated.
Regression test for #1479.
"""
def hook(cls, attribs):
return [a.evolve(name="renamed") for a in attribs]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
_original: int
f = attr.fields(C).renamed
assert "renamed" == f.alias
assert f.alias_is_default is True
def test_hook_evolve_name_keeps_explicit_alias(self):
"""
When a field_transformer evolves a field's name but the field had
an explicit alias, the alias is preserved.
Regression test for #1479.
"""
def hook(cls, attribs):
return [a.evolve(name="renamed") for a in attribs]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
original: int = attr.ib(alias="my_alias")
f = attr.fields(C).renamed
assert "my_alias" == f.alias
assert f.alias_is_default is False
def test_hook_new_field_without_alias(self):
"""
When a field_transformer adds a brand-new field without setting an
alias, the post-transformer alias resolution fills it in.
Regression test for #1479.
"""
def hook(cls, attribs):
return [
*list(attribs),
attr.Attribute(
name="_extra",
default=0,
validator=None,
repr=True,
cmp=None,
hash=None,
init=True,
metadata={},
type=int,
converter=None,
kw_only=False,
eq=True,
eq_key=None,
order=True,
order_key=None,
on_setattr=None,
alias=None,
inherited=False,
),
]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int
f = attr.fields(C)._extra
assert "extra" == f.alias
assert f.alias_is_default is True
def test_hook_explicit_alias_matching_default(self):
"""
When a user explicitly sets an alias that happens to equal the
auto-generated default, alias_is_default is still False.
Regression test for #1479.
"""
@attr.s(auto_attribs=True)
class C:
_private: int = attr.ib(alias="private")
f = attr.fields(C)._private
assert "private" == f.alias
assert f.alias_is_default is False
def test_hook_evolve_alias_sets_not_default(self):
"""
When a field_transformer uses evolve() to set an explicit alias,
alias_is_default becomes False.
Regression test for #1479.
"""
def hook(cls, attribs):
return [a.evolve(alias="custom") for a in attribs]
@attr.s(auto_attribs=True, field_transformer=hook)
class C:
x: int
f = attr.fields(C).x
assert "custom" == f.alias
assert f.alias_is_default is False
class TestAsDictHook:
def test_asdict(self):
"""
asdict() calls the hooks in attrs classes and in other datastructures
like lists or dicts.
"""
def hook(inst, a, v):
if isinstance(v, datetime):
return v.isoformat()
return v
@attr.dataclass
class Child:
x: datetime
y: list[datetime]
@attr.dataclass
class Parent:
a: Child
b: list[Child]
c: dict[str, Child]
d: dict[str, datetime]
inst = Parent(
a=Child(1, [datetime(2020, 7, 1)]),
b=[Child(2, [datetime(2020, 7, 2)])],
c={"spam": Child(3, [datetime(2020, 7, 3)])},
d={"eggs": datetime(2020, 7, 4)},
)
result = attr.asdict(inst, value_serializer=hook)
assert {
"a": {"x": 1, "y": ["2020-07-01T00:00:00"]},
"b": [{"x": 2, "y": ["2020-07-02T00:00:00"]}],
"c": {"spam": {"x": 3, "y": ["2020-07-03T00:00:00"]}},
"d": {"eggs": "2020-07-04T00:00:00"},
} == result
def test_asdict_calls(self):
"""
The correct instances and attribute names are passed to the hook.
"""
calls = []
def hook(inst, a, v):
calls.append((inst, a.name if a else a, v))
return v
@attr.dataclass
class Child:
x: int
@attr.dataclass
class Parent:
a: Child
b: list[Child]
c: dict[str, Child]
inst = Parent(a=Child(1), b=[Child(2)], c={"spam": Child(3)})
attr.asdict(inst, value_serializer=hook)
assert [
(inst, "a", inst.a),
(inst.a, "x", inst.a.x),
(inst, "b", inst.b),
(inst.b[0], "x", inst.b[0].x),
(inst, "c", inst.c),
(None, None, "spam"),
(inst.c["spam"], "x", inst.c["spam"].x),
] == calls