File: test_next_gen.py

package info (click to toggle)
python-attrs 25.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,004 kB
  • sloc: python: 10,495; makefile: 153
file content (494 lines) | stat: -rw-r--r-- 11,617 bytes parent folder | download
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
# SPDX-License-Identifier: MIT

"""
Integration tests for next-generation APIs.
"""

import re

from contextlib import contextmanager
from functools import partial

import pytest

import attr as _attr  # don't use it by accident
import attrs

from attr._compat import PY_3_11_PLUS


@attrs.define
class C:
    x: str
    y: int


class TestNextGen:
    def test_simple(self):
        """
        Instantiation works.
        """
        C("1", 2)

    def test_field_type(self):
        """
        Make class with attrs.field and type parameter.
        """
        classFields = {"testint": attrs.field(type=int)}

        A = attrs.make_class("A", classFields)

        assert int is attrs.fields(A).testint.type

    def test_no_slots(self):
        """
        slots can be deactivated.
        """

        @attrs.define(slots=False)
        class NoSlots:
            x: int

        ns = NoSlots(1)

        assert {"x": 1} == ns.__dict__

    def test_validates(self):
        """
        Validators at __init__ and __setattr__ work.
        """

        @attrs.define
        class Validated:
            x: int = attrs.field(validator=attrs.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)

        @attrs.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 attrs.ib/attrs.field fails.
        """
        with pytest.raises(attrs.exceptions.UnannotatedAttributeError):

            @attrs.define(auto_attribs=True)
            class ThisFails:
                x = attrs.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 attrs.ib are ignored.
        """

        @attrs.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.
        """

        @attrs.define
        class OldSchool:
            x = attrs.field()

        assert OldSchool(1) == OldSchool(1)

        # Test with maybe_cls = None
        @attrs.define()
        class OldSchool2:
            x = attrs.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
        """

        @attrs.define
        class NewSchool:
            x: int
            y: list = attrs.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(attrs.fields_dict(NewSchool).keys()) == ["x", "y"]

    def test_auto_attribs_partially_annotated(self):
        """
        define infers auto_attribs=True if any type annotations are found
        """

        @attrs.define
        class NewSchool:
            x: int
            y: list
            z = 10

        # fields are defined for any annotated attributes
        assert NewSchool(1, []) == NewSchool(1, [])
        assert list(attrs.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.
        """

        @attrs.define
        class NewSchool:
            x: int

        assert NewSchool(1) == NewSchool(1)

        # Test with maybe_cls = None
        @attrs.define()
        class NewSchool2:
            x: int

        assert NewSchool2(1) == NewSchool2(1)

    def test_exception(self):
        """
        Exceptions are detected and correctly handled.
        """

        @attrs.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):
        """
        attrs.frozen freezes classes.
        """

        @attrs.frozen
        class F:
            x: str

        f = F(1)

        with pytest.raises(attrs.exceptions.FrozenInstanceError):
            f.x = 2

    def test_auto_detect_eq(self):
        """
        auto_detect=True works for eq.

        Regression test for #670.
        """

        @attrs.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 `attrs.frozen` class and the frozen-ness
        is inherited.
        """

        @attrs.frozen
        class A:
            a: int

        @attrs.frozen
        class B(A):
            b: int

        @attrs.define(on_setattr=attrs.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(attrs.exceptions.FrozenInstanceError):
            A(1).a = 1

        with pytest.raises(attrs.exceptions.FrozenInstanceError):
            B(1, 2).a = 1

        with pytest.raises(attrs.exceptions.FrozenInstanceError):
            B(1, 2).b = 2

        with pytest.raises(attrs.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.
        """

        @attrs.define(frozen=True)
        class A:
            pass

        with pytest.raises(
            ValueError, match="Frozen classes can't use on_setattr."
        ):

            @attrs.define(frozen=True, on_setattr=attrs.setters.validate)
            class B:
                pass

        with pytest.raises(
            ValueError,
            match=re.escape(
                "Frozen classes can't use on_setattr "
                "(frozen-ness was inherited)."
            ),
        ):

            @attrs.define(on_setattr=attrs.setters.validate)
            class C(A):
                pass

    @pytest.mark.parametrize(
        "decorator",
        [
            partial(_attr.s, frozen=True, slots=True, auto_exc=True),
            attrs.frozen,
            attrs.define,
            attrs.mutable,
        ],
    )
    def test_discard_context(self, decorator):
        """
        raise from None works.

        Regression test for #703.
        """

        @decorator
        class MyException(Exception):
            x: str = attrs.field()

        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

    @pytest.mark.parametrize(
        "decorator",
        [
            partial(_attr.s, frozen=True, slots=True, auto_exc=True),
            attrs.frozen,
            attrs.define,
            attrs.mutable,
        ],
    )
    def test_setting_exception_mutable_attributes(self, decorator):
        """
        contextlib.contextlib (re-)sets __traceback__ on raised exceptions.

        Ensure that works, as well as if done explicitly
        """

        @decorator
        class MyException(Exception):
            pass

        @contextmanager
        def do_nothing():
            yield

        with do_nothing(), pytest.raises(MyException) as ei:
            raise MyException

        assert isinstance(ei.value, MyException)

        # this should not raise an exception either
        ei.value.__traceback__ = ei.value.__traceback__
        ei.value.__cause__ = ValueError("cause")
        ei.value.__context__ = TypeError("context")
        ei.value.__suppress_context__ = True
        ei.value.__suppress_context__ = False
        ei.value.__notes__ = []
        del ei.value.__notes__

        if PY_3_11_PLUS:
            ei.value.add_note("note")
            del ei.value.__notes__

    def test_converts_and_validates_by_default(self):
        """
        If no on_setattr is set, assume setters.convert, setters.validate.
        """

        @attrs.define
        class C:
            x: int = attrs.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"

    def test_mro_ng(self):
        """
        Attributes and methods are looked up the same way in NG by default.

        See #428
        """

        @attrs.define
        class A:
            x: int = 10

            def xx(self):
                return 10

        @attrs.define
        class B(A):
            y: int = 20

        @attrs.define
        class C(A):
            x: int = 50

            def xx(self):
                return 50

        @attrs.define
        class D(B, C):
            pass

        d = D()

        assert d.x == d.xx()


class TestAsTuple:
    def test_smoke(self):
        """
        `attrs.astuple` only changes defaults, so we just call it and compare.
        """
        inst = C("foo", 42)

        assert attrs.astuple(inst) == _attr.astuple(inst)


class TestAsDict:
    def test_smoke(self):
        """
        `attrs.asdict` only changes defaults, so we just call it and compare.
        """
        inst = C("foo", {(1,): 42})

        assert attrs.asdict(inst) == _attr.asdict(
            inst, retain_collection_types=True
        )


class TestImports:
    """
    Verify our re-imports and mirroring works.
    """

    def test_converters(self):
        """
        Importing from attrs.converters works.
        """
        from attrs.converters import optional

        assert optional is _attr.converters.optional

    def test_exceptions(self):
        """
        Importing from attrs.exceptions works.
        """
        from attrs.exceptions import FrozenError

        assert FrozenError is _attr.exceptions.FrozenError

    def test_filters(self):
        """
        Importing from attrs.filters works.
        """
        from attrs.filters import include

        assert include is _attr.filters.include

    def test_setters(self):
        """
        Importing from attrs.setters works.
        """
        from attrs.setters import pipe

        assert pipe is _attr.setters.pipe

    def test_validators(self):
        """
        Importing from attrs.validators works.
        """
        from attrs.validators import and_

        assert and_ is _attr.validators.and_