Skip to content

Commit 2e4134c

Browse files
mikeedjonesJONEMI21
and
JONEMI21
authored
Use core schema fns to initalize SchemaValidators in the test suite. (#1631)
Co-authored-by: JONEMI21 <[email protected]>
1 parent f1aaaaf commit 2e4134c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

51 files changed

+1752
-1915
lines changed

tests/benchmarks/test_micro_benchmarks.py

+145-144
Large diffs are not rendered by default.

tests/serializers/test_any.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,13 @@
1515
from dirty_equals import HasRepr, IsList
1616

1717
import pydantic_core
18-
from pydantic_core import PydanticSerializationError, SchemaSerializer, SchemaValidator, core_schema, to_json
18+
from pydantic_core import (
19+
PydanticSerializationError,
20+
SchemaSerializer,
21+
SchemaValidator,
22+
core_schema,
23+
to_json,
24+
)
1925

2026
from ..conftest import plain_repr
2127
from .test_dataclasses import IsStrictDict, on_pypy

tests/serializers/test_list_tuple.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,13 @@
44

55
import pytest
66

7-
from pydantic_core import PydanticSerializationError, SchemaError, SchemaSerializer, core_schema, validate_core_schema
7+
from pydantic_core import (
8+
PydanticSerializationError,
9+
SchemaError,
10+
SchemaSerializer,
11+
core_schema,
12+
validate_core_schema,
13+
)
814

915

1016
def test_list_any():

tests/serializers/test_simple.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
import pytest
55

6-
from pydantic_core import SchemaSerializer, core_schema
6+
from pydantic_core import CoreConfig, SchemaSerializer, core_schema
77

88
try:
99
import numpy
@@ -149,15 +149,15 @@ def test_numpy():
149149
(float('-inf'), 'null', {}),
150150
(float('nan'), 'null', {}),
151151
# explicit values of ser_json_inf_nan
152-
(float('inf'), 'null', {'ser_json_inf_nan': 'null'}),
153-
(float('-inf'), 'null', {'ser_json_inf_nan': 'null'}),
154-
(float('nan'), 'null', {'ser_json_inf_nan': 'null'}),
155-
(float('inf'), 'Infinity', {'ser_json_inf_nan': 'constants'}),
156-
(float('-inf'), '-Infinity', {'ser_json_inf_nan': 'constants'}),
157-
(float('nan'), 'NaN', {'ser_json_inf_nan': 'constants'}),
158-
(float('inf'), '"Infinity"', {'ser_json_inf_nan': 'strings'}),
159-
(float('-inf'), '"-Infinity"', {'ser_json_inf_nan': 'strings'}),
160-
(float('nan'), '"NaN"', {'ser_json_inf_nan': 'strings'}),
152+
(float('inf'), 'null', CoreConfig(ser_json_inf_nan='null')),
153+
(float('-inf'), 'null', CoreConfig(ser_json_inf_nan='null')),
154+
(float('nan'), 'null', CoreConfig(ser_json_inf_nan='null')),
155+
(float('inf'), 'Infinity', CoreConfig(ser_json_inf_nan='constants')),
156+
(float('-inf'), '-Infinity', CoreConfig(ser_json_inf_nan='constants')),
157+
(float('nan'), 'NaN', CoreConfig(ser_json_inf_nan='constants')),
158+
(float('inf'), '"Infinity"', CoreConfig(ser_json_inf_nan='strings')),
159+
(float('-inf'), '"-Infinity"', CoreConfig(ser_json_inf_nan='strings')),
160+
(float('nan'), '"NaN"', CoreConfig(ser_json_inf_nan='strings')),
161161
],
162162
)
163163
def test_float_inf_and_nan_serializers(value, expected_json, config):

tests/test_build.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def test_build_error_deep():
2828

2929

3030
def test_schema_as_string():
31-
v = SchemaValidator({'type': 'bool'})
31+
v = SchemaValidator(cs.bool_schema())
3232
assert v.validate_python('tRuE') is True
3333

