Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix default value serializing #9066

Merged
merged 3 commits into from Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 13 additions & 2 deletions pydantic/json_schema.py
Expand Up @@ -54,7 +54,7 @@
)
from .annotated_handlers import GetJsonSchemaHandler
from .config import JsonDict, JsonSchemaExtraCallable, JsonValue
from .errors import PydanticInvalidForJsonSchema, PydanticUserError
from .errors import PydanticInvalidForJsonSchema, PydanticSchemaGenerationError, PydanticUserError

if TYPE_CHECKING:
from . import ConfigDict
Expand Down Expand Up @@ -1993,9 +1993,20 @@ def encode_default(self, dft: Any) -> Any:
Returns:
The encoded default value.
"""
from .type_adapter import TypeAdapter

config = self._config
try:
default = (
dft
if hasattr(dft, '__pydantic_serializer__')
else TypeAdapter(type(dft), config=config.config_dict).dump_python(dft, mode='json')
)
except PydanticSchemaGenerationError:
raise pydantic_core.PydanticSerializationError(f'Unable to encode default value {dft}')

return pydantic_core.to_jsonable_python(
dft,
default,
timedelta_mode=config.ser_json_timedelta,
bytes_mode=config.ser_json_bytes,
)
Expand Down
35 changes: 35 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -5995,3 +5995,38 @@ class Model(BaseModel):
assert Model.model_fields['a'].is_required()
assert Model.model_fields['b'].is_required()
assert Model.model_fields['c'].is_required()


@pytest.mark.parametrize(
'field_type,default_value,expected_schema',
[
(
IPvAnyAddress,
IPv4Address('127.0.0.1'),
{
'properties': {
'field': {'default': '127.0.0.1', 'format': 'ipvanyaddress', 'title': 'Field', 'type': 'string'}
},
'title': 'Model',
'type': 'object',
},
),
(
IPvAnyAddress,
IPv6Address('::1'),
{
'properties': {
'field': {'default': '::1', 'format': 'ipvanyaddress', 'title': 'Field', 'type': 'string'}
},
'title': 'Model',
'type': 'object',
},
),
],
)
def test_default_value_encoding(field_type, default_value, expected_schema):
class Model(BaseModel):
field: field_type = default_value

schema = Model.model_json_schema()
assert schema == expected_schema