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
|
"""Tests for the extended validation mode."""
import pickle
from typing import Deque, Dict, FrozenSet, List, Set, Tuple
import pytest
from attrs import define, field
from attrs.validators import in_
from hypothesis import given
from cattrs import Converter
from cattrs._compat import Counter
from cattrs.errors import (
AttributeValidationNote,
ClassValidationError,
IterableValidationError,
IterableValidationNote,
)
def test_class_validation():
"""Proper class validation errors are raised when structuring."""
c = Converter(detailed_validation=True)
@define
class Test:
a: int
b: str = field(validator=in_(["a", "b"]))
c: str
with pytest.raises(ClassValidationError) as exc:
c.structure({"a": "a", "b": "c"}, Test)
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring class test_class_validation.<locals>.Test @ attribute a"
]
assert repr(exc.value.exceptions[1]) == repr(KeyError("c"))
assert exc.value.exceptions[1].__notes__ == [
"Structuring class test_class_validation.<locals>.Test @ attribute c"
]
def test_external_class_validation():
"""Proper class validation errors are raised when a classes __init__ raises."""
c = Converter(detailed_validation=True)
@define
class Test:
a: int
b: str = field(validator=in_(["a", "b"]))
c: str
with pytest.raises(ClassValidationError) as exc:
c.structure({"a": 1, "b": "c", "c": "1"}, Test)
assert type(exc.value.exceptions[0]) is ValueError
assert str(exc.value.exceptions[0].args[0]) == "'b' must be in ['a', 'b'] (got 'c')"
def test_list_validation():
"""Proper validation errors are raised structuring lists."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure(["1", 2, "a", 3.0, "c"], List[int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring typing.List[int] @ index 2"
]
assert repr(exc.value.exceptions[1]) == repr(
ValueError("invalid literal for int() with base 10: 'c'")
)
assert exc.value.exceptions[1].__notes__ == [
"Structuring typing.List[int] @ index 4"
]
def test_deque_validation():
"""Proper validation errors are raised structuring deques."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure(["1", 2, "a", 3.0, "c"], Deque[int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring typing.Deque[int] @ index 2"
]
assert repr(exc.value.exceptions[1]) == repr(
ValueError("invalid literal for int() with base 10: 'c'")
)
assert exc.value.exceptions[1].__notes__ == [
"Structuring typing.Deque[int] @ index 4"
]
def test_mapping_validation(converter):
"""Proper validation errors are raised structuring mappings."""
if converter.detailed_validation:
with pytest.raises(IterableValidationError) as exc:
converter.structure({"1": 1, "2": "b", "c": 3}, Dict[int, int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'b'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring mapping value @ key '2'"
]
assert repr(exc.value.exceptions[1]) == repr(
ValueError("invalid literal for int() with base 10: 'c'")
)
assert exc.value.exceptions[1].__notes__ == [
"Structuring mapping key @ key 'c'"
]
else:
with pytest.raises(ValueError):
converter.structure({"1": 1, "2": "b", "c": 3}, Dict[int, int])
@given(...)
def test_counter_validation(detailed_validation: bool):
"""Proper validation errors are raised structuring counters."""
c = Converter(detailed_validation=detailed_validation)
if detailed_validation:
with pytest.raises(IterableValidationError) as exc:
c.structure({"a": 1, "b": "b", "c": 3}, Counter[str])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'b'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring mapping value @ key 'b'"
]
else:
with pytest.raises(ValueError):
c.structure({"1": 1, "2": "b", "c": 3}, Counter[str])
def test_set_validation():
"""Proper validation errors are raised structuring sets."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure({"1", 2, "a"}, Set[int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == ["Structuring set @ element 'a'"]
def test_frozenset_validation():
"""Proper validation errors are raised structuring frozensets."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure({"1", 2, "a"}, FrozenSet[int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == ["Structuring frozenset @ element 'a'"]
def test_homo_tuple_validation():
"""Proper validation errors are raised structuring homogenous tuples."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure(["1", 2, "a"], Tuple[int, ...])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring typing.Tuple[int, ...] @ index 2"
]
def test_hetero_tuple_validation():
"""Proper validation errors are raised structuring heterogenous tuples."""
c = Converter(detailed_validation=True)
with pytest.raises(IterableValidationError) as exc:
c.structure(["1", 2, "a"], Tuple[int, int, int])
assert repr(exc.value.exceptions[0]) == repr(
ValueError("invalid literal for int() with base 10: 'a'")
)
assert exc.value.exceptions[0].__notes__ == [
"Structuring typing.Tuple[int, int, int] @ index 2"
]
def test_notes_pickling():
"""Validation notes should be picklable"""
note = pickle.loads( # noqa: S301
pickle.dumps(IterableValidationNote("foo", "key", str))
)
assert note == "foo"
assert note.index == "key"
assert note.type is str
note = pickle.loads( # noqa: S301
pickle.dumps(AttributeValidationNote("foo", "name", int))
)
assert note == "foo"
assert note.name == "name"
assert note.type is int
def test_error_derive():
"""Our ExceptionGroups should derive properly."""
c = Converter(detailed_validation=True)
@define
class Test:
a: int
b: str = field(validator=in_(["a", "b"]))
c: str
with pytest.raises(ClassValidationError) as exc:
c.structure({"a": "a", "b": "c"}, Test)
match, rest = exc.value.split(KeyError)
assert len(match.exceptions) == 1
assert len(rest.exceptions) == 1
assert match.cl == exc.value.cl
assert rest.cl == exc.value.cl
def test_iterable_note_grouping():
"""IterableValidationErrors can group their subexceptions by notes."""
exc1 = ValueError()
exc2 = KeyError()
exc3 = TypeError()
exc2.__notes__ = [note := IterableValidationNote("Test Note", 0, int)]
exc3.__notes__ = ["A string note"]
exc = IterableValidationError("Test", [exc1, exc2, exc3], list[int])
with_notes, without_notes = exc.group_exceptions()
assert with_notes == [(exc2, note)]
assert without_notes == [exc1, exc3]
def test_class_note_grouping():
"""ClassValidationErrors can group their subexceptions by notes."""
exc1 = ValueError()
exc2 = KeyError()
exc3 = TypeError()
exc2.__notes__ = [note := AttributeValidationNote("Test Note", "a", int)]
exc3.__notes__ = ["A string note"]
exc = ClassValidationError("Test", [exc1, exc2, exc3], int)
with_notes, without_notes = exc.group_exceptions()
assert with_notes == [(exc2, note)]
assert without_notes == [exc1, exc3]
|