From 54957d2f24f0f77da2e853274e9b905023e8b57a Mon Sep 17 00:00:00 2001 From: Valentin Lorentz <vlorentz@softwareheritage.org> Date: Wed, 21 Aug 2019 17:44:41 +0200 Subject: [PATCH] Make OriginVisit use datetime for its date. But keep support for deserializing from str, like swh-storage does. --- swh/model/model.py | 9 ++++++--- swh/model/tests/test_hypothesis_strategies.py | 5 ++++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/swh/model/model.py b/swh/model/model.py index 36f8ef3f..f6277e46 100644 --- a/swh/model/model.py +++ b/swh/model/model.py @@ -112,7 +112,6 @@ class OriginVisit(BaseModel): """Serializes the date as a string and omits the visit id if it is `None`.""" ov = super().to_dict() - ov['date'] = str(self.date) if ov['visit'] is None: del ov['visit'] return ov @@ -120,9 +119,13 @@ class OriginVisit(BaseModel): @classmethod def from_dict(cls, d): """Parses the date from a string, and accepts missing visit ids.""" + d = d.copy() + date = d.pop('date') return cls( - origin=Origin.from_dict(d['origin']), - date=dateutil.parser.parse(d['date']), + origin=Origin.from_dict(d.pop('origin')), + date=(date + if isinstance(date, datetime.datetime) + else dateutil.parser.parse(date)), visit=d.get('visit')) diff --git a/swh/model/tests/test_hypothesis_strategies.py b/swh/model/tests/test_hypothesis_strategies.py index 09c21d81..0df1fee4 100644 --- a/swh/model/tests/test_hypothesis_strategies.py +++ b/swh/model/tests/test_hypothesis_strategies.py @@ -3,6 +3,8 @@ # License: GNU General Public License version 3, or any later version # See top-level LICENSE file for more information +import datetime + import attr from hypothesis import given @@ -30,7 +32,8 @@ def assert_nested_dict(obj): elif isinstance(obj, list): for value in obj: assert_nested_dict(value) - elif isinstance(obj, (int, float, str, bytes, bool, type(None))): + elif isinstance(obj, (int, float, str, bytes, bool, type(None), + datetime.datetime)): pass else: assert False, obj -- GitLab