-
Notifications
You must be signed in to change notification settings - Fork 196
/
test_dict.py
218 lines (180 loc) · 7.93 KB
/
test_dict.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
import re
from collections import OrderedDict
from collections.abc import Mapping
from typing import Any, Dict
import pytest
from dirty_equals import HasRepr, IsStr
from pydantic_core import SchemaValidator, ValidationError
from ..conftest import Err, PyAndJson
def test_dict(py_and_json: PyAndJson):
v = py_and_json({'type': 'dict', 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
assert v.validate_test({'1': 2, '3': 4}) == {1: 2, 3: 4}
v = py_and_json({'type': 'dict', 'strict': True, 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
assert v.validate_test({'1': 2, '3': 4}) == {1: 2, 3: 4}
assert v.validate_test({}) == {}
with pytest.raises(ValidationError, match='Input should be a valid dictionary'):
v.validate_test([])
@pytest.mark.parametrize(
'input_value,expected',
[
({'1': b'1', '2': b'2'}, {'1': '1', '2': '2'}),
(OrderedDict(a=b'1', b='2'), {'a': '1', 'b': '2'}),
({}, {}),
('foobar', Err("Input should be a valid dictionary [kind=dict_type, input_value='foobar', input_type=str]")),
([], Err('Input should be a valid dictionary [kind=dict_type,')),
([('x', 'y')], Err('Input should be a valid dictionary [kind=dict_type,')),
([('x', 'y'), ('z', 'z')], Err('Input should be a valid dictionary [kind=dict_type,')),
((), Err('Input should be a valid dictionary [kind=dict_type,')),
((('x', 'y'),), Err('Input should be a valid dictionary [kind=dict_type,')),
((type('Foobar', (), {'x': 1})()), Err('Input should be a valid dictionary [kind=dict_type,')),
],
ids=repr,
)
def test_dict_cases(input_value, expected):
v = SchemaValidator({'type': 'dict', 'keys_schema': 'str', 'values_schema': 'str'})
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
def test_dict_value_error(py_and_json: PyAndJson):
v = py_and_json({'type': 'dict', 'values_schema': 'int'})
assert v.validate_test({'a': 2, 'b': '4'}) == {'a': 2, 'b': 4}
with pytest.raises(ValidationError, match='Input should be a valid integer') as exc_info:
v.validate_test({'a': 2, 'b': 'wrong'})
assert exc_info.value.errors() == [
{
'kind': 'int_parsing',
'loc': ['b'],
'message': 'Input should be a valid integer, unable to parse string as an integer',
'input_value': 'wrong',
}
]
def test_dict_error_key_int():
v = SchemaValidator({'type': 'dict', 'values_schema': 'int'})
with pytest.raises(ValidationError, match='Input should be a valid integer') as exc_info:
v.validate_python({1: 2, 3: 'wrong'})
assert exc_info.value.errors() == [
{
'kind': 'int_parsing',
'loc': [3],
'message': 'Input should be a valid integer, unable to parse string as an integer',
'input_value': 'wrong',
}
]
def test_dict_error_key_other():
v = SchemaValidator({'type': 'dict', 'values_schema': 'int'})
with pytest.raises(ValidationError, match='Input should be a valid integer') as exc_info:
v.validate_python({1: 2, (1, 2): 'wrong'})
assert exc_info.value.errors() == [
{
'kind': 'int_parsing',
'loc': ['(1, 2)'],
'message': 'Input should be a valid integer, unable to parse string as an integer',
'input_value': 'wrong',
}
]
def test_dict_any_value():
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'str'}})
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'str'}})
assert v.validate_python({'1': 1, '2': 'a', '3': None}) == {'1': 1, '2': 'a', '3': None}
def test_mapping():
class MyMapping(Mapping):
def __init__(self, d):
self._d = d
def __getitem__(self, key):
return self._d[key]
def __iter__(self):
return iter(self._d)
def __len__(self):
return len(self._d)
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
assert v.validate_python(MyMapping({'1': 2, 3: '4'})) == {1: 2, 3: 4}
v = SchemaValidator(
{'type': 'dict', 'strict': True, 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}}
)
with pytest.raises(ValidationError, match='Input should be a valid dictionary'):
v.validate_python(MyMapping({'1': 2, 3: '4'}))
def test_key_error():
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
assert v.validate_python({'1': True}) == {1: 1}
with pytest.raises(ValidationError, match=re.escape('x -> [key]\n Input should be a valid integer')) as exc_info:
v.validate_python({'x': 1})
assert exc_info.value.errors() == [
{
'kind': 'int_parsing',
'loc': ['x', '[key]'],
'message': 'Input should be a valid integer, unable to parse string as an integer',
'input_value': 'x',
}
]
def test_mapping_error():
class BadMapping(Mapping):
def __getitem__(self, key):
raise None
def __iter__(self):
raise RuntimeError('intentional error')
def __len__(self):
return 1
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
with pytest.raises(ValidationError) as exc_info:
v.validate_python(BadMapping())
assert exc_info.value.errors() == [
{
'kind': 'dict_from_mapping',
'loc': [],
'message': 'Unable to convert mapping to a dictionary, error: RuntimeError: intentional error',
'input_value': HasRepr(IsStr(regex='.+BadMapping object at.+')),
'context': {'error': 'RuntimeError: intentional error'},
}
]
def test_mapping_error_yield_1():
class BadMapping(Mapping):
def items(self):
return [(1,)]
def __iter__(self):
return iter({1: 2})
def __getitem__(self, key):
raise None
def __len__(self):
return 1
v = SchemaValidator({'type': 'dict', 'keys_schema': {'type': 'int'}, 'values_schema': {'type': 'int'}})
with pytest.raises(ValidationError) as exc_info:
v.validate_python(BadMapping())
assert exc_info.value.errors() == [
{
'kind': 'dict_from_mapping',
'loc': [],
'message': (
'Unable to convert mapping to a dictionary, error: '
'ValueError: Expected tuple of length 2, but got tuple of length 1.'
),
'input_value': HasRepr(IsStr(regex='.+BadMapping object at.+')),
'context': {'error': 'ValueError: Expected tuple of length 2, but got tuple of length 1.'},
}
]
@pytest.mark.parametrize(
'kwargs,input_value,expected',
[
({}, {'1': 1, '2': 2}, {'1': 1, '2': 2}),
(
{'min_items': 3},
{'1': 1, '2': 2, '3': 3.0, '4': [1, 2, 3, 4]},
{'1': 1, '2': 2, '3': 3.0, '4': [1, 2, 3, 4]},
),
({'min_items': 3}, {1: '2', 3: '4'}, Err('Input should have at least 3 items, got 2 items [kind=too_short,')),
({'max_items': 4}, {'1': 1, '2': 2, '3': 3.0}, {'1': 1, '2': 2, '3': 3.0}),
(
{'max_items': 3},
{'1': 1, '2': 2, '3': 3.0, '4': [1, 2, 3, 4]},
Err('Input should have at most 3 items, got 4 items [kind=too_long,'),
),
],
)
def test_dict_length_constraints(kwargs: Dict[str, Any], input_value, expected):
v = SchemaValidator({'type': 'dict', **kwargs})
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