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
|
import re
from collections import deque
from typing import Any
import pytest
from pydantic_core import SchemaValidator, ValidationError
from pydantic_core import core_schema as cs
from ..conftest import Err, PyAndJson, infinite_generator
@pytest.mark.parametrize(
'input_value,expected',
[
([], set()),
([1, 2, 3], {1, 2, 3}),
([1, 2, '3'], {1, 2, 3}),
([1, 2, 3, 2, 3], {1, 2, 3}),
(5, Err('[type=set_type, input_value=5, input_type=int]')),
],
)
def test_set_ints_both(py_and_json: PyAndJson, input_value, expected):
v = py_and_json({'type': 'set', 'items_schema': {'type': 'int'}})
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)):
v.validate_test(input_value)
else:
assert v.validate_test(input_value) == expected
@pytest.mark.parametrize('input_value,expected', [([1, 2.5, '3'], {1, 2.5, '3'})])
def test_set_no_validators_both(py_and_json: PyAndJson, input_value, expected):
v = py_and_json({'type': 'set'})
assert v.validate_test(input_value) == expected
@pytest.mark.parametrize(
'input_value,expected',
[
([1, 2.5, '3'], {1, 2.5, '3'}),
('foo', Err('[type=set_type, input_value=foo, input_type=str]')),
(1, Err('[type=set_type, input_value=1.0, input_type=float]')),
(1.0, Err('[type=set_type, input_value=1.0, input_type=float]')),
(False, Err('[type=set_type, input_value=False, input_type=bool]')),
],
)
def test_frozenset_no_validators_both(py_and_json: PyAndJson, input_value, expected):
v = py_and_json({'type': 'set'})
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=expected.message):
v.validate_test(input_value)
else:
assert v.validate_test(input_value) == expected
@pytest.mark.parametrize(
'input_value,expected',
[
({1, 2, 3}, {1, 2, 3}),
(set(), set()),
([1, 2, 3, 2, 3], {1, 2, 3}),
([], set()),
((1, 2, 3, 2, 3), {1, 2, 3}),
((), set()),
(frozenset([1, 2, 3, 2, 3]), {1, 2, 3}),
(deque((1, 2, '3')), {1, 2, 3}),
({1: 10, 2: 20, '3': '30'}.keys(), {1, 2, 3}),
({1: 10, 2: 20, '3': '30'}.values(), {10, 20, 30}),
({1: 10, 2: 20, '3': '30'}, Err('Input should be a valid set [type=set_type,')),
((x for x in [1, 2, '3']), {1, 2, 3}),
({'abc'}, Err('0\n Input should be a valid integer')),
({1: 2}, Err('1 validation error for set[int]\n Input should be a valid set')),
('abc', Err('Input should be a valid set')),
],
)
@pytest.mark.thread_unsafe # generators in parameters not compatible with pytest-run-parallel, https://github.com/Quansight-Labs/pytest-run-parallel/issues/14
def test_set_ints_python(input_value, expected):
v = SchemaValidator(cs.set_schema(items_schema=cs.int_schema()))
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)):
v.validate_python(input_value)
else:
assert v.validate_python(input_value) == expected
@pytest.mark.parametrize('input_value,expected', [([1, 2.5, '3'], {1, 2.5, '3'}), ([(1, 2), (3, 4)], {(1, 2), (3, 4)})])
def test_set_no_validators_python(input_value, expected):
v = SchemaValidator(cs.set_schema())
assert v.validate_python(input_value) == expected
def test_set_multiple_errors():
v = SchemaValidator(cs.set_schema(items_schema=cs.int_schema()))
with pytest.raises(ValidationError) as exc_info:
v.validate_python(['a', (1, 2), []])
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': (0,),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
},
{'type': 'int_type', 'loc': (1,), 'msg': 'Input should be a valid integer', 'input': (1, 2)},
{'type': 'int_type', 'loc': (2,), 'msg': 'Input should be a valid integer', 'input': []},
]
def test_list_with_unhashable_items():
v = SchemaValidator(cs.set_schema())
class Unhashable:
__hash__ = None
unhashable = Unhashable()
with pytest.raises(ValidationError) as exc_info:
v.validate_python([{'a': 'b'}, unhashable])
assert exc_info.value.errors(include_url=False) == [
{'type': 'set_item_not_hashable', 'loc': (0,), 'msg': 'Set items should be hashable', 'input': {'a': 'b'}},
{'type': 'set_item_not_hashable', 'loc': (1,), 'msg': 'Set items should be hashable', 'input': unhashable},
]
def generate_repeats():
for i in 1, 2, 3:
yield i
yield i
@pytest.mark.parametrize(
'kwargs,input_value,expected',
[
({'strict': True}, {1, 2, 3}, {1, 2, 3}),
({'strict': True}, set(), set()),
({'strict': True}, [1, 2, 3, 2, 3], Err('Input should be a valid set [type=set_type,')),
({'strict': True}, [], Err('Input should be a valid set [type=set_type,')),
({'strict': True}, (), Err('Input should be a valid set [type=set_type,')),
({'strict': True}, (1, 2, 3), Err('Input should be a valid set [type=set_type,')),
({'strict': True}, frozenset([1, 2, 3]), Err('Input should be a valid set [type=set_type,')),
({'strict': True}, 'abc', Err('Input should be a valid set [type=set_type,')),
({'min_length': 3}, {1, 2, 3}, {1, 2, 3}),
({'min_length': 3}, {1, 2}, Err('Set should have at least 3 items after validation, not 2 [type=too_short,')),
(
{'max_length': 3},
{1, 2, 3, 4},
Err('Set should have at most 3 items after validation, not more [type=too_long,'),
),
(
{'max_length': 3},
[1, 2, 3, 4],
Err('Set should have at most 3 items after validation, not more [type=too_long,'),
),
({'max_length': 3, 'items_schema': {'type': 'int'}}, {1, 2, 3, 4}, Err('type=too_long,')),
({'max_length': 3, 'items_schema': {'type': 'int'}}, [1, 2, 3, 4], Err('type=too_long,')),
# length check after set creation
({'max_length': 3}, [1, 1, 2, 2, 3, 3], {1, 2, 3}),
({'max_length': 3}, generate_repeats(), {1, 2, 3}),
(
{'max_length': 3},
infinite_generator(),
Err('Set should have at most 3 items after validation, not more [type=too_long,'),
),
],
ids=repr,
)
@pytest.mark.thread_unsafe # generators in parameters not compatible with pytest-run-parallel, https://github.com/Quansight-Labs/pytest-run-parallel/issues/14
def test_set_kwargs(kwargs: dict[str, Any], input_value, expected):
v = SchemaValidator(cs.set_schema(**kwargs))
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)):
r = v.validate_python(input_value)
print(f'unexpected result: {r!r}')
else:
assert v.validate_python(input_value) == expected
@pytest.mark.parametrize('input_value,expected', [({1, 2, 3}, {1, 2, 3}), ([1, 2, 3], [1, 2, 3])])
def test_union_set_list(input_value, expected):
v = SchemaValidator(cs.union_schema(choices=[cs.set_schema(), cs.list_schema()]))
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)):
v.validate_python(input_value)
else:
assert v.validate_python(input_value) == expected
@pytest.mark.parametrize(
'input_value,expected',
[
({1, 2, 3}, {1, 2, 3}),
({'a', 'b', 'c'}, {'a', 'b', 'c'}),
(
[1, 'a'],
Err(
'2 validation errors for union',
errors=[
{
'type': 'int_type',
'loc': ('set[int]', 1),
'msg': 'Input should be a valid integer',
'input': 'a',
},
# second because validation on the string choice comes second
{
'type': 'string_type',
'loc': ('set[str]', 0),
'msg': 'Input should be a valid string',
'input': 1,
},
],
),
),
],
)
def test_union_set_int_set_str(input_value, expected):
v = SchemaValidator(
cs.union_schema(
choices=[
cs.set_schema(items_schema=cs.int_schema(strict=True)),
cs.set_schema(items_schema=cs.str_schema(strict=True)),
]
)
)
if isinstance(expected, Err):
with pytest.raises(ValidationError, match=re.escape(expected.message)) as exc_info:
v.validate_python(input_value)
if expected.errors is not None:
assert exc_info.value.errors(include_url=False) == expected.errors
else:
assert v.validate_python(input_value) == expected
def test_set_as_dict_keys(py_and_json: PyAndJson):
v = py_and_json({'type': 'dict', 'keys_schema': {'type': 'set'}, 'values_schema': {'type': 'int'}})
with pytest.raises(ValidationError, match=re.escape("[type=set_type, input_value='foo', input_type=str]")):
v.validate_test({'foo': 'bar'})
def test_generator_error():
def gen(error: bool):
yield 1
yield 2
if error:
raise RuntimeError('my error')
yield 3
v = SchemaValidator(cs.set_schema(items_schema=cs.int_schema()))
r = v.validate_python(gen(False))
assert r == {1, 2, 3}
assert isinstance(r, set)
msg = r'Error iterating over object, error: RuntimeError: my error \[type=iteration_error,'
with pytest.raises(ValidationError, match=msg):
v.validate_python(gen(True))
@pytest.mark.parametrize(
'input_value,items_schema,expected',
[
pytest.param(
{1: 10, 2: 20, '3': '30'}.items(),
{'type': 'tuple', 'items_schema': [{'type': 'any'}], 'variadic_item_index': 0},
{(1, 10), (2, 20), ('3', '30')},
id='Tuple[Any, Any]',
),
pytest.param(
{1: 10, 2: 20, '3': '30'}.items(),
{'type': 'tuple', 'items_schema': [{'type': 'int'}], 'variadic_item_index': 0},
{(1, 10), (2, 20), (3, 30)},
id='Tuple[int, int]',
),
pytest.param({1: 10, 2: 20, '3': '30'}.items(), {'type': 'any'}, {(1, 10), (2, 20), ('3', '30')}, id='Any'),
],
)
def test_set_from_dict_items(input_value, items_schema, expected):
v = SchemaValidator(cs.set_schema(items_schema=items_schema))
output = v.validate_python(input_value)
assert isinstance(output, set)
assert output == expected
@pytest.mark.parametrize(
'input_value,expected',
[
([], set()),
([1, '2', b'3'], {1, '2', b'3'}),
({1, '2', b'3'}, {1, '2', b'3'}),
(frozenset([1, '2', b'3']), {1, '2', b'3'}),
(deque([1, '2', b'3']), {1, '2', b'3'}),
],
)
def test_set_any(input_value, expected):
v = SchemaValidator(cs.set_schema())
output = v.validate_python(input_value)
assert output == expected
assert isinstance(output, set)
@pytest.mark.parametrize(
'fail_fast,expected',
[
pytest.param(
True,
[
{
'type': 'int_parsing',
'loc': (1,),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not-num',
},
],
id='fail_fast',
),
pytest.param(
False,
[
{
'type': 'int_parsing',
'loc': (1,),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'not-num',
},
{
'type': 'int_parsing',
'loc': (2,),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'again',
},
],
id='not_fail_fast',
),
],
)
def test_set_fail_fast(fail_fast, expected):
v = SchemaValidator(cs.set_schema(items_schema=cs.int_schema(), fail_fast=fail_fast))
with pytest.raises(ValidationError) as exc_info:
v.validate_python([1, 'not-num', 'again'])
assert exc_info.value.errors(include_url=False) == expected
|