From c4829754db0f0a5b10265309d327875694d33ab4 Mon Sep 17 00:00:00 2001 From: dobosevych Date: Tue, 31 May 2022 08:21:04 +0300 Subject: [PATCH] Datetime serialization and deserialization fixed (#1515) * Datetime serialization and deserialization fixed * Unit test fixed * Unit test fixed * Fixed pylint * Added Undocumented Autodoc Modules * Update kombu/utils/json.py Co-authored-by: Omer Katz * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Clean and freeze now * Clean and freeze now * Clean and freeze now * Clean and freeze now Co-authored-by: Asif Saif Uddin Co-authored-by: Omer Katz Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- kombu/utils/json.py | 6 +++--- requirements/test.txt | 1 + t/unit/utils/test_json.py | 9 ++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/kombu/utils/json.py b/kombu/utils/json.py index f6429c3f..26583d61 100644 --- a/kombu/utils/json.py +++ b/kombu/utils/json.py @@ -41,9 +41,7 @@ class JSONEncoder(_encoder_cls): if not isinstance(o, datetime): o = datetime(o.year, o.month, o.day, 0, 0, 0, 0) r = o.isoformat() - 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): @@ -71,6 +69,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: diff --git a/requirements/test.txt b/requirements/test.txt index 6674f34c..038d5e9d 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -3,3 +3,4 @@ pytest~=7.1.1 pytest-sugar Pyro4 hypothesis +pytest-freezegun diff --git a/t/unit/utils/test_json.py b/t/unit/utils/test_json.py index c263b4f9..54d559e4 100644 --- a/t/unit/utils/test_json.py +++ b/t/unit/utils/test_json.py @@ -25,11 +25,10 @@ class Custom: 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, @@ -37,10 +36,10 @@ class test_JSONEncoder: '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), } @given(message=st.binary())