forked from pydantic/pydantic-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_misc.py
216 lines (173 loc) · 7.26 KB
/
test_misc.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
import copy
import pickle
import re
import pytest
from typing_extensions import get_args
from pydantic_core import CoreSchema, CoreSchemaType, PydanticUndefined, core_schema
from pydantic_core._pydantic_core import (
SchemaError,
SchemaValidator,
ValidationError,
__version__,
build_info,
build_profile,
)
@pytest.mark.parametrize('obj', [ValidationError, SchemaValidator, SchemaError])
def test_module(obj):
assert obj.__module__ == 'pydantic_core._pydantic_core'
def test_version():
assert isinstance(__version__, str)
assert '.' in __version__
def test_build_profile():
assert build_profile in ('debug', 'release')
def test_build_info():
assert isinstance(build_info, str)
def test_schema_error():
err = SchemaError('test')
assert isinstance(err, Exception)
assert str(err) == 'test'
assert repr(err) == 'SchemaError("test")'
def test_validation_error(pydantic_version):
v = SchemaValidator({'type': 'int'})
with pytest.raises(ValidationError) as exc_info:
v.validate_python(1.5)
assert exc_info.value.title == 'int'
assert exc_info.value.error_count() == 1
assert (
exc_info.value.errors(include_url=False)
== exc_info.value.errors(include_url=False, include_context=False)
== [
{
'type': 'int_from_float',
'loc': (),
'msg': 'Input should be a valid integer, got a number with a fractional part',
'input': 1.5,
}
]
)
# insert_assert(exc_info.value.errors())
assert exc_info.value.errors() == [
{
'type': 'int_from_float',
'loc': (),
'msg': 'Input should be a valid integer, got a number with a fractional part',
'input': 1.5,
'url': f'https://errors.pydantic.dev/{pydantic_version}/v/int_from_float',
}
]
def test_validation_error_include_context():
v = SchemaValidator({'type': 'list', 'max_length': 2})
with pytest.raises(ValidationError) as exc_info:
v.validate_python([1, 2, 3])
assert exc_info.value.title == 'list[any]'
assert exc_info.value.error_count() == 1
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'too_long',
'loc': (),
'msg': 'List should have at most 2 items after validation, not 3',
'input': [1, 2, 3],
'ctx': {'field_type': 'List', 'max_length': 2, 'actual_length': 3},
}
]
# insert_assert(exc_info.value.errors(include_url=False, include_context=False))
assert exc_info.value.errors(include_url=False, include_context=False) == [
{
'type': 'too_long',
'loc': (),
'msg': 'List should have at most 2 items after validation, not 3',
'input': [1, 2, 3],
}
]
def test_custom_title():
v = SchemaValidator({'type': 'int'}, {'title': 'MyInt'})
with pytest.raises(ValidationError) as exc_info:
v.validate_python(1.5)
assert exc_info.value.title == 'MyInt'
def test_validation_error_multiple(pydantic_version):
class MyModel:
# this is not required, but it avoids `__pydantic_fields_set__` being included in `__dict__`
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
field_a: str
field_b: int
v = SchemaValidator(
{
'type': 'model',
'cls': MyModel,
'schema': {
'type': 'model-fields',
'fields': {
'x': {'type': 'model-field', 'schema': {'type': 'float'}},
'y': {'type': 'model-field', 'schema': {'type': 'int'}},
},
},
}
)
with pytest.raises(ValidationError) as exc_info:
v.validate_python({'x': 'x' * 60, 'y': 'y'})
assert exc_info.value.title == 'MyModel'
assert exc_info.value.error_count() == 2
assert exc_info.value.errors(include_url=False) == [
{
'type': 'float_parsing',
'loc': ('x',),
'msg': 'Input should be a valid number, unable to parse string as a number',
'input': 'x' * 60,
},
{
'type': 'int_parsing',
'loc': ('y',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'y',
},
]
assert repr(exc_info.value) == (
'2 validation errors for MyModel\n'
'x\n'
' Input should be a valid number, unable to parse string as a number '
"[type=float_parsing, input_value='xxxxxxxxxxxxxxxxxxxxxxxx...xxxxxxxxxxxxxxxxxxxxxxx', input_type=str]\n"
f' For further information visit https://errors.pydantic.dev/{pydantic_version}/v/float_parsing\n'
'y\n'
' Input should be a valid integer, unable to parse string as an integer '
"[type=int_parsing, input_value='y', input_type=str]\n"
f' For further information visit https://errors.pydantic.dev/{pydantic_version}/v/int_parsing'
)
def test_core_schema_type_literal():
def get_type_value(schema):
type_ = schema.__annotations__['type']
m = re.search(r"Literal\['(.+?)']", type_.__forward_arg__)
assert m, f'Unknown schema type: {type_}'
return m.group(1)
schema_types = tuple(get_type_value(x) for x in CoreSchema.__args__)
schema_types = tuple(dict.fromkeys(schema_types)) # remove duplicates while preserving order
if get_args(CoreSchemaType) != schema_types:
literal = ''.join(f'\n {e!r},' for e in schema_types)
print(
f'python code (near end of python/pydantic_core/core_schema.py):\n\nCoreSchemaType = Literal[{literal}\n]'
)
pytest.fail('core_schema.CoreSchemaType needs to be updated')
def test_undefined():
with pytest.raises(NotImplementedError, match='UndefinedType'):
PydanticUndefined.__class__()
undefined_copy = copy.copy(PydanticUndefined)
undefined_deepcopy = copy.deepcopy(PydanticUndefined)
assert undefined_copy is PydanticUndefined
assert undefined_deepcopy is PydanticUndefined
assert pickle.loads(pickle.dumps(PydanticUndefined)) is PydanticUndefined
def test_unicode_error_input_repr() -> None:
"""https://github.com/pydantic/pydantic/issues/6448"""
schema = core_schema.int_schema()
validator = SchemaValidator(schema)
danger_str = 'ÿ' * 1000
expected = "1 validation error for int\n Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='ÿÿÿÿÿÿÿÿÿÿÿÿ...ÿÿÿÿÿÿÿÿÿÿÿ', input_type=str]"
with pytest.raises(ValidationError) as exc_info:
validator.validate_python(danger_str)
actual = repr(exc_info.value).split('For further information visit ')[0].strip()
assert expected == actual
def test_core_schema_import_field_validation_info():
with pytest.warns(DeprecationWarning, match='`FieldValidationInfo` is deprecated, use `ValidationInfo` instead.'):
core_schema.FieldValidationInfo
def test_core_schema_import_missing():
with pytest.raises(AttributeError, match="module 'pydantic_core' has no attribute 'foobar'"):
core_schema.foobar