Skip to content

Commit

Permalink
Fix default value serializing (#9066)
Browse files Browse the repository at this point in the history
  • Loading branch information
NeevCohen committed Mar 21, 2024
1 parent 99147ca commit a80e034
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 2 deletions.
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

0 comments on commit a80e034

Please sign in to comment.