File: test_v.py

package info (click to toggle)
python-cattrs 25.3.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,812 kB
  • sloc: python: 12,236; makefile: 155
file content (357 lines) | stat: -rw-r--r-- 9,868 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
"""Tests for the cattrs.v framework."""

from typing import (
    Dict,
    List,
    MutableMapping,
    MutableSequence,
    Optional,
    Sequence,
    Tuple,
    TypedDict,
)

from attrs import Factory, define, field
from pytest import fixture, raises

from cattrs import Converter, transform_error
from cattrs._compat import Mapping
from cattrs.errors import IterableValidationError
from cattrs.gen import make_dict_structure_fn
from cattrs.v import format_exception


@fixture
def c() -> Converter:
    """We need only converters with detailed_validation=True."""
    return Converter(detailed_validation=True)


def test_attribute_errors(c: Converter) -> None:
    @define
    class C:
        a: int
        b: int = 0

    try:
        c.structure({}, C)
    except Exception as exc:
        assert transform_error(exc) == ["required field missing @ $.a"]

    try:
        c.structure({"a": 1, "b": "str"}, C)
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $.b"]

    @define
    class D:
        c: C

    try:
        c.structure({}, D)
    except Exception as exc:
        assert transform_error(exc) == ["required field missing @ $.c"]

    try:
        c.structure({"c": {}}, D)
    except Exception as exc:
        assert transform_error(exc) == ["required field missing @ $.c.a"]

    try:
        c.structure({"c": 1}, D)
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected C @ $.c"]

    try:
        c.structure({"c": {"a": "str"}}, D)
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $.c.a"]

    @define
    class E:
        a: Optional[int]

    with raises(Exception) as exc:
        c.structure({"a": "str"}, E)

    # Complicated due to various Python versions.
    tn = (
        Optional[int].__name__
        if hasattr(Optional[int], "__name__")
        else repr(Optional[int])
    )
    assert transform_error(exc.value) == [
        f"invalid value for type, expected {tn} @ $.a"
    ]


def test_class_errors(c: Converter) -> None:
    """Errors not directly related to attributes are parsed correctly."""

    @define
    class C:
        a: int
        b: int = 0

    c.register_structure_hook(
        C, make_dict_structure_fn(C, c, _cattrs_forbid_extra_keys=True)
    )

    try:
        c.structure({"d": 1}, C)
    except Exception as exc:
        assert transform_error(exc) == [
            "required field missing @ $.a",
            "extra fields found (d) @ $",
        ]


def test_untyped_class_errors(c: Converter) -> None:
    """Errors on untyped attrs classes transform correctly."""

    @define
    class C:
        a = field()

    def struct_hook(v, __):
        if v == 0:
            raise ValueError()
        raise TypeError("wrong type")

    c.register_structure_hook_func(lambda t: t is None, struct_hook)

    with raises(Exception) as exc_info:
        c.structure({"a": 0}, C)

    assert transform_error(exc_info.value) == ["invalid value @ $.a"]

    with raises(Exception) as exc_info:
        c.structure({"a": 1}, C)

    assert transform_error(exc_info.value) == ["invalid type (wrong type) @ $.a"]


def test_sequence_errors(c: Converter) -> None:
    try:
        c.structure(["str", 1, "str"], List[int])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $[0]",
            "invalid value for type, expected int @ $[2]",
        ]

    try:
        c.structure(1, List[int])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected an iterable @ $"
        ]

    try:
        c.structure(["str", 1, "str"], Tuple[int, ...])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $[0]",
            "invalid value for type, expected int @ $[2]",
        ]

    try:
        c.structure(["str", 1, "str"], Sequence[int])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $[0]",
            "invalid value for type, expected int @ $[2]",
        ]

    try:
        c.structure(["str", 1, "str"], MutableSequence[int])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $[0]",
            "invalid value for type, expected int @ $[2]",
        ]

    @define
    class C:
        a: List[int]
        b: List[List[int]] = Factory(list)

    try:
        c.structure({"a": ["str", 1, "str"]}, C)
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $.a[0]",
            "invalid value for type, expected int @ $.a[2]",
        ]

    try:
        c.structure({"a": [], "b": [[], ["str", 1, "str"]]}, C)
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $.b[1][0]",
            "invalid value for type, expected int @ $.b[1][2]",
        ]

    # IterableValidationErrors with subexceptions without notes
    exc = IterableValidationError("Test", [TypeError("Test")], list[str])

    assert transform_error(exc) == ["invalid type (Test) @ $"]


