Skip to content

Commit

Permalink
Merge pull request #539 from aiven/alex-fix-serializer-path
Browse files Browse the repository at this point in the history
Fix JSON serialization for pathlib.Path [BF-956]
  • Loading branch information
rdunklau authored Jun 14, 2022
2 parents ad1daf5 + c529520 commit 17d9ac8
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 3 deletions.
2 changes: 2 additions & 0 deletions pghoard/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,8 @@ def default_json_serialization(obj):
return obj.isoformat().replace("+00:00", "Z")
# assume UTC for datetime objects without a timezone
return obj.isoformat() + "Z"
elif isinstance(obj, Path):
return str(obj)
return None


Expand Down
9 changes: 6 additions & 3 deletions test/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import datetime
import json
import os
from pathlib import Path
from typing import Any, Dict

import pytest
from rohmu.errors import Error
Expand Down Expand Up @@ -50,17 +52,18 @@ def get_pgpass_contents():
os.environ["HOME"] = original_home

def test_json_serialization(self, tmpdir):
ob = {
ob: Dict[str, Any] = {
"foo": [
"bar",
"baz",
42,
],
"t": datetime.datetime(2015, 9, 1, 4, 0, 0),
"f": 0.42,
"path": Path("/some/path")
}
res = json.dumps(ob, default=default_json_serialization, separators=(",", ":"), sort_keys=True)
assert res == '{"f":0.42,"foo":["bar","baz",42],"t":"2015-09-01T04:00:00Z"}'
assert res == '{"f":0.42,"foo":["bar","baz",42],"path":"/some/path","t":"2015-09-01T04:00:00Z"}'

assert isinstance(json_encode(ob), str)
assert isinstance(json_encode(ob, binary=True), bytes)
Expand All @@ -71,7 +74,7 @@ def test_json_serialization(self, tmpdir):
write_json_file(output_file, ob)
with open(output_file, "r") as fp:
ob2 = json.load(fp)
ob_ = dict(ob, t=ob["t"].isoformat() + "Z")
ob_ = dict(ob, t=ob["t"].isoformat() + "Z", path=str(ob["path"]))
assert ob2 == ob_

write_json_file(output_file, ob, compact=True)
Expand Down

0 comments on commit 17d9ac8

Please sign in to comment.