Skip to content

Commit

Permalink
Fixing #102 - Array of ENUMs Fails to Produce >1 Value
Browse files Browse the repository at this point in the history
noamgat committed May 17, 2024
1 parent 5461294 commit 4cbff42
Showing 2 changed files with 35 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lmformatenforcer/jsonschemaparser.py
Original file line number Diff line number Diff line change
@@ -102,6 +102,13 @@ def add_character(self, new_character: str) -> CharacterLevelParser:
if isinstance(finished_receiver, StringParsingState):
updated_parser.last_parsed_string = finished_receiver.parsed_string
del new_object_stack[-1]
if new_object_stack:
new_top_parser = new_object_stack[-1]
if isinstance(new_top_parser, ListParsingState):
new_top_parser = new_top_parser._clone()
new_top_parser.num_items_seen += 1
new_object_stack[-1] = new_top_parser


return updated_parser

@@ -657,7 +664,8 @@ def can_end(self) -> bool:

def get_allowed_control_characters(self):
num_items = self.num_items_seen
is_on_top = self.root.context.active_parser.object_stack[-1] == self
top_parser = self.root.context.active_parser.object_stack[-1]
is_on_top = top_parser == self or isinstance(top_parser, UnionParser) and self in top_parser.parsers
if (not is_on_top) and self.root.context.active_parser.last_non_whitespace_character != "[":
# If there is an active parser above us, and the last character is not [,
# there is an active item parser on the stack that we did not count yet.
26 changes: 26 additions & 0 deletions tests/test_jsonschemaparser.py
Original file line number Diff line number Diff line change
@@ -567,6 +567,32 @@ def test_top_level_array_object():
_test_json_schema_parsing_with_string(invalid_result, test_schema, False)


def test_arrays_with_multiple_enums():
schema = {
"properties": {
"array_of_numbers": {
"default": [],
"description": "An array of numbers",
"items": {
"type": "integer",
"enum": [1, 2, 3, 4, 5],
},
"title": "Items",
"type": "array",
"maxItems": 2
}
},
"required": ["array_of_numbers"],
"type": "object",
}

_test_json_schema_parsing_with_string('{"array_of_numbers":[4]}', schema, True)
_test_json_schema_parsing_with_string('{"array_of_numbers":[4, 1]}', schema, True)
_test_json_schema_parsing_with_string('{"array_of_numbers":[4, 4]}', schema, True)
_test_json_schema_parsing_with_string('{"array_of_numbers":[1, 2, 3]}', schema, False)
_test_json_schema_parsing_with_string('{"array_of_numbers":[6]}', schema, False)
_test_json_schema_parsing_with_string('{"array_of_numbers":[1, 6]}', schema, False)

@contextmanager
def _temp_replace_env_var(env_var_name, temp_value):
try:

0 comments on commit 4cbff42

Please sign in to comment.