3434

@@ -53,7 +53,7 @@ def test_schema_wrong_type(pydantic_version):
5353

5454
@pytest.mark.parametrize('pickle_protocol', range(1, pickle.HIGHEST_PROTOCOL + 1))
5555
def test_pickle(pickle_protocol: int) -> None:
56-
v1 = SchemaValidator({'type': 'bool'})
56+
v1 = SchemaValidator(cs.bool_schema())
5757
assert v1.validate_python('tRuE') is True
5858
p = pickle.dumps(v1, protocol=pickle_protocol)
5959
v2 = pickle.loads(p)
@@ -98,7 +98,7 @@ def test_function_no_mode():
9898

9999
def test_try_self_schema_discriminator():
100100
"""Trying to use self-schema when it shouldn't be used"""
101-
v = SchemaValidator({'type': 'tagged-union', 'choices': {'int': {'type': 'int'}}, 'discriminator': 'self-schema'})
101+
v = SchemaValidator(cs.tagged_union_schema(choices={'int': cs.int_schema()}, discriminator='self-schema'))
102102
assert 'discriminator: LookupKey' in repr(v)
103103

104104

tests/test_config.py

+44-46
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,13 @@
55
from dirty_equals import FunctionCheck, HasAttributes, IsInstance
66

77
from pydantic_core import CoreConfig, SchemaValidator, ValidationError
8+
from pydantic_core import core_schema as cs
89

910
from .conftest import Err, plain_repr
1011

1112

1213
def test_on_field():
13-
v = SchemaValidator({'type': 'str', 'min_length': 2, 'max_length': 5})
14+
v = SchemaValidator(cs.str_schema(min_length=2, max_length=5))
1415
r = plain_repr(v)
1516
assert 'min_length:Some(2)' in r
1617
assert 'max_length:Some(5)' in r
@@ -19,14 +20,14 @@ def test_on_field():
1920

2021

2122
def test_on_config():
22-
v = SchemaValidator({'type': 'str'}, {'str_max_length': 5})
23+
v = SchemaValidator(cs.str_schema(), config=CoreConfig(str_max_length=5))
2324
assert 'max_length:Some(5)' in plain_repr(v)
2425
assert v.isinstance_python('test') is True
2526
assert v.isinstance_python('test long') is False
2627

2728

2829
def test_field_priority_arg():
29-
v = SchemaValidator({'type': 'str', 'max_length': 5}, {'str_max_length': 10})
30+
v = SchemaValidator(cs.str_schema(max_length=5), config=CoreConfig(str_max_length=10))
3031
assert 'max_length:Some(5)' in plain_repr(v)
3132
assert v.isinstance_python('test') is True
3233
assert v.isinstance_python('test long') is False
@@ -39,12 +40,11 @@ class MyModel:
3940

4041
def test_on_model_class():
4142
v = SchemaValidator(
42-
{
43-
'type': 'model',
44-
'cls': MyModel,
45-
'config': {'str_max_length': 5},
46-
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
47-
}
43+
cs.model_schema(
44+
cls=MyModel,
45+
config=CoreConfig(str_max_length=5),
46+
schema=cs.model_fields_schema(fields={'f': cs.model_field(schema=cs.str_schema())}),
47+
)
4848
)
4949
assert 'max_length:Some(5)' in plain_repr(v)
5050
assert v.isinstance_python({'f': 'test'}) is True
@@ -53,15 +53,11 @@ def test_on_model_class():
5353

