Skip to content

Commit

Permalink
Tighten up utils.write_json and add a test
Browse files Browse the repository at this point in the history
  • Loading branch information
palewire committed Dec 22, 2022
1 parent 8abd32c commit 963cffe
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
25 changes: 21 additions & 4 deletions newshomepages/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,29 @@ def write_csv(dict_list, path):
writer.writerows(dict_list)


def write_json(data: typing.Any, path: Path, indent: int = 2):
"""Write JSON data to the provided path."""
def write_json(
data: typing.Any, path: Path, indent: int = 2, verbose: bool = True
) -> None:
"""Write JSON data to the provided path.
Args:
data (Any): Any Python object ready to be serialized as JSON.
path (Path): The filesystem Path where the object should be written.
indent (int): The number of identations to include in the JSON. (Default: 2)
verbose (bool): Whether or not to log the action prior to execution. (Default: True)
Returns nothing.
"""
# Log
if verbose:
print(f"📥 Writing JSON to {path}")

# Make the parent directory, if it doesn't already exist
path.parent.mkdir(parents=True, exist_ok=True)
print(f"📥 Writing JSON to {path}")

# Write out the data as JSON
with open(path, "w") as fh:
json.dump(data, fh, indent=2)
json.dump(data, fh, indent=indent)


@retry(tries=3, delay=15, backoff=2)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from pathlib import Path

import pytz

from newshomepages import utils
Expand All @@ -13,6 +15,15 @@ def test_safe_ia_handle():
pass


def test_write_json(tmpdir):
"""Test write_json."""
p = Path(tmpdir / "write_json")
utils.write_json({"foo": "bar"}, p)
utils.write_json([{"foo": "bar"}], p)
utils.write_json({"foo": "bar"}, p, indent=4)
utils.write_json({"foo": "bar"}, p, verbose=False)


def test_sites():
"""Test sites utils."""
# Read in the list
Expand Down

0 comments on commit 963cffe

Please sign in to comment.