Skip to content

Commit 3146f44

Browse files
committed
Add parameterized test for pydantic v1/v2 default value handling
1 parent 9698d79 commit 3146f44

2 files changed

Lines changed: 56 additions & 2 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# generated by datamodel-codegen:
2+
# filename: has_default_value.json
3+
# timestamp: 2019-07-26T00:00:00+00:00
4+
5+
from __future__ import annotations
6+
7+
from enum import Enum
8+
9+
from pydantic import BaseModel, Field, RootModel
10+
11+
12+
class TeamType(Enum):
13+
Department = 'Department'
14+
Division = 'Division'
15+
BusinessUnit = 'BusinessUnit'
16+
Organization = 'Organization'
17+
18+
19+
class ID(RootModel[str]):
20+
root: str
21+
22+
23+
class Pet(BaseModel):
24+
name: str | None = None
25+
26+
27+
class Family(RootModel[list[ID]]):
28+
root: list[ID] = Field(
29+
default_factory=lambda: [ID.model_validate(v) for v in ['abc', 'efg']]
30+
)
31+
32+
33+
class FamilyPets(RootModel[list[Pet]]):
34+
root: list[Pet] = Field(
35+
default_factory=lambda: [Pet.model_validate(v) for v in ['taro', 'shiro']]
36+
)
37+
38+
39+
class Person(BaseModel):
40+
id: ID | None = Field(default_factory=lambda: ID('abc'))
41+
user: Pet | None = None
42+
firstName: str | None = Field(None, description="The person's first name.")
43+
team: TeamType | None = 'Department'
44+
anotherTeam: TeamType | None = 'Department'
45+
Family_1: Family | None = Field(None, alias='Family')
46+
FamilyPets_1: FamilyPets | None = Field(None, alias='FamilyPets')

tests/main/jsonschema/test_main_jsonschema.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3254,14 +3254,22 @@ def test_jsonschema_use_title_as_name_nested_titles_pydantic(output_file: Path)
32543254
)
32553255

32563256

3257-
def test_main_jsonschema_has_default_value(output_file: Path) -> None:
3257+
@pytest.mark.parametrize(
3258+
("output_model", "expected_file"),
3259+
[
3260+
("pydantic.BaseModel", "has_default_value.py"),
3261+
("pydantic_v2.BaseModel", "has_default_value_pydantic_v2.py"),
3262+
],
3263+
)
3264+
def test_main_jsonschema_has_default_value(output_model: str, expected_file: str, output_file: Path) -> None:
32583265
"""Test default value handling."""
32593266
run_main_and_assert(
32603267
input_path=JSON_SCHEMA_DATA_PATH / "has_default_value.json",
32613268
output_path=output_file,
32623269
input_file_type="jsonschema",
32633270
assert_func=assert_file_content,
3264-
expected_file="has_default_value.py",
3271+
expected_file=expected_file,
3272+
extra_args=["--output-model-type", output_model],
32653273
)
32663274

32673275

0 commit comments

Comments
 (0)