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

Issue #28 - Fixing serialisation/deserialisation of date types as well as datetime types #170

Merged
merged 1 commit into from
Sep 13, 2021
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
8 changes: 5 additions & 3 deletions sharedmodels/sharedmodels/dataclassbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,9 +196,11 @@ def _get_value_for_typed_field(
return typing_hint(val) # type: ignore
except:
...
elif isinstance(val, str) and issubclass(typing_hint, datetime.datetime):
elif isinstance(val, str) and issubclass(typing_hint, datetime.date):
# ISO-8601 conversion.
return datetime.datetime.fromisoformat(val)
if issubclass(typing_hint, datetime.datetime):
return datetime.datetime.fromisoformat(val)
return datetime.date.fromisoformat(val)

raise DataClassFromDictValueError(
f"Could not match {val} with static type {typing_hint}"
Expand Down Expand Up @@ -301,7 +303,7 @@ def replace_with_json_serialisable_types(val: Any) -> Any:
Its inverse is :func:`replace_serialised_types_with_builtin_types`.
"""

if isinstance(val, datetime.datetime):
if isinstance(val, datetime.date):
return val.isoformat()
elif isinstance(val, dict):
return dict(
Expand Down
13 changes: 13 additions & 0 deletions sharedmodels/sharedmodels/tests/unit/test_dataclassbase.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,19 @@ class A(DataClassBase):
assert reinflated_a.some_datetime == dt


def test_date_json_serialisation():
@dataclass
class A(DataClassBase):
some_datetime: datetime.date

date = datetime.date.today()

a = A(date)
reinflated_a = a.from_json(a.as_json())
assert isinstance(reinflated_a, A)
assert reinflated_a.some_datetime == date


def test_override_values():
@dataclass
class A(DataClassBase):
Expand Down