Skip to content
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

fix: merge schemas in allOf #100

Merged
merged 1 commit into from
May 17, 2024
Merged
Show file tree
Hide file tree
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
5 changes: 5 additions & 0 deletions lmformatenforcer/jsonschemaparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ def get_parser(
if value_schema.anyOf:
parsers = [get_parser(parsing_state, schema) for schema in value_schema.anyOf]
return UnionParser(parsers)
if value_schema.allOf:
merged_schema = value_schema.allOf[0]
for schema in value_schema.allOf[1:]:
merged_schema = _merge_object_schemas(merged_schema, schema)
return get_parser(parsing_state, merged_schema)
if value_schema.extras and 'const' in value_schema.extras:
allowed_value = value_schema.extras['const']
is_string = type(allowed_value) == str
Expand Down
47 changes: 47 additions & 0 deletions tests/test_jsonschemaparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,53 @@ def test_any_json_object():
_test_json_schema_parsing_with_string('{"a": 1, "b": 2.2, "c": "c", "d": [1,2,3, null], "e": {"ee": 2}}', None, True)
_test_json_schema_parsing_with_string("true", None, True)
_test_json_schema_parsing_with_string('"str"', None, True)


def test_allof():
# Define a schema that includes allOf
allof_schema = {
"type": "object",
"allOf": [
{
"type": "object",
"properties": {
"num": {
"type": "number"
}
},
"required": ["num"]
},
{
"type": "object",
"properties": {
"str": {
"type": "string"
}
},
"required": ["str"]
}
]
}

# Valid cases
valid_test_strings = [
'{"num": 123, "str": "test"}',
'{"num": 0, "str": ""}'
]

# Invalid cases
invalid_test_strings = [
'{"num": 123}', # Missing 'str'
'{"str": "test"}', # Missing 'num'
'{"num": "123", "str": "test"}', # Invalid type for 'num'
'{"num": 123, "str": 456}' # Invalid type for 'str'
]

for test_string in valid_test_strings:
_test_json_schema_parsing_with_string(test_string, allof_schema, True)

for test_string in invalid_test_strings:
_test_json_schema_parsing_with_string(test_string, allof_schema, False)


def test_long_json_object():
Expand Down
Loading