From 6e96b85a865ca16cc4a096c433c9f28590490a5c Mon Sep 17 00:00:00 2001 From: Boxy Date: Tue, 6 Aug 2024 14:57:28 +0100 Subject: [PATCH] Expose AnySerializer via core schema (#1394) --- python/pydantic_core/core_schema.py | 1 + tests/serializers/test_any.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/python/pydantic_core/core_schema.py b/python/pydantic_core/core_schema.py index c157a027b..4ac24bd6c 100644 --- a/python/pydantic_core/core_schema.py +++ b/python/pydantic_core/core_schema.py @@ -219,6 +219,7 @@ def field_name(self) -> str | None: 'multi-host-url', 'json', 'uuid', + 'any', ] diff --git a/tests/serializers/test_any.py b/tests/serializers/test_any.py index 4c3cd9eff..7337d012e 100644 --- a/tests/serializers/test_any.py +++ b/tests/serializers/test_any.py @@ -652,3 +652,32 @@ def test_ser_json_inf_nan_with_list_of_any() -> None: assert isnan(s.to_python([nan])[0]) assert s.to_python([nan], mode='json')[0] is None assert s.to_json([nan]) == b'[null]' + + +def test_simple_any_ser_schema_repr(): + assert ( + plain_repr(SchemaSerializer(core_schema.simple_ser_schema('any'))) + == 'SchemaSerializer(serializer=Any(AnySerializer),definitions=[])' + ) + + +def test_simple_any_ser_schema(): + import operator + + class MyEnum(Enum): + A = (1,) + B = (2,) + + v = SchemaSerializer( + core_schema.no_info_after_validator_function( + operator.attrgetter('value'), + core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values())), + serialization=core_schema.simple_ser_schema('any'), + ), + ) + + assert v.to_python({MyEnum.A: 'x'}) == {MyEnum.A: 'x'} + assert v.to_python({MyEnum.A: 'x'}, mode='json') == {'1': 'x'} + assert v.to_json({MyEnum.A: 'x'}) == b'{"1":"x"}' + assert v.to_python(1) == 1 + assert v.to_json(1) == b'1'