Skip to content

Commit

Permalink
fix anyof in array fields (#146)
Browse files Browse the repository at this point in the history
  • Loading branch information
koxudaxi authored Jun 11, 2020
1 parent 762ac1b commit af9df2e
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 1 deletion.
5 changes: 4 additions & 1 deletion datamodel_code_generator/parser/jsonschema.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,8 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase]
fields: List[DataModelFieldBase] = []

for field_name, field in properties.items():
is_list = False
is_list: bool = False
is_union: bool = False
field_types: List[DataType]
field_name, alias = get_valid_field_name_and_alias(field_name)
if field.ref:
Expand All @@ -299,6 +300,7 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase]
)
field_types = array_fields[0].data_types
is_list = True
is_union = True
elif field.anyOf:
field_types = self.parse_any_of(field_name, field)
elif field.allOf:
Expand Down Expand Up @@ -341,6 +343,7 @@ def parse_object_fields(self, obj: JsonSchemaObject) -> List[DataModelFieldBase]
data_types=field_types,
required=required,
is_list=is_list,
is_union=is_union,
alias=alias,
)
)
Expand Down
27 changes: 27 additions & 0 deletions tests/data/openapi/nested_anyof.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
openapi: 3.0.0
info:
title: datamodel-code-generator bug example
components:
schemas:
Container:
allOf:
- type: object
required:
- contents
properties:
contents:
type: array
items:
anyOf:
- $ref: '#/components/schemas/Type1'
- $ref: '#/components/schemas/Type2'
Type1:
type: object
properties:
prop:
type: string
Type2:
type: object
properties:
prop:
type: string
29 changes: 29 additions & 0 deletions tests/parser/test_openapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,6 +845,35 @@ class Error(BaseModel):
)


def test_openapi_parser_parse_nested_anyof():
parser = OpenAPIParser(
BaseModel,
CustomRootType,
text=Path(DATA_PATH / 'nested_anyof.yaml').read_text(),
)
assert (
parser.parse()
== '''from __future__ import annotations
from typing import List, Optional, Union
from pydantic import BaseModel
class Type1(BaseModel):
prop: Optional[str] = None
class Type2(BaseModel):
prop: Optional[str] = None
class Container(BaseModel):
contents: List[Union[Type1, Type2]]
'''
)


def test_openapi_parser_parse_allof():
parser = OpenAPIParser(
BaseModel, CustomRootType, text=Path(DATA_PATH / 'allof.yaml').read_text()
Expand Down

0 comments on commit af9df2e

Please sign in to comment.