Skip to content
Open
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
11 changes: 10 additions & 1 deletion schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -701,7 +701,16 @@ def _to_schema(s: Any, ignore_extra_keys: bool) -> Schema:
if schema.name and not title:
return_schema["title"] = schema.name

if flavor == TYPE:
if isinstance(s, Schema):
# A nested Schema instance (e.g. Const, or Schema(Schema(...)))
# carries its own constraints; expand it recursively instead of
# dropping it to an empty (match-anything) schema.
return_schema.update(
_json_schema(
s, is_main_schema=False, allow_reference=allow_reference
)
)
elif flavor == TYPE:
# Handle type
return_schema["type"] = _get_type_name(s)
elif flavor == ITERABLE:
Expand Down
32 changes: 32 additions & 0 deletions test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1009,6 +1009,38 @@ def test_json_schema_nested_schema():
}


def test_json_schema_const_and_nested_schema():
# Regression: a Const (or any Schema nested directly inside another Schema)
# wrapping a literal/type was dropped to an empty {} schema, which accepts
# anything and contradicts what Schema.validate() enforces. The generated
# JSON schema must preserve the constraint.
assert Schema(Const("fixed")).json_schema("my-id") == {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "my-id",
"const": "fixed",
}
assert Schema(Const(int)).json_schema("my-id") == {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "my-id",
"type": "integer",
}
# A Schema nested directly inside another Schema must expand, not vanish.
assert Schema(Schema(int)).json_schema("my-id") == {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "my-id",
"type": "integer",
}
# Const used as a dict value keeps its const in the property schema.
assert Schema({"role": Const("admin")}).json_schema("my-id") == {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "my-id",
"type": "object",
"properties": {"role": {"const": "admin"}},
"required": ["role"],
"additionalProperties": False,
}


def test_json_schema_optional_key():
s = Schema({Optional("test"): str})
assert s.json_schema("my-id") == {
Expand Down