Skip to content

Commit

Permalink
add benchmark for root model validation (#1581)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt authored Dec 12, 2024
1 parent 80756c1 commit 730adc3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
19 changes: 19 additions & 0 deletions tests/benchmarks/complete_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,22 @@ def input_data_wrong():
'field_functions_model': {'field_before': 1, 'field_after': 1, 'field_wrap': 1, 'field_plain': 1},
'field_recursive': {'name': 'foo', 'sub_branch': {'name': 'bar', 'sub_branch': {}}},
}


def wrap_schema_in_root_model(schema: dict) -> dict:
class MyRootModel:
# __slots__ is not required, but it avoids __pydantic_fields_set__ falling into __dict__
__slots__ = '__dict__', '__pydantic_fields_set__', '__pydantic_extra__', '__pydantic_private__'

return {
'type': 'model',
'cls': MyRootModel,
'config': {},
'schema': {
'type': 'model-fields',
'fields': {
'root': {'type': 'model-field', 'schema': schema},
},
},
'root_model': True,
}
15 changes: 14 additions & 1 deletion tests/benchmarks/test_complete_benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from pydantic_core import SchemaSerializer, SchemaValidator, ValidationError, validate_core_schema

from .complete_schema import input_data_lax, input_data_strict, input_data_wrong, schema
from .complete_schema import input_data_lax, input_data_strict, input_data_wrong, schema, wrap_schema_in_root_model


def test_complete_valid():
Expand Down Expand Up @@ -99,6 +99,12 @@ def test_complete_core_strict(benchmark):
benchmark(v.validate_python, input_data_strict())


@pytest.mark.benchmark(group='complete')
def test_complete_core_root(benchmark):
v = SchemaValidator(validate_core_schema(wrap_schema_in_root_model(schema())))
benchmark(v.validate_python, {'root': input_data_lax()})


@pytest.mark.benchmark(group='complete-to-python')
def test_complete_core_serializer_to_python(benchmark):
core_schema = validate_core_schema(schema())
Expand Down Expand Up @@ -160,6 +166,13 @@ def test_complete_core_json(benchmark):
benchmark(v.validate_json, json_data)


@pytest.mark.benchmark(group='complete-json')
def test_complete_core_root_json(benchmark):
v = SchemaValidator(validate_core_schema(wrap_schema_in_root_model(schema())))
json_data = json.dumps({'root': input_data_lax()}, default=default_json_encoder)
benchmark(v.validate_json, json_data)


@pytest.mark.benchmark(group='build')
def test_build_schema(benchmark):
lax_schema = schema()
Expand Down

0 comments on commit 730adc3

Please sign in to comment.