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(schema): JSON schema generation with a Literal of an enum member #2536

Merged
merged 2 commits into from May 9, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -794,6 +794,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

PrettyWood marked this conversation as resolved.
Show resolved Hide resolved
if is_literal_type(field_type):
values = all_literal_values(field_type)

Expand All @@ -810,8 +811,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)
PrettyWood marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -1784,6 +1784,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'],
}

PrettyWood marked this conversation as resolved.
Show resolved Hide resolved

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