diff --git a/datamodel_code_generator/parser/base.py b/datamodel_code_generator/parser/base.py index 318582946..1e1b8db1c 100644 --- a/datamodel_code_generator/parser/base.py +++ b/datamodel_code_generator/parser/base.py @@ -28,10 +28,10 @@ inflect_engine = inflect.engine() -def get_singular_name(name: str) -> str: +def get_singular_name(name: str, suffix: str = 'Item') -> str: singular_name = inflect_engine.singular_noun(name) if singular_name is False: - singular_name = f'{name}Item' + singular_name = f'{name}{suffix}' return singular_name diff --git a/datamodel_code_generator/parser/jsonschema.py b/datamodel_code_generator/parser/jsonschema.py index 9c0943f14..0dc15af75 100644 --- a/datamodel_code_generator/parser/jsonschema.py +++ b/datamodel_code_generator/parser/jsonschema.py @@ -395,6 +395,13 @@ def parse_array_fields( elif item.allOf: singular_name = get_singular_name(name) item_obj_data_types.extend(self.parse_all_of(singular_name, item)) + elif item.enum: + singular_name = get_singular_name(name, 'Enum') + enum = self.parse_enum(singular_name, item) + item_obj_data_types.append( + self.data_type(type=enum.name, ref=True, version_compatible=True) + ) + else: item_obj_data_types.extend(self.get_data_type(item)) diff --git a/tests/data/openapi/array_enum.yaml b/tests/data/openapi/array_enum.yaml new file mode 100644 index 000000000..b2ab6d7dd --- /dev/null +++ b/tests/data/openapi/array_enum.yaml @@ -0,0 +1,18 @@ +openapi: 3.0.0 +info: + title: datamodel-code-generator bug example +components: + schemas: + Type1: + type: array + items: + type: string + enum: + - enumOne + - enumTwo + + Type2: + type: string + enum: + - enumFour + - enumFive diff --git a/tests/parser/test_openapi.py b/tests/parser/test_openapi.py index 0350877c2..c4f7110b9 100644 --- a/tests/parser/test_openapi.py +++ b/tests/parser/test_openapi.py @@ -1558,3 +1558,44 @@ def test_openapi_parser_parse_additional_properties( base_class=base_class, ) assert parser.parse(with_import=with_import, format_=format_) == result + + +@pytest.mark.parametrize( + 'with_import, format_, base_class, result', + [ + ( + True, + True, + None, + '''from __future__ import annotations + +from enum import Enum +from typing import List + +from pydantic import BaseModel + + +class Type1Enum(Enum): + enumOne = 'enumOne' + enumTwo = 'enumTwo' + + +class Type1(BaseModel): + __root__: List[Type1Enum] + + +class Type2(Enum): + enumFour = 'enumFour' + enumFive = 'enumFive' +''', + ), + ], +) +def test_openapi_parser_parse_array_enum(with_import, format_, base_class, result): + parser = OpenAPIParser( + BaseModel, + CustomRootType, + text=Path(DATA_PATH / 'array_enum.yaml').read_text(), + base_class=base_class, + ) + assert parser.parse(with_import=with_import, format_=format_) == result