Skip to content

Commit 730adc3

Browse files
authored
add benchmark for root model validation (pydantic#1581)
1 parent 80756c1 commit 730adc3

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

tests/benchmarks/complete_schema.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,3 +340,22 @@ def input_data_wrong():
340340
'field_functions_model': {'field_before': 1, 'field_after': 1, 'field_wrap': 1, 'field_plain': 1},
341341
'field_recursive': {'name': 'foo', 'sub_branch': {'name': 'bar', 'sub_branch': {}}},
342342
}
343+
344+
345+
def wrap_schema_in_root_model(schema: dict) -> dict:
346+
class MyRootModel:
347+
# __slots__ is not required, but it avoids __pydantic_fields_set__ falling into __dict__
348+
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'
349+
350+
return {
351+
'type': 'model',
352+
'cls': MyRootModel,
353+
'config': {},
354+
'schema': {
355+
'type': 'model-fields',
356+
'fields': {
357+
'root': {'type': 'model-field', 'schema': schema},
358+
},
359+
},
360+
'root_model': True,
361+
}

tests/benchmarks/test_complete_benchmark.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
from pydantic_core import SchemaSerializer, SchemaValidator, ValidationError, validate_core_schema
1313

14-
from .complete_schema import input_data_lax, input_data_strict, input_data_wrong, schema
14+
from .complete_schema import input_data_lax, input_data_strict, input_data_wrong, schema, wrap_schema_in_root_model
1515

1616

1717
def test_complete_valid():
@@ -99,6 +99,12 @@ def test_complete_core_strict(benchmark):
9999
benchmark(v.validate_python, input_data_strict())
100100

101101

102+
@pytest.mark.benchmark(group='complete')
103+
def test_complete_core_root(benchmark):
104+
v = SchemaValidator(validate_core_schema(wrap_schema_in_root_model(schema())))
105+
benchmark(v.validate_python, {'root': input_data_lax()})
106+
107+
102108
@pytest.mark.benchmark(group='complete-to-python')
103109
def test_complete_core_serializer_to_python(benchmark):
104110
core_schema = validate_core_schema(schema())
@@ -160,6 +166,13 @@ def test_complete_core_json(benchmark):
160166
benchmark(v.validate_json, json_data)
161167

162168

169+
@pytest.mark.benchmark(group='complete-json')
170+
def test_complete_core_root_json(benchmark):
171+
v = SchemaValidator(validate_core_schema(wrap_schema_in_root_model(schema())))
172+
json_data = json.dumps({'root': input_data_lax()}, default=default_json_encoder)
173+
benchmark(v.validate_json, json_data)
174+
175+
163176
@pytest.mark.benchmark(group='build')
164177
def test_build_schema(benchmark):
165178
lax_schema = schema()

0 commit comments

Comments
 (0)