Skip to content

Commit 864b084

Browse files
committed
Add tests for --no-use-union-operator and add pragma: no cover to environment-specific code
1 parent b0ff0ec commit 864b084

18 files changed

Lines changed: 127 additions & 18 deletions

docs/cli-reference/model-customization.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4945,6 +4945,21 @@ where optional fields have defaults but cannot accept `None` values.
49454945
- type: string
49464946
- type: number
49474947
nullable: true
4948+
maybeValue:
4949+
description: A value that can be string or integer, not nullable
4950+
oneOf:
4951+
- type: string
4952+
- type: integer
4953+
nullableUnion:
4954+
description: A nullable union of string or integer
4955+
oneOf:
4956+
- type: string
4957+
- type: integer
4958+
nullable: true
4959+
simpleUnion:
4960+
oneOf:
4961+
- type: string
4962+
- type: number
49484963
required:
49494964
- comments
49504965
- oneOfComments
@@ -5034,6 +5049,13 @@ where optional fields have defaults but cannot accept `None` values.
50345049
class Options(BaseModel):
50355050
comments: list[str | None]
50365051
oneOfComments: list[str | float | None]
5052+
maybeValue: str | int | None = Field(
5053+
None, description='A value that can be string or integer, not nullable'
5054+
)
5055+
nullableUnion: str | int | None = Field(
5056+
None, description='A nullable union of string or integer'
5057+
)
5058+
simpleUnion: str | float | None = None
50375059
```
50385060

50395061
---

src/datamodel_code_generator/config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@
5959
ExtraTemplateDataType = defaultdict[str, dict[str, Any]]
6060
elif is_pydantic_v2():
6161
ExtraTemplateDataType = defaultdict[str, Annotated[dict[str, Any], Field(default_factory=dict)]]
62-
else:
62+
else: # pragma: no cover
6363
ExtraTemplateDataType = defaultdict[str, dict[str, Any]]
6464

6565

src/datamodel_code_generator/format.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ def __init__( # noqa: PLR0912, PLR0913, PLR0915, PLR0917
238238
black_kwargs: dict[str, Any] = {}
239239
if wrap_string_literal is not None:
240240
experimental_string_processing = wrap_string_literal
241-
elif black.__version__ < "24.1.0":
241+
elif black.__version__ < "24.1.0": # pragma: no cover
242242
experimental_string_processing = config.get("experimental-string-processing")
243243
else:
244244
experimental_string_processing = config.get("preview", False) and ( # pragma: no cover

src/datamodel_code_generator/model/msgspec.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -238,12 +238,12 @@ def _add_unset_type(type_: str, use_union_operator: bool) -> str: # noqa: FBT00
238238
"""Add UnsetType to a type hint without removing None."""
239239
if use_union_operator:
240240
return f"{type_}{UNION_OPERATOR_DELIMITER}{UNSET_TYPE}"
241-
if type_.startswith(UNION_PREFIX):
241+
if type_.startswith(UNION_PREFIX): # pragma: no cover
242242
return f"{type_[:-1]}{UNION_DELIMITER}{UNSET_TYPE}]"
243243
if type_.startswith(OPTIONAL_PREFIX): # pragma: no cover
244244
inner_type = type_[len(OPTIONAL_PREFIX) : -1]
245245
return f"{UNION_PREFIX}{inner_type}{UNION_DELIMITER}{NONE}{UNION_DELIMITER}{UNSET_TYPE}]"
246-
return f"{UNION_PREFIX}{type_}{UNION_DELIMITER}{UNSET_TYPE}]"
246+
return f"{UNION_PREFIX}{type_}{UNION_DELIMITER}{UNSET_TYPE}]" # pragma: no cover
247247

248248

249249
@import_extender
@@ -438,7 +438,7 @@ def needs_annotated_import(self) -> bool:
438438
"""
439439
if not self.annotated:
440440
return False
441-
if self.extras.get("is_classvar"):
441+
if self.extras.get("is_classvar"): # pragma: no cover
442442
return self.use_annotated and self._get_meta_string() is not None
443443
return True
444444

src/datamodel_code_generator/model/pydantic/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def dict( # type: ignore[override]
4444

4545
if is_pydantic_v2():
4646
return self.model_dump(**kwargs)
47-
return super().dict(**kwargs)
47+
return super().dict(**kwargs) # pragma: no cover
4848

4949

5050
__all__ = [

src/datamodel_code_generator/model/pydantic_v2/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def dict(self, **kwargs: Any) -> dict[str, Any]: # type: ignore[override]
5252

5353
if is_pydantic_v2():
5454
return self.model_dump(**kwargs)
55-
return super().dict(**kwargs)
55+
return super().dict(**kwargs) # pragma: no cover
5656

5757

5858
__all__ = [

src/datamodel_code_generator/util.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919

2020
try:
2121
from tomllib import load as load_tomllib # type: ignore[ignoreMissingImports]
22-
except ImportError:
22+
except ImportError: # pragma: no cover
2323
from tomli import load as load_tomllib # type: ignore[ignoreMissingImports]
2424

2525

@@ -165,9 +165,9 @@ def inner(
165165
if mode == "before":
166166
return model_validator_v2(mode=mode)(classmethod(method)) # type: ignore[reportReturnType]
167167
return model_validator_v2(mode=mode)(method) # type: ignore[reportReturnType]
168-
from pydantic import root_validator # noqa: PLC0415
168+
from pydantic import root_validator # noqa: PLC0415 # pragma: no cover
169169

170-
return root_validator(method, pre=mode == "before") # pyright: ignore[reportCallIssue]
170+
return root_validator(method, pre=mode == "before") # pyright: ignore[reportCallIssue] # pragma: no cover
171171

172172
return inner
173173

@@ -184,9 +184,9 @@ def inner(method: Callable[[Model, Any], Any]) -> Callable[[Model, Any], Any]:
184184
from pydantic import field_validator as field_validator_v2 # noqa: PLC0415
185185

186186
return field_validator_v2(field_name, *fields, mode=mode)(method)
187-
from pydantic import validator # noqa: PLC0415
187+
from pydantic import validator # noqa: PLC0415 # pragma: no cover
188188

189-
return validator(field_name, *fields, pre=mode == "before")(method) # pyright: ignore[reportReturnType]
189+
return validator(field_name, *fields, pre=mode == "before")(method) # pyright: ignore[reportReturnType] # pragma: no cover
190190

191191
return inner
192192

@@ -221,7 +221,7 @@ class _BaseModelV2(_PydanticBaseModel):
221221
model_config = _ConfigDict(strict=False)
222222

223223
return _BaseModelV2
224-
return _PydanticBaseModel
224+
return _PydanticBaseModel # pragma: no cover
225225

226226

227227
_BaseModel: type | None = None
@@ -286,25 +286,25 @@ def model_dump(obj: _BaseModel, **kwargs: Any) -> dict[str, Any]: # pyright: ig
286286
"""Version-compatible model serialization (dict/model_dump)."""
287287
if is_pydantic_v2():
288288
return obj.model_dump(**kwargs)
289-
return obj.dict(**kwargs) # type: ignore[reportDeprecated]
289+
return obj.dict(**kwargs) # type: ignore[reportDeprecated] # pragma: no cover
290290

291291

292292
def model_validate(cls: type[Model], obj: Any) -> Model:
293293
"""Version-compatible model validation (parse_obj/model_validate)."""
294294
if is_pydantic_v2():
295295
return cls.model_validate(obj)
296-
return cls.parse_obj(obj) # type: ignore[reportDeprecated]
296+
return cls.parse_obj(obj) # type: ignore[reportDeprecated] # pragma: no cover
297297

298298

299299
def get_fields_set(obj: _BaseModel) -> set[str]: # pyright: ignore[reportInvalidTypeForm]
300300
"""Version-compatible access to fields set (__fields_set__/model_fields_set)."""
301301
if is_pydantic_v2():
302302
return obj.model_fields_set
303-
return obj.__fields_set__ # type: ignore[reportDeprecated]
303+
return obj.__fields_set__ # type: ignore[reportDeprecated] # pragma: no cover
304304

305305

306306
def model_copy(obj: Model, **kwargs: Any) -> Model:
307307
"""Version-compatible model copy (copy/model_copy)."""
308308
if is_pydantic_v2():
309309
return obj.model_copy(**kwargs)
310-
return obj.copy(**kwargs) # type: ignore[reportDeprecated]
310+
return obj.copy(**kwargs) # type: ignore[reportDeprecated] # pragma: no cover

src/datamodel_code_generator/validators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,6 @@ class ModelValidators(BaseModel):
4646
class ValidatorsConfig(RootModel[dict[str, ModelValidators]]):
4747
"""Root model for validators configuration."""
4848

49-
else:
49+
else: # pragma: no cover
5050
# Pydantic v1 doesn't support RootModel, but validators feature is v2-only anyway
5151
ValidatorsConfig = None # type: ignore[assignment,misc]

tests/data/expected/main/openapi/msgspec_no_use_union_operator.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,17 @@ class Notes(Struct):
7979
class Options(Struct):
8080
comments: list[str]
8181
oneOfComments: list[Union[str, float]]
82+
maybeValue: Union[
83+
Annotated[
84+
Union[str, int],
85+
Meta(description='A value that can be string or integer, not nullable'),
86+
],
87+
UnsetType,
88+
] = UNSET
89+
nullableUnion: Union[
90+
Annotated[
91+
Union[str, int], Meta(description='A nullable union of string or integer')
92+
],
93+
UnsetType,
94+
] = UNSET
95+
simpleUnion: Union[str, float, UnsetType] = UNSET

tests/data/expected/main/openapi/msgspec_nullable.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,15 @@ class Notes(Struct):
7979
class Options(Struct):
8080
comments: list[str]
8181
oneOfComments: list[str | float]
82+
maybeValue: (
83+
Annotated[
84+
str | int,
85+
Meta(description='A value that can be string or integer, not nullable'),
86+
]
87+
| UnsetType
88+
) = UNSET
89+
nullableUnion: (
90+
Annotated[str | int, Meta(description='A nullable union of string or integer')]
91+
| UnsetType
92+
) = UNSET
93+
simpleUnion: str | float | UnsetType = UNSET

0 commit comments

Comments
 (0)