Skip to content

Commit

Permalink
Merge pull request #27 from kodemore/fix-serializer
Browse files Browse the repository at this point in the history
Allow Serializer to support non decorated types
  • Loading branch information
dkraczkowski authored Nov 8, 2023
2 parents 9ac1089 + 7cfd0dd commit 5558b91
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 3 deletions.
4 changes: 2 additions & 2 deletions chili/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__}]",
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
61 changes: 61 additions & 0 deletions tests/test_serialzer.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 5558b91

Please sign in to comment.