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

Datetime serialization and deserialization fixed #1515

Merged
merged 14 commits into from
May 31, 2022
Merged
6 changes: 3 additions & 3 deletions kombu/utils/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ def default(self, o,
if not isinstance(o, datetime):
o = datetime(o.year, o.month, o.day, 0, 0, 0, 0)
r = o.isoformat()
auvipy marked this conversation as resolved.
Show resolved Hide resolved
if r.endswith("+00:00"):
r = r[:-6] + "Z"
return r
return {"datetime": r, "__datetime__": True}
elif isinstance(o, times):
return o.isoformat()
elif isinstance(o, textual):
Expand Down Expand Up @@ -80,6 +78,8 @@ def dumps(s, _dumps=json.dumps, cls=None, default_kwargs=None, **kwargs):

def object_hook(dct):
"""Hook function to perform custom deserialization."""
if "__datetime__" in dct:
return datetime.datetime.fromisoformat(dct["datetime"])
if "__bytes__" in dct:
return dct["bytes"].encode("utf-8")
if "__base64__" in dct:
Expand Down
1 change: 1 addition & 0 deletions requirements/test.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ pytest~=7.0.1
pytest-sugar
Pyro4
hypothesis
pytest-freezegun
9 changes: 4 additions & 5 deletions t/unit/utils/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,21 @@ def __json__(self):


class test_JSONEncoder:

@pytest.mark.freeze_time("2015-10-21")
def test_datetime(self):
now = datetime.utcnow()
now_utc = now.replace(tzinfo=pytz.utc)
stripped = datetime(*now.timetuple()[:3])
serialized = loads(dumps({
'datetime': now,
'tz': now_utc,
'date': now.date(),
'time': now.time()},
))
assert serialized == {
'datetime': now.isoformat(),
'tz': '{}Z'.format(now_utc.isoformat().split('+', 1)[0]),
'datetime': now,
'tz': now_utc,
'time': now.time().isoformat(),
'date': stripped.isoformat(),
'date': datetime(now.year, now.month, now.day, 0, 0, 0, 0),
}
dobosevych marked this conversation as resolved.
Show resolved Hide resolved

@given(message=st.binary())
Expand Down