Skip to content

Commit

Permalink
fix(schema): fix schema generation with multiple Enums having the sam…
Browse files Browse the repository at this point in the history
…e name (#2226)

closes #1857
  • Loading branch information
PrettyWood committed Jan 2, 2021
1 parent 43308d1 commit 13a5c7d
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/1857-PrettyWood.md
@@ -0,0 +1 @@
fix schema generation with multiple Enums having the same name
2 changes: 1 addition & 1 deletion pydantic/schema.py
Expand Up @@ -791,7 +791,7 @@ def field_singleton_schema( # noqa: C901 (ignore complexity)
f_schema['const'] = literal_value

if lenient_issubclass(field_type, Enum):
enum_name = normalize_name(field_type.__name__)
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))
definitions[enum_name] = enum_process_schema(field_type)
Expand Down
52 changes: 52 additions & 0 deletions tests/test_schema.py
Expand Up @@ -2097,3 +2097,55 @@ class Model(BaseModel):
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
}


def test_multiple_enums_with_same_name(create_module):
module_1 = create_module(
# language=Python
"""
from enum import Enum
from pydantic import BaseModel
class MyEnum(str, Enum):
a = 'a'
b = 'b'
c = 'c'
class MyModel(BaseModel):
my_enum_1: MyEnum
"""
)

module_2 = create_module(
# language=Python
"""
from enum import Enum
from pydantic import BaseModel
class MyEnum(str, Enum):
d = 'd'
e = 'e'
f = 'f'
class MyModel(BaseModel):
my_enum_2: MyEnum
"""
)

class Model(BaseModel):
my_model_1: module_1.MyModel
my_model_2: module_2.MyModel

assert len(Model.schema()['definitions']) == 4
assert set(Model.schema()['definitions']) == {
f'{module_1.__name__}__MyEnum',
f'{module_1.__name__}__MyModel',
f'{module_2.__name__}__MyEnum',
f'{module_2.__name__}__MyModel',
}

0 comments on commit 13a5c7d

Please sign in to comment.