Skip to content

Commit

Permalink
Fix "parent" AttributeError when calling --collapse-root-models (#1432)
Browse files Browse the repository at this point in the history
Fixes #1419
  • Loading branch information
imankulov authored Jul 20, 2023
1 parent 8691002 commit a0a6cd6
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 1 deletion.
4 changes: 3 additions & 1 deletion datamodel_code_generator/parser/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,9 @@ def __collapse_root_models(
data_type.remove_reference()

root_type_model.reference.children = [
c for c in root_type_model.reference.children if c.parent
c
for c in root_type_model.reference.children
if getattr(c, 'parent', None)
]

if not root_type_model.reference.children:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# generated by datamodel-codegen:
# filename: flat_type.jsonschema
# timestamp: 2019-07-26T00:00:00+00:00

from __future__ import annotations

from typing import Optional

from pydantic import BaseModel


class FooModel(BaseModel):
foo: Optional[str] = None
16 changes: 16 additions & 0 deletions tests/data/openapi/flat_type.jsonschema
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"title": "Foo",
"$schema": "http://json-schema.org/schema#",
"description": "",
"type": "object",
"properties": {
"foo": {
"$ref": "#/definitions/foo"
}
},
"definitions": {
"foo": {
"type": "string"
}
}
}
25 changes: 25 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4339,6 +4339,31 @@ def test_main_collapse_root_models_field_constraints():
)


@freeze_time('2019-07-26')
def test_main_collapse_root_models_with_references_to_flat_types():
with TemporaryDirectory() as output_dir:
output_file: Path = Path(output_dir) / 'output.py'
return_code: Exit = main(
[
'--input',
str(OPEN_API_DATA_PATH / 'flat_type.jsonschema'),
'--output',
str(output_file),
'--collapse-root-models',
]
)

assert return_code == Exit.OK
assert (
output_file.read_text()
== (
EXPECTED_MAIN_PATH
/ 'main_collapse_root_models_with_references_to_flat_types'
/ 'output.py'
).read_text()
)


@freeze_time('2019-07-26')
def test_main_openapi_max_items_enum():
with TemporaryDirectory() as output_dir:
Expand Down

0 comments on commit a0a6cd6

Please sign in to comment.