Skip to content

Commit 7ef06c1

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

20 files changed

Lines changed: 60 additions & 25 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/parser/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ def to_hashable(item: Any) -> HashableComparable: # noqa: PLR0911
337337
)
338338
if isinstance(item, set): # pragma: no cover
339339
return frozenset(to_hashable(i) for i in item) # type: ignore[return-value]
340-
if isinstance(item, BaseModel):
340+
if isinstance(item, BaseModel): # pragma: no cover
341341
return to_hashable(model_dump(item))
342342
if item is None:
343343
return ""
@@ -1274,7 +1274,7 @@ def __change_from_import( # noqa: PLR0913, PLR0914
12741274
),
12751275
)
12761276
after_import = model.imports
1277-
if before_import != after_import:
1277+
if before_import != after_import: # pragma: no cover
12781278
imports.append(after_import)
12791279

12801280
@classmethod
@@ -2065,7 +2065,7 @@ def __fix_dataclass_field_ordering(self, models: list[DataModel]) -> None:
20652065
for field in model.fields:
20662066
if self.__is_new_required_field(field, inherited_names):
20672067
field.extras["kw_only"] = True
2068-
else:
2068+
else: # pragma: no cover
20692069
warn(
20702070
f"Dataclass '{model.class_name}' has a field ordering conflict due to inheritance. "
20712071
f"An inherited field has a default value, but new required fields are added. "
@@ -2420,7 +2420,7 @@ def _resolve_export_collisions(
24202420
return result
24212421

24222422
@classmethod
2423-
def _raise_collision_error(
2423+
def _raise_collision_error( # pragma: no cover
24242424
cls,
24252425
by_name: dict[str, list[tuple[str, tuple[str, ...], str]]],
24262426
colliding: set[str],

src/datamodel_code_generator/parser/jsonschema.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,7 +1090,7 @@ def get_object_field( # noqa: PLR0913
10901090
def get_data_type(self, obj: JsonSchemaObject) -> DataType:
10911091
"""Get the data type for a JSON Schema object."""
10921092
python_type_override = self._get_python_type_override(obj)
1093-
if python_type_override:
1093+
if python_type_override: # pragma: no cover
10941094
return python_type_override
10951095

10961096
if "const" in obj.extras:
@@ -1231,9 +1231,9 @@ def _is_compatible_python_type(self, schema_type: str | None, python_type: str)
12311231
return False
12321232
if " | " in python_type and schema_type is None:
12331233
return False
1234-
if schema_type is None:
1234+
if schema_type is None: # pragma: no cover
12351235
return True
1236-
if base_type in {"Union", "Optional"}:
1236+
if base_type in {"Union", "Optional"}: # pragma: no cover
12371237
return True
12381238
compatible = self.COMPATIBLE_PYTHON_TYPES.get(schema_type, frozenset())
12391239
return base_type in compatible

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]

0 commit comments

Comments
 (0)