5454
def test_field_priority_model():
5555
v = SchemaValidator(
56-
{
57-
'type': 'model',
58-
'cls': MyModel,
59-
'config': {'str_max_length': 10},
60-
'schema': {
61-
'type': 'model-fields',
62-
'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str', 'max_length': 5}}},
63-
},
64-
}
56+
cs.model_schema(
57+
cls=MyModel,
58+
config=CoreConfig(str_max_length=10),
59+
schema=cs.model_fields_schema(fields={'f': cs.model_field(schema=cs.str_schema(max_length=5))}),
60+
)
6561
)
6662
assert 'max_length:Some(5)' in plain_repr(v)
6763
assert v.isinstance_python({'f': 'test'}) is True
@@ -71,29 +67,34 @@ def test_field_priority_model():
7167
@pytest.mark.parametrize(
7268
'config,float_field_schema,input_value,expected',
7369
[
74-
({}, {'type': 'float'}, {'x': 'nan'}, IsInstance(MyModel) & HasAttributes(x=FunctionCheck(math.isnan))),
7570
(
76-
{'allow_inf_nan': True},
77-
{'type': 'float'},
71+
CoreConfig(),
72+
cs.float_schema(),
7873
{'x': 'nan'},
7974
IsInstance(MyModel) & HasAttributes(x=FunctionCheck(math.isnan)),
8075
),
8176
(
82-
{'allow_inf_nan': False},
83-
{'type': 'float'},
77+
CoreConfig(allow_inf_nan=True),
78+
cs.float_schema(),
79+
{'x': 'nan'},
80+
IsInstance(MyModel) & HasAttributes(x=FunctionCheck(math.isnan)),
81+
),
82+
(
83+
CoreConfig(allow_inf_nan=False),
84+
cs.float_schema(),
8485
{'x': 'nan'},
8586
Err('Input should be a finite number [type=finite_number,'),
8687
),
8788
# field `allow_inf_nan` (if set) should have priority over global config
8889
(
89-
{'allow_inf_nan': True},
90-
{'type': 'float', 'allow_inf_nan': False},
90+
CoreConfig(allow_inf_nan=True),
91+
cs.float_schema(allow_inf_nan=False),
9192
{'x': 'nan'},
9293
Err('Input should be a finite number [type=finite_number,'),
9394
),
9495
(
95-
{'allow_inf_nan': False},
96-
{'type': 'float', 'allow_inf_nan': True},
96+
CoreConfig(allow_inf_nan=False),
97+
cs.float_schema(allow_inf_nan=True),
9798
{'x': 'nan'},
9899
IsInstance(MyModel) & HasAttributes(x=FunctionCheck(math.isnan)),
99100
),
@@ -102,12 +103,11 @@ def test_field_priority_model():
102103
)
103104
def test_allow_inf_nan(config: CoreConfig, float_field_schema, input_value, expected):
104105
v = SchemaValidator(
105-
{
106-
'type': 'model',
107-
'cls': MyModel,
108-
'schema': {'type': 'model-fields', 'fields': {'x': {'type': 'model-field', 'schema': float_field_schema}}},
109-
'config': config,
110-
}
106+
cs.model_schema(
107+
cls=MyModel,
108+
schema=cs.model_fields_schema(fields={'x': cs.model_field(schema=float_field_schema)}),
109+
config=config,
110+
)
111111
)
112112
if isinstance(expected, Err):
113113
with pytest.raises(ValidationError, match=re.escape(expected.message)):
@@ -120,34 +120,32 @@ def test_allow_inf_nan(config: CoreConfig, float_field_schema, input_value, expe
120120
@pytest.mark.parametrize(
121121
'config,input_str',
122122
(
123-
({}, 'type=string_type, input_value=123, input_type=int'),
124-
({'hide_input_in_errors': False}, 'type=string_type, input_value=123, input_type=int'),
125-
({'hide_input_in_errors': True}, 'type=string_type'),
123+
(CoreConfig(), 'type=string_type, input_value=123, input_type=int'),
124+
(CoreConfig(hide_input_in_errors=False), 'type=string_type, input_value=123, input_type=int'),
125+
(CoreConfig(hide_input_in_errors=True), 'type=string_type'),
126126
),
127127
)
128128
def test_hide_input_in_errors(config, input_str):
129129
v = SchemaValidator(
130-
{
131-
'type': 'model',
132-
'cls': MyModel,
133-
'schema': {'type': 'model-fields', 'fields': {'f': {'type': 'model-field', 'schema': {'type': 'str'}}}},
134-
},
135-
config,
130+
cs.model_schema(
131+
cls=MyModel, schema=cs.model_fields_schema(fields={'f': cs.model_field(schema=cs.str_schema())})
132+
),
133+
config=config,
136134
)
137135

138136
with pytest.raises(ValidationError, match=re.escape(f'Input should be a valid string [{input_str}]')):
139137
assert v.validate_python({'f': 123})
140138

141139

142140
def test_cache_strings():
143-
v = SchemaValidator({'type': 'str'})
141+
v = SchemaValidator(cs.str_schema())
144142
assert 'cache_strings=True' in plain_repr(v)
145143

146-
v = SchemaValidator({'type': 'str'}, {'cache_strings': True})
144+
v = SchemaValidator(cs.str_schema(), config=CoreConfig(cache_strings=True))
147145
assert 'cache_strings=True' in plain_repr(v)
148146

149-
v = SchemaValidator({'type': 'str'}, {'cache_strings': False})
147+
v = SchemaValidator(cs.str_schema(), config=CoreConfig(cache_strings=False))
150148
assert 'cache_strings=False' in plain_repr(v)
151149

152-
v = SchemaValidator({'type': 'str'}, {'cache_strings': 'keys'})
150+
v = SchemaValidator(cs.str_schema(), config=CoreConfig(cache_strings='keys'))
153151
assert "cache_strings='keys'" in plain_repr(v)

tests/test_errors.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -539,7 +539,7 @@ def test_all_errors():
539539

540540
@pytest.mark.skipif(sys.version_info < (3, 11), reason='This is the modern version used post 3.10.')
541541
def test_validation_error_cause_contents():
542-
enabled_config: CoreConfig = {'validation_error_cause': True}
542+
enabled_config: CoreConfig = CoreConfig(validation_error_cause=True)
543543

544544
def multi_raise_py_error(v: Any) -> Any:
545545
try:
@@ -605,7 +605,7 @@ def outer_raise_py_error(v: Any) -> Any:
605605
def test_validation_error_cause_contents_legacy():
606606
from exceptiongroup import BaseExceptionGroup
607607

608-
enabled_config: CoreConfig = {'validation_error_cause': True}
608+
enabled_config: CoreConfig = CoreConfig(validation_error_cause=True)
609609

610610
def multi_raise_py_error(v: Any) -> Any:
611611
try:
@@ -683,10 +683,10 @@ class CauseResult(enum.Enum):
683683
[ # Without the backport should still work after 3.10 as not needed:
684684
(
685685
'Enabled',
686-
{'validation_error_cause': True},
686+
CoreConfig(validation_error_cause=True),
687687
CauseResult.CAUSE if sys.version_info >= (3, 11) else CauseResult.IMPORT_ERROR,
688688
),
689-
('Disabled specifically', {'validation_error_cause': False}, CauseResult.NO_CAUSE),
689+
('Disabled specifically', CoreConfig(validation_error_cause=False), CauseResult.NO_CAUSE),
690690
('Disabled implicitly', {}, CauseResult.NO_CAUSE),
691691
],
692692
)
@@ -721,7 +721,7 @@ def singular_raise_py_error(v: Any) -> Any:
721721
def test_validation_error_cause_traceback_preserved():
722722
"""Makes sure historic bug of traceback being lost is fixed."""
723723

724-
enabled_config: CoreConfig = {'validation_error_cause': True}
724+
enabled_config: CoreConfig = CoreConfig(validation_error_cause=True)
725725

726726
def singular_raise_py_error(v: Any) -> Any:
727727
raise ValueError('Oh no!')
@@ -749,7 +749,7 @@ def __repr__(self):
749749

750750

751751
def test_error_on_repr(pydantic_version):
752-
s = SchemaValidator({'type': 'int'})
752+
s = SchemaValidator(core_schema.int_schema())
753753
with pytest.raises(ValidationError) as exc_info:
754754
s.validate_python(BadRepr())
755755

@@ -775,7 +775,7 @@ def test_error_on_repr(pydantic_version):
775775

776776

777777
def test_error_json(pydantic_version):
778-
s = SchemaValidator({'type': 'str', 'min_length': 3})
778+
s = SchemaValidator(core_schema.str_schema(min_length=3))
779779
with pytest.raises(ValidationError) as exc_info:
780780
s.validate_python('12')
781781

@@ -853,7 +853,7 @@ def raise_py_error(v: Any) -> Any:
853853

854854

855855
def test_error_json_cycle():
856-
s = SchemaValidator({'type': 'str', 'min_length': 3})
856+
s = SchemaValidator(core_schema.str_schema(min_length=3))
857857
cycle = []
858858
cycle.append(cycle)
859859
msg = '[type=string_type, input_value=[[...]], input_type=list]'
@@ -875,7 +875,7 @@ def __str__(self):
875875

876876

877877
def test_error_json_unknown():
878-
s = SchemaValidator({'type': 'str'})
878+
s = SchemaValidator(core_schema.str_schema())
879879
with pytest.raises(ValidationError) as exc_info:
880880
s.validate_python(Foobar())
881881

@@ -1089,7 +1089,7 @@ def test_loc_with_dots(pydantic_version):
10891089

10901090

10911091
def test_hide_input_in_error() -> None:
1092-
s = SchemaValidator({'type': 'int'})
1092+
s = SchemaValidator(core_schema.int_schema())
10931093
with pytest.raises(ValidationError) as exc_info:
10941094
s.validate_python('definitely not an int')
10951095

@@ -1098,7 +1098,7 @@ def test_hide_input_in_error() -> None:
10981098

10991099

11001100
def test_hide_input_in_json() -> None:
1101-
s = SchemaValidator({'type': 'int'})
1101+
s = SchemaValidator(core_schema.int_schema())
11021102
with pytest.raises(ValidationError) as exc_info:
11031103
s.validate_python('definitely not an int')
11041104

@@ -1111,7 +1111,7 @@ def test_hide_input_in_json() -> None:
11111111
reason='PyPy before 3.9 cannot pickle this correctly',
11121112
)
11131113
def test_validation_error_pickle() -> None:
1114-
s = SchemaValidator({'type': 'int'})
1114+
s = SchemaValidator(core_schema.int_schema())
11151115
with pytest.raises(ValidationError) as exc_info:
11161116
s.validate_python('definitely not an int')
11171117

