From 07b4aa7582c1cfe4848d96cd1b86224037e9d135 Mon Sep 17 00:00:00 2001 From: ReRubis Date: Sun, 31 Dec 2023 07:20:52 +0000 Subject: [PATCH 1/2] Add testing of serialization Signed-off-by: ReRubis --- tests/test_color.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_color.py b/tests/test_color.py index ccf25f8..59ec6e2 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -89,6 +89,9 @@ class TestModel(BaseModel): assert isinstance(model.color, Color) assert model.color == color + assert model.model_dump(mode='json') == f'{{"color": "{int(color)}"}}' + assert model.model_dump() == {'color': int(color)} + def test_color_error_in_models(): class TestModel(BaseModel): @@ -97,6 +100,7 @@ class TestModel(BaseModel): with pytest.raises(ValueError): TestModel(color='not a color') + # @pytest.mark.parametrize('img_name', [Path(f'tests/data/{file_name}') for file_name in TEST_FILE_NAMES]) # def test_base64_images_in_models(img_name: Path): # class TestModel(BaseModel): From 99a3a0921c39e5a86ea29962f3169f4e7106e7d4 Mon Sep 17 00:00:00 2001 From: ReRubis Date: Sun, 31 Dec 2023 08:03:40 +0000 Subject: [PATCH 2/2] Fix serialization in Color class Signed-off-by: ReRubis --- asyncord/color.py | 67 +++++++++++++++++++++++++++------------------ tests/test_color.py | 4 +-- 2 files changed, 43 insertions(+), 28 deletions(-) diff --git a/asyncord/color.py b/asyncord/color.py index 04ac7a6..073378f 100644 --- a/asyncord/color.py +++ b/asyncord/color.py @@ -59,30 +59,6 @@ def to_hex(self) -> str: """Return the hexadecimal code of the color.""" return hex(self.value) - @classmethod - def validate(cls, value: int | str | RGB | tuple[int, int, int] | Self) -> Self: - """Pydantic auxiliary validation method. - - Args: - value: Value to validate. - - Returns: - Validated Color. - - Raises: - ValueError: If value is not - """ - if isinstance(value, int | str | RGB): - return cls.build(value) - - if isinstance(value, tuple) and len(value) == 3 and all(isinstance(v, int) for v in value): - return cls.build(value) - - if isinstance(value, cls): - return value - - raise ValueError('Invalid value type') - @classmethod def __get_pydantic_core_schema__( cls, _source: type[BaseModel], _handler: Callable[[Any], CoreSchema], @@ -107,9 +83,12 @@ def __get_pydantic_core_schema__( ]) return core_schema.no_info_after_validator_function( - function=cls.validate, + function=cls._validate, schema=schema, - serialization=core_schema.simple_ser_schema('int'), + serialization=core_schema.plain_serializer_function_ser_schema( + function=cls._serialize, + when_used='json-unless-none', + ), ) def __repr__(self) -> str: @@ -130,6 +109,42 @@ def __int__(self) -> int: """Return the integer value of the color.""" return self.value + @classmethod + def _validate(cls, value: int | str | RGB | tuple[int, int, int] | Self) -> Self: + """Pydantic auxiliary validation method. + + Args: + value: Value to validate. + + Returns: + Validated Color. + + Raises: + ValueError: If value is not + """ + if isinstance(value, int | str | RGB): + return cls.build(value) + + if isinstance(value, tuple) and len(value) == 3 and all(isinstance(v, int) for v in value): + return cls.build(value) + + if isinstance(value, cls): + return value + + raise ValueError('Invalid value type') + + @classmethod + def _serialize(cls, value: Self) -> int: + """Pydantic auxiliary method to serialize the color. + + Args: + value: Value to serialize. + + Returns: + Serialized value. + """ + return int(value) + ColorInput = Annotated[int | str | RGB | tuple[int, int, int] | Color, Color] diff --git a/tests/test_color.py b/tests/test_color.py index 59ec6e2..147debd 100644 --- a/tests/test_color.py +++ b/tests/test_color.py @@ -89,8 +89,8 @@ class TestModel(BaseModel): assert isinstance(model.color, Color) assert model.color == color - assert model.model_dump(mode='json') == f'{{"color": "{int(color)}"}}' - assert model.model_dump() == {'color': int(color)} + assert model.model_dump() == {'color': color} + assert model.model_dump(mode='json') == {'color': DECIMAL_VALUE} def test_color_error_in_models():