Skip to content

Commit

Permalink
support enum in array (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
koxudaxi authored Jun 12, 2020
1 parent af9df2e commit abde9b4
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 2 deletions.
4 changes: 2 additions & 2 deletions datamodel_code_generator/parser/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
7 changes: 7 additions & 0 deletions datamodel_code_generator/parser/jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Expand Down
18 changes: 18 additions & 0 deletions tests/data/openapi/array_enum.yaml
Original file line number Diff line number Diff line change
@@ -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
41 changes: 41 additions & 0 deletions tests/parser/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit abde9b4

Please sign in to comment.