@@ -1122,7 +1122,7 @@ def test_validation_error_pickle() -> None:
11221122

11231123
@pytest.mark.skipif('PYDANTIC_ERRORS_INCLUDE_URL' in os.environ, reason="can't test when envvar is set")
11241124
def test_errors_include_url() -> None:
1125-
s = SchemaValidator({'type': 'int'})
1125+
s = SchemaValidator(core_schema.int_schema())
11261126
with pytest.raises(ValidationError) as exc_info:
11271127
s.validate_python('definitely not an int')
11281128
assert 'https://errors.pydantic.dev' in repr(exc_info.value)
@@ -1149,7 +1149,7 @@ def test_errors_include_url_envvar(env_var, env_var_value, expected_to_have_url)
11491149
Since it can only be set before `ValidationError.__repr__()` is first called,
11501150
we need to spawn a subprocess to test it.
11511151
"""
1152-
code = "import pydantic_core; pydantic_core.SchemaValidator({'type': 'int'}).validate_python('ooo')"
1152+
code = "import pydantic_core; from pydantic_core import core_schema; pydantic_core.SchemaValidator(core_schema.int_schema()).validate_python('ooo')"
11531153
env = os.environ.copy()
11541154
env.pop('PYDANTIC_ERRORS_OMIT_URL', None) # in case the ambient environment has it set
11551155
if env_var_value is not None:

0 commit comments

Comments
 (0)