()
| 424 | |
| 425 | |
| 426 | def test_optional_model_using_asdict() -> None: |
| 427 | def make_fields_optional(model_cls: type[BaseModel]) -> type[BaseModel]: |
| 428 | new_fields = {} |
| 429 | |
| 430 | for f_name, f_info in model_cls.model_fields.items(): |
| 431 | f_dct = f_info.asdict() |
| 432 | new_fields[f_name] = ( |
| 433 | Annotated[(Union[f_dct['annotation'], None], *f_dct['metadata'], Field(**f_dct['attributes']))], # noqa: F821 |
| 434 | None, |
| 435 | ) |
| 436 | |
| 437 | return create_model( |
| 438 | f'{type.__name__}Optional', |
| 439 | __base__=model_cls, # (1)! |
| 440 | **new_fields, |
| 441 | ) |
| 442 | |
| 443 | class Model(BaseModel): |
| 444 | a: Annotated[int, Field(gt=1)] |
| 445 | |
| 446 | ModelOptional = make_fields_optional(Model) |
| 447 | |
| 448 | assert ModelOptional().a is None |
| 449 | |
| 450 | with pytest.raises(ValidationError): |
| 451 | ModelOptional(a=0) |
| 452 | |
| 453 | |
| 454 | def test_default_factory_without_validated_data_unsupported() -> None: |
nothing calls this directly
no test coverage detected