Skip to content

Commit

Permalink
Serialize Colors as HEX
Browse files Browse the repository at this point in the history
  • Loading branch information
giancarloromeo committed Nov 26, 2024
1 parent 1f18a84 commit 07f3159
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ class Position(BaseModel):


class Marker(BaseModel):
color: Annotated[Color, PlainSerializer(str), Field(...)]
color: Annotated[Color, PlainSerializer(Color.as_hex), Field(...)]

model_config = ConfigDict(extra="forbid")
2 changes: 1 addition & 1 deletion packages/models-library/src/models_library/projects_ui.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Slideshow(_SlideshowRequired, total=False):

class Annotation(BaseModel):
type: Literal["note", "rect", "text"] = Field(...)
color: Annotated[Color, PlainSerializer(str), Field(...)]
color: Annotated[Color, PlainSerializer(Color.as_hex), Field(...)]
attributes: dict = Field(..., description="svg attributes")
model_config = ConfigDict(
extra="forbid",
Expand Down
11 changes: 7 additions & 4 deletions packages/models-library/tests/test_projects_nodes_ui.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import pytest
from models_library.projects_nodes_ui import Marker
from pydantic_extra_types.color import Color


def test_marker_serialization():
m = Marker(color=Color("#b7e28d"))

assert m.model_dump_json() == '{"color":"#b7e28d"}'
@pytest.mark.parametrize(
"color_str,expected_color_str", [("#b7e28d", "#b7e28d"), ("Cyan", "#0ff")]
)
def test_marker_color_serialized_to_hex(color_str, expected_color_str):
m = Marker(color=Color(color_str))
assert m.model_dump_json() == f'{{"color":"{expected_color_str}"}}'
14 changes: 14 additions & 0 deletions packages/models-library/tests/test_projects_ui.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import pytest
from models_library.projects_ui import Annotation
from pydantic_extra_types.color import Color


@pytest.mark.parametrize(
"color_str,expected_color_str", [("#b7e28d", "#b7e28d"), ("Cyan", "#0ff")]
)
def test_annotation_color_serialized_to_hex(color_str, expected_color_str):
m = Annotation(type="text", color=Color(color_str), attributes={})
assert (
m.model_dump_json()
== f'{{"type":"text","color":"{expected_color_str}","attributes":{{}}}}'
)

0 comments on commit 07f3159

Please sign in to comment.