Skip to content

Commit

Permalink
Fix Secret serialization schema, applicable for unions (#9240)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Apr 16, 2024
1 parent b844ea7 commit ae71183
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
14 changes: 11 additions & 3 deletions pydantic/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -1561,14 +1561,22 @@ def validate_secret_value(value, handler) -> Secret[SecretType]:
validated_inner = handler(value)
return cls(validated_inner)

def serialize(value: Secret[SecretType], info: core_schema.SerializationInfo) -> str | Secret[SecretType]:
if info.mode == 'json':
return str(value)
else:
return value

return core_schema.json_or_python_schema(
python_schema=core_schema.no_info_wrap_validator_function(
validate_secret_value,
inner_schema,
serialization=core_schema.plain_serializer_function_ser_schema(lambda x: x),
),
json_schema=core_schema.no_info_after_validator_function(
lambda x: cls(x), inner_schema, serialization=core_schema.to_string_ser_schema(when_used='json')
json_schema=core_schema.no_info_after_validator_function(lambda x: cls(x), inner_schema),
serialization=core_schema.plain_serializer_function_ser_schema(
serialize,
info_arg=True,
when_used='always',
),
)

Expand Down
9 changes: 9 additions & 0 deletions tests/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -4463,6 +4463,15 @@ class Foobar(BaseModel):
assert m.value.get_secret_value() == date(2017, 1, 1)


def test_secret_union_serializable() -> None:
class Base(BaseModel):
x: Union[Secret[int], Secret[str]]

model = Base(x=1)
assert model.model_dump() == {'x': Secret[int](1)}
assert model.model_dump_json() == '{"x":"**********"}'


@pytest.mark.parametrize(
'pydantic_type',
[
Expand Down

0 comments on commit ae71183

Please sign in to comment.