Skip to content

Commit b9cf6f9

Browse files
authored
Fix allOf handling to generate class definitions with descriptions instead of aliases (#2643)
1 parent 9ae7c0b commit b9cf6f9

4 files changed

Lines changed: 58 additions & 1 deletion

File tree

src/datamodel_code_generator/model/template/pydantic_v2/BaseModel.jinja2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
{% if base_class != "BaseModel" and "," not in base_class and not fields and not config -%}
1+
{% if base_class != "BaseModel" and "," not in base_class and not fields and not config and not description -%}
22

33
{# if this is just going to be `class Foo(Bar): pass`, then might as well just make Foo
44
an alias for Bar: every pydantic model class consumes considerable memory. #}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# generated by datamodel-codegen:
2+
# filename: allof_with_description_only.yaml
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from typing import Optional
8+
9+
from pydantic import BaseModel
10+
11+
12+
class MyModel(BaseModel):
13+
"""
14+
A model that has a description.
15+
"""
16+
17+
name: Optional[str] = None
18+
19+
20+
class MyOtherModel(MyModel):
21+
"""
22+
Another model that should also have a description.
23+
"""
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
openapi: "3.0.0"
2+
info:
3+
title: Test API
4+
version: "1.0.0"
5+
paths: {}
6+
components:
7+
schemas:
8+
MyModel:
9+
type: object
10+
description: A model that has a description.
11+
properties:
12+
name:
13+
type: string
14+
MyOtherModel:
15+
allOf:
16+
- $ref: "#/components/schemas/MyModel"
17+
description: Another model that should also have a description.

tests/test_main_kr.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,3 +955,20 @@ def test_profile_without_pyproject_errors(tmp_path: Path, capsys: pytest.Capture
955955
assert return_code == Exit.ERROR
956956
captured = capsys.readouterr()
957957
assert "no [tool.datamodel-codegen] section found" in captured.err.lower()
958+
959+
960+
@freeze_time("2019-07-26")
961+
def test_allof_with_description_generates_class_not_alias(output_file: Path) -> None:
962+
"""Test that allOf with description generates class definition, not alias."""
963+
run_main_and_assert(
964+
input_path=OPEN_API_DATA_PATH / "allof_with_description_only.yaml",
965+
output_path=output_file,
966+
input_file_type=None,
967+
assert_func=assert_file_content,
968+
expected_file=EXPECTED_MAIN_KR_PATH / "main_allof_with_description_only" / "output.py",
969+
extra_args=[
970+
"--output-model-type",
971+
"pydantic_v2.BaseModel",
972+
"--use-schema-description",
973+
],
974+
)

0 commit comments

Comments
 (0)