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 color serialize #45

Merged
merged 2 commits into from
Dec 31, 2023
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 41 additions & 26 deletions asyncord/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand All @@ -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:
Expand All @@ -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]

Expand Down
4 changes: 4 additions & 0 deletions tests/test_color.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,9 @@ class TestModel(BaseModel):
assert isinstance(model.color, Color)
assert model.color == color

assert model.model_dump() == {'color': color}
assert model.model_dump(mode='json') == {'color': DECIMAL_VALUE}


def test_color_error_in_models():
class TestModel(BaseModel):
Expand All @@ -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):
Expand Down