/
test_next_gen.py
335 lines (250 loc) · 7.64 KB
/
test_next_gen.py
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
"""
Python 3-only integration tests for provisional next generation APIs.
"""
import re
from functools import partial
import pytest
import attr
@attr.define
class C:
x: str
y: int
class TestNextGen:
def test_simple(self):
"""
Instantiation works.
"""
C("1", 2)
def test_no_slots(self):
"""
slots can be deactivated.
"""
@attr.define(slots=False)
class NoSlots:
x: int
ns = NoSlots(1)
assert {"x": 1} == getattr(ns, "__dict__")
def test_validates(self):
"""
Validators at __init__ and __setattr__ work.
"""
@attr.define
class Validated:
x: int = attr.field(validator=attr.validators.instance_of(int))
v = Validated(1)
with pytest.raises(TypeError):
Validated(None)
with pytest.raises(TypeError):
v.x = "1"
def test_no_order(self):
"""
Order is off by default but can be added.
"""
with pytest.raises(TypeError):
C("1", 2) < C("2", 3)
@attr.define(order=True)
class Ordered:
x: int
assert Ordered(1) < Ordered(2)
def test_override_auto_attribs_true(self):
"""
Don't guess if auto_attrib is set explicitly.
Having an unannotated attr.ib/attr.field fails.
"""
with pytest.raises(attr.exceptions.UnannotatedAttributeError):
@attr.define(auto_attribs=True)
class ThisFails:
x = attr.field()
y: int
def test_override_auto_attribs_false(self):
"""
Don't guess if auto_attrib is set explicitly.
Annotated fields that don't carry an attr.ib are ignored.
"""
@attr.define(auto_attribs=False)
class NoFields:
x: int
y: int
assert NoFields() == NoFields()
def test_auto_attribs_detect(self):
"""
define correctly detects if a class lacks type annotations.
"""
@attr.define
class OldSchool:
x = attr.field()
assert OldSchool(1) == OldSchool(1)
# Test with maybe_cls = None
@attr.define()
class OldSchool2:
x = attr.field()
assert OldSchool2(1) == OldSchool2(1)
def test_auto_attribs_detect_fields_and_annotations(self):
"""
define infers auto_attribs=True if fields have type annotations
"""
@attr.define
class NewSchool:
x: int
y: list = attr.field()
@y.validator
def _validate_y(self, attribute, value):
if value < 0:
raise ValueError("y must be positive")
assert NewSchool(1, 1) == NewSchool(1, 1)
with pytest.raises(ValueError):
NewSchool(1, -1)
assert list(attr.fields_dict(NewSchool).keys()) == ["x", "y"]
def test_auto_attribs_partially_annotated(self):
"""
define infers auto_attribs=True if any type annotations are found
"""
@attr.define
class NewSchool:
x: int
y: list
z = 10
# fields are defined for any annotated attributes
assert NewSchool(1, []) == NewSchool(1, [])
assert list(attr.fields_dict(NewSchool).keys()) == ["x", "y"]
# while the unannotated attributes are left as class vars
assert NewSchool.z == 10
assert "z" in NewSchool.__dict__
def test_auto_attribs_detect_annotations(self):
"""
define correctly detects if a class has type annotations.
"""
@attr.define
class NewSchool:
x: int
assert NewSchool(1) == NewSchool(1)
# Test with maybe_cls = None
@attr.define()
class NewSchool2:
x: int
assert NewSchool2(1) == NewSchool2(1)
def test_exception(self):
"""
Exceptions are detected and correctly handled.
"""
@attr.define
class E(Exception):
msg: str
other: int
with pytest.raises(E) as ei:
raise E("yolo", 42)
e = ei.value
assert ("yolo", 42) == e.args
assert "yolo" == e.msg
assert 42 == e.other
def test_frozen(self):
"""
attr.frozen freezes classes.
"""
@attr.frozen
class F:
x: str
f = F(1)
with pytest.raises(attr.exceptions.FrozenInstanceError):
f.x = 2
def test_auto_detect_eq(self):
"""
auto_detect=True works for eq.
Regression test for #670.
"""
@attr.define
class C:
def __eq__(self, o):
raise ValueError()
with pytest.raises(ValueError):
C() == C()
def test_subclass_frozen(self):
"""
It's possible to subclass an `attr.frozen` class and the frozen-ness is
inherited.
"""
@attr.frozen
class A:
a: int
@attr.frozen
class B(A):
b: int
@attr.define(on_setattr=attr.setters.NO_OP)
class C(B):
c: int
assert B(1, 2) == B(1, 2)
assert C(1, 2, 3) == C(1, 2, 3)
with pytest.raises(attr.exceptions.FrozenInstanceError):
A(1).a = 1
with pytest.raises(attr.exceptions.FrozenInstanceError):
B(1, 2).a = 1
with pytest.raises(attr.exceptions.FrozenInstanceError):
B(1, 2).b = 2
with pytest.raises(attr.exceptions.FrozenInstanceError):
C(1, 2, 3).c = 3
def test_catches_frozen_on_setattr(self):
"""
Passing frozen=True and on_setattr hooks is caught, even if the
immutability is inherited.
"""
@attr.define(frozen=True)
class A:
pass
with pytest.raises(
ValueError, match="Frozen classes can't use on_setattr."
):
@attr.define(frozen=True, on_setattr=attr.setters.validate)
class B:
pass
with pytest.raises(
ValueError,
match=re.escape(
"Frozen classes can't use on_setattr "
"(frozen-ness was inherited)."
),
):
@attr.define(on_setattr=attr.setters.validate)
class C(A):
pass
@pytest.mark.parametrize(
"decorator",
[
partial(attr.s, frozen=True, slots=True, auto_exc=True),
attr.frozen,
attr.define,
attr.mutable,
],
)
def test_discard_context(self, decorator):
"""
raise from None works.
Regression test for #703.
"""
@decorator
class MyException(Exception):
x: str = attr.ib()
with pytest.raises(MyException) as ei:
try:
raise ValueError()
except ValueError:
raise MyException("foo") from None
assert "foo" == ei.value.x
assert ei.value.__cause__ is None
def test_converts_and_validates_by_default(self):
"""
If no on_setattr is set, assume setters.convert, setters.validate.
"""
@attr.define
class C:
x: int = attr.field(converter=int)
@x.validator
def _v(self, _, value):
if value < 10:
raise ValueError("must be >=10")
inst = C(10)
# Converts
inst.x = "11"
assert 11 == inst.x
# Validates
with pytest.raises(ValueError, match="must be >=10"):
inst.x = "9"