Skip to content

Commit

Permalink
fix(schema): JSON schema generation with a Literal of an enum member (
Browse files Browse the repository at this point in the history
#2536)

Co-authored-by: Samuel Colvin <s@muelcolvin.com>
  • Loading branch information
PrettyWood and samuelcolvin committed May 11, 2021
1 parent 00c55be commit 2d9ab78
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/2536-PrettyWood.md
@@ -0,0 +1 @@
fix JSON schema generation with a `Literal` of an enum member
5 changes: 3 additions & 2 deletions pydantic/schema.py
Expand Up @@ -788,6 +788,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
f_schema: Dict[str, Any] = {}
if field.field_info is not None and field.field_info.const:
f_schema['const'] = field.default

field_type = field.type_
if is_literal_type(field_type):
values = all_literal_values(field_type)
Expand All @@ -805,8 +806,8 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
# All values have the same type
field_type = values[0].__class__
f_schema['enum'] = list(values)

if lenient_issubclass(field_type, Enum):
add_field_type_to_schema(field_type, f_schema)
elif lenient_issubclass(field_type, Enum):
enum_name = model_name_map[field_type]
f_schema, schema_overrides = get_field_info_schema(field)
f_schema.update(get_schema_ref(enum_name, ref_prefix, ref_template, schema_overrides))
Expand Down
16 changes: 16 additions & 0 deletions tests/test_schema.py
Expand Up @@ -1780,6 +1780,22 @@ class Model(BaseModel):
}


def test_literal_enum():
class MyEnum(str, Enum):
FOO = 'foo'
BAR = 'bar'

class Model(BaseModel):
kind: Literal[MyEnum.FOO]

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'kind': {'title': 'Kind', 'enum': ['foo'], 'type': 'string'}},
'required': ['kind'],
}


def test_color_type():
class Model(BaseModel):
color: Color
Expand Down

0 comments on commit 2d9ab78

Please sign in to comment.