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

[Feature] Constant elements in JSON schemas #886

Merged
merged 4 commits into from
Jun 6, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
4 changes: 4 additions & 0 deletions guidance/library/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,10 @@ def _gen_json(
reference=json_schema[REF_STRING], definitions=definitions
)

CONST_STRING = "const"
if CONST_STRING in json_schema:
return lm + _to_compact_json(json_schema[CONST_STRING])

ENUM_STRING = "enum"
if ENUM_STRING in json_schema:
return lm + _process_enum(options=json_schema["enum"])
Expand Down
56 changes: 56 additions & 0 deletions tests/library/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -1078,6 +1078,62 @@ def test_bad_prefix_enum(self, bad_obj, good_bytes, failure_byte, allowed_bytes)
)


class TestConst:
def test_constant_int(self):
# First sanity check what we're setting up
schema_obj = {"const": 1}
target_obj = 1
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)

def test_constant_string(self):
# First sanity check what we're setting up
schema_obj = {"const": "hello"}
target_obj = "hello"
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)

def test_constant_array(self):
# First sanity check what we're setting up
schema_obj = {"const": [1, 2, 3]}
target_obj = [1, 2, 3]
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)

def test_constant_object(self):
# First sanity check what we're setting up
schema_obj = {"const": {"a": 1, "b": 2}}
target_obj = {"a": 1, "b": 2}
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)

def test_nested_constant(self):
# First sanity check what we're setting up
schema_obj = {"type": "object", "properties": {"a": {"const": 1}}}
target_obj = {"a": 1}
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)

def test_type_specified_constant(self):
# First sanity check what we're setting up
schema_obj = {"type": "integer", "const": 1}
target_obj = 1
validate(instance=target_obj, schema=schema_obj)

# The actual check
generate_and_check(target_obj, schema_obj)


class TestAdditionalProperties:

simple_schema = """{
Expand Down
Loading