Skip to content

Add tagged union benchmarks #656

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 1, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions tests/benchmarks/test_micro_benchmarks.py
Original file line number Diff line number Diff line change
Expand Up @@ -1410,3 +1410,43 @@ def test_int_range_json(benchmark):
v.validate_python('0')

benchmark(v.validate_json, '42')


@pytest.mark.benchmark(group='tagged_union_ints')
def test_tagged_union_int_keys_python(benchmark):
inner_schema = core_schema.typed_dict_schema(
{
'x': core_schema.typed_dict_field(core_schema.int_schema()),
'y': core_schema.typed_dict_field(core_schema.int_schema()),
}
)
v = SchemaValidator(core_schema.tagged_union_schema({x: inner_schema for x in range(1000)}, discriminator='x'))

payload = {'x': 999, 'y': '1'}
assert v.validate_python(payload) == {'x': 999, 'y': 1}
with pytest.raises(
ValidationError, match="Input tag '1001' found using 'x' does not match any of the expected tags"
):
v.validate_python({'x': 1001, 'y': '1'})

benchmark(v.validate_python, payload)


@pytest.mark.benchmark(group='tagged_union_ints')
def test_tagged_union_int_keys_json(benchmark):
inner_schema = core_schema.typed_dict_schema(
{
'x': core_schema.typed_dict_field(core_schema.int_schema()),
'y': core_schema.typed_dict_field(core_schema.int_schema()),
}
)
v = SchemaValidator(core_schema.tagged_union_schema({x: inner_schema for x in range(1000)}, discriminator='x'))

payload = '{"x": 999, "y": "1"}'
assert v.validate_json(payload) == {'x': 999, 'y': 1}
with pytest.raises(
ValidationError, match="Input tag '1001' found using 'x' does not match any of the expected tags"
):
v.validate_json('{"x": 1001, "y": "1"}')

benchmark(v.validate_json, payload)