From 7cfd0ddc56836001a8360ad69d87255c4bbfea2f Mon Sep 17 00:00:00 2001 From: Dawid Kraczkowski Date: Wed, 8 Nov 2023 08:25:21 +0100 Subject: [PATCH] Allow Serializer to support non decorated types --- chili/serializer.py | 4 +-- pyproject.toml | 2 +- tests/test_serialzer.py | 61 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+), 3 deletions(-) create mode 100644 tests/test_serialzer.py diff --git a/chili/serializer.py b/chili/serializer.py index 1c3de03..26f8bac 100644 --- a/chili/serializer.py +++ b/chili/serializer.py @@ -42,8 +42,8 @@ def __class_getitem__(cls, item: Type[T]) -> Type[Serializer]: # noqa: E501 if is_dataclass(item): item = serializable(item) - if not hasattr(item, _DECODABLE) or not hasattr(item, _ENCODABLE): - raise SerialisationError.invalid_type + if not hasattr(item, _DECODABLE) and not hasattr(item, _ENCODABLE): + item = serializable(item) return type( # type: ignore f"{cls.__qualname__}[{item.__module__}.{item.__qualname__}]", diff --git a/pyproject.toml b/pyproject.toml index 074f16e..8c89ad7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,7 +22,7 @@ license = "MIT" name = "chili" readme = "README.md" repository = "https://github.com/kodemore/chili" -version = "2.7.0" +version = "2.7.1" [tool.poetry.dependencies] gaffe = ">=0.3.0" diff --git a/tests/test_serialzer.py b/tests/test_serialzer.py new file mode 100644 index 0000000..48a22aa --- /dev/null +++ b/tests/test_serialzer.py @@ -0,0 +1,61 @@ +from chili import Serializer, serializable + + +def test_can_instantiate() -> None: + # given + @serializable + class Example: + ... + + # when + instance = Serializer[Example]() + + # then + assert isinstance(instance, Serializer) + assert instance.__generic__ == Example + + +def test_can_encode_non_serializable_type() -> None: + # given + class Example: + name: str + age: int + + def __init__(self, name: str, age: int): + self.name = name + self.age = age + + # when + serializer = Serializer[Example]() + value = serializer.encode(Example("bob", 33)) + + # then + assert value == { + "name": "bob", + "age": 33, + } + + +def test_can_decode_non_serializable_type() -> None: + # given + class Example: + name: str + age: int + + def __init__(self, name: str, age: int): + self.name = name + self.age = age + + # when + serializer = Serializer[Example]() + value = serializer.decode( + { + "name": "bob", + "age": 33, + } + ) + + # then + assert isinstance(value, Example) + assert value.name == "bob" + assert value.age == 33