Skip to content

Commit

Permalink
Add more tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Fatal1ty committed Nov 14, 2023
1 parent da4f630 commit 3207d29
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
43 changes: 43 additions & 0 deletions tests/test_forward_refs/test_generic_serializable_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from typing import Dict, Generic, TypeVar

from mashumaro import DataClassDictMixin
from mashumaro.types import SerializableType

T = TypeVar("T")


class Foo(Generic[T], SerializableType, use_annotations=True):
a: T

def __init__(self, a: T) -> None:
self.a = a

@classmethod
def _deserialize(cls, value: Dict[str, T]) -> Foo[T]:
return cls(**value)

def _serialize(self) -> Dict[str, T]:
return {"a": self.a}

def __eq__(self, other: Foo) -> bool:
return self.a == other.a

def __repr__(self):
return f"Foo(a={self.a})"


@dataclass
class Bar(DataClassDictMixin):
x_str: Foo[str]
x_date: Foo[date]


def test_generic_serializable_type():
data = {"x_str": {"a": "2023-11-14"}, "x_date": {"a": "2023-11-14"}}
obj = Bar(Foo("2023-11-14"), Foo(date(2023, 11, 14)))
assert obj.to_dict() == data
assert Bar.from_dict(data) == obj
48 changes: 48 additions & 0 deletions tests/test_forward_refs/test_generic_serialization_strategy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from __future__ import annotations

from dataclasses import dataclass
from datetime import date
from typing import Dict, Generic, TypeVar

from mashumaro import DataClassDictMixin
from mashumaro.config import BaseConfig
from mashumaro.types import SerializationStrategy

T = TypeVar("T")


class Foo(Generic[T]):
a: T

def __init__(self, a: T) -> None:
self.a = a

def __eq__(self, other: Foo) -> bool:
return self.a == other.a

def __repr__(self):
return f"Foo(a={self.a})"


class FooStrategy(Generic[T], SerializationStrategy):
def deserialize(self, value: Dict[str, T]) -> Foo[T]:
return Foo(**value)

def serialize(self, value: Foo[T]) -> Dict[str, T]:
return {"a": value.a}


@dataclass
class Bar(DataClassDictMixin):
x_str: Foo[str]
x_date: Foo[date]

class Config(BaseConfig):
serialization_strategy = {Foo: FooStrategy()}


def test_generic_serialization_strategy():
data = {"x_str": {"a": "2023-11-14"}, "x_date": {"a": "2023-11-14"}}
obj = Bar(Foo("2023-11-14"), Foo(date(2023, 11, 14)))
assert obj.to_dict() == data
assert Bar.from_dict(data) == obj

0 comments on commit 3207d29

Please sign in to comment.