MCPcopy
hub / github.com/pydantic/pydantic / test_optional_model_using_asdict

Function test_optional_model_using_asdict

tests/test_fields.py:426–451  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

424
425
426def 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
454def test_default_factory_without_validated_data_unsupported() -> None:

Callers

nothing calls this directly

Calls 1

make_fields_optionalFunction · 0.85

Tested by

no test coverage detected