def test_mapping_errors(c: Converter) -> None:
    try:
        c.structure({"a": 1, "b": "str"}, Dict[str, int])
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $['b']"]

    @define
    class C:
        a: Dict[str, int]

    try:
        c.structure({"a": {"a": "str", "b": 1, "c": "str"}}, C)
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $.a['a']",
            "invalid value for type, expected int @ $.a['c']",
        ]

    try:
        c.structure({"a": 1}, C)
    except Exception as exc:
        assert transform_error(exc) == ["expected a mapping @ $.a"]

    try:
        c.structure({"a": 1, "b": "str"}, Mapping[str, int])
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $['b']"]

    try:
        c.structure({"a": 1, "b": "str"}, MutableMapping[str, int])
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $['b']"]

    try:
        c.structure({"a": 1, 2: "str"}, MutableMapping[int, int])
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $['a']",
            "invalid value for type, expected int @ $[2]",
        ]


def test_custom_error_fn(c: Converter) -> None:
    def my_format(exc, type):
        if isinstance(exc, KeyError):
            return "no key"
        return format_exception(exc, type)

    @define
    class C:
        a: int
        b: int = 1

    try:
        c.structure({"b": "str"}, C)
    except Exception as exc:
        assert transform_error(exc, format_exception=my_format) == [
            "no key @ $.a",
            "invalid value for type, expected int @ $.b",
        ]


def test_custom_error_fn_nested(c: Converter) -> None:
    def my_format(exc, type):
        if isinstance(exc, TypeError):
            return "Must be correct type"
        return format_exception(exc, type)

    @define
    class C:
        a: Dict[str, int]

    try:
        c.structure({"a": {"a": "str", "b": 1, "c": None}}, C)
    except Exception as exc:
        assert transform_error(exc, format_exception=my_format) == [
            "invalid value for type, expected int @ $.a['a']",
            "Must be correct type @ $.a['c']",
        ]


def test_typeddict_attribute_errors(c: Converter) -> None:
    """TypedDict errors are correctly generated."""

    class C(TypedDict):
        a: int
        b: int

    try:
        c.structure({}, C)
    except Exception as exc:
        assert transform_error(exc) == [
            "required field missing @ $.a",
            "required field missing @ $.b",
        ]

    try:
        c.structure({"b": 1}, C)
    except Exception as exc:
        assert transform_error(exc) == ["required field missing @ $.a"]

    try:
        c.structure({"a": 1, "b": "str"}, C)
    except Exception as exc:
        assert transform_error(exc) == ["invalid value for type, expected int @ $.b"]

    class D(TypedDict):
        c: C

    try:
        c.structure({}, D)
    except Exception as exc:
        assert transform_error(exc) == ["required field missing @ $.c"]

    try:
        c.structure({"c": {}}, D)
    except Exception as exc:
        assert transform_error(exc) == [
            "required field missing @ $.c.a",
            "required field missing @ $.c.b",
        ]

    try:
        c.structure({"c": 1}, D)
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid type (expected a mapping, not int) @ $.c"
        ]

    try:
        c.structure({"c": {"a": "str"}}, D)
    except Exception as exc:
        assert transform_error(exc) == [
            "invalid value for type, expected int @ $.c.a",
            "required field missing @ $.c.b",
        ]

    class E(TypedDict):
        a: Optional[int]

    with raises(Exception) as exc:
        c.structure({"a": "str"}, E)

    # Complicated due to various Python versions.
    tn = (
        Optional[int].__name__
        if hasattr(Optional[int], "__name__")
        else repr(Optional[int])
    )
    assert transform_error(exc.value) == [
        f"invalid value for type, expected {tn} @ $.a"
    ]


def test_other_errors():
    """Errors without explicit support transform predictably."""
    assert format_exception(IndexError("Test"), List[int]) == "unknown error (Test)"