commit af849a06a7183b06aa1ab7ed478ed862c86b6566 Author: juga0 juga@riseup.net Date: Sat Mar 21 13:01:50 2020 +0000
chg: state: Encode/decode datetimes --- sbws/util/state.py | 6 ++++-- tests/unit/util/test_state.py | 8 ++++++++ 2 files changed, 12 insertions(+), 2 deletions(-)
diff --git a/sbws/util/state.py b/sbws/util/state.py index 50e6a66..b6614a7 100644 --- a/sbws/util/state.py +++ b/sbws/util/state.py @@ -2,6 +2,8 @@ from sbws.util.filelock import FileLock import os import json
+from .json import CustomDecoder, CustomEncoder +
class State: """ @@ -48,12 +50,12 @@ class State: return {} with FileLock(self._fname): with open(self._fname, 'rt') as fd: - return json.load(fd) + return json.load(fd, cls=CustomDecoder)
def _write(self): with FileLock(self._fname): with open(self._fname, 'wt') as fd: - return json.dump(self._state, fd, indent=4) + return json.dump(self._state, fd, indent=4, cls=CustomEncoder)
def __len__(self): self._state = self._read() diff --git a/tests/unit/util/test_state.py b/tests/unit/util/test_state.py index a57768d..d08a4a9 100644 --- a/tests/unit/util/test_state.py +++ b/tests/unit/util/test_state.py @@ -83,3 +83,11 @@ def test_two_instances(tmpdir): s1["x"] = "foo" s2["y"] = "bar" assert s2["x"] == "foo" + + +def test_datetime_values(tmpdir): + import datetime + state = State(os.path.join(str(tmpdir), 'state.dat')) + now = datetime.datetime.utcnow().replace(microsecond=0) + state["datetimes"] = now + assert now == state["datetimes"]