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
|
# 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=None)",
) == 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)]
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
|