Skip to content

Commit 22b6258

Browse files
committed
add io module
for writing to and reading from the file-system
1 parent 6eb92df commit 22b6258

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed

app/io.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""app.io.py"""
2+
import json
3+
import pathlib
4+
from typing import Dict, Union
5+
6+
HERE = pathlib.Path(__file__)
7+
DATA = HERE.joinpath("..", "data").resolve()
8+
9+
10+
def save(
11+
name: str, content: Union[str, Dict], write_mode: str = "w", indent: int = 2, **json_dumps_kwargs
12+
) -> pathlib.Path:
13+
"""Save content to a file. If content is a dictionary, use json.dumps()."""
14+
path = DATA / name
15+
if isinstance(content, dict):
16+
content = json.dumps(content, indent=indent, **json_dumps_kwargs)
17+
with open(DATA / name, mode=write_mode) as f_out:
18+
f_out.write(content)
19+
return path
20+
21+
22+
def load(name: str, **json_kwargs) -> Union[str, Dict]:
23+
"""Loads content from a file. If file ends with '.json', call json.load() and return a Dictionary."""
24+
path = DATA / name
25+
with open(path) as f_in:
26+
if path.suffix == ".json":
27+
return json.load(f_in, **json_kwargs)
28+
return f_in.read()

tests/test_io.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""test.test_io.py"""
2+
import string
3+
4+
import pytest
5+
6+
import app.io
7+
8+
9+
@pytest.mark.parametrize(
10+
"name, content, kwargs",
11+
[
12+
("test_file.txt", string.ascii_lowercase, {}),
13+
("test_json_file.json", {"a": 0, "b": 1, "c": 2}, {}),
14+
("test_custom_json.json", {"z": -1, "b": 1, "y": -2, "a": 0}, {"indent": 4, "sort_keys": True}),
15+
],
16+
)
17+
def test_save(tmp_path, name, content, kwargs):
18+
test_path = tmp_path / name
19+
assert not test_path.exists()
20+
21+
result = app.io.save(test_path, content, **kwargs)
22+
assert result == test_path
23+
assert test_path.exists()
24+
25+
26+
@pytest.mark.parametrize(
27+
"name, content, kwargs",
28+
[
29+
("test_file.txt", string.ascii_lowercase, {}),
30+
("test_json_file.json", {"a": 0, "b": 1, "c": 2}, {}),
31+
("test_custom_json.json", {"z": -1, "b": 1, "y": -2, "a": 0}, {"indent": 4, "sort_keys": True}),
32+
],
33+
)
34+
def test_round_trip(tmp_path, name, content, kwargs):
35+
test_path = tmp_path / name
36+
assert not test_path.exists()
37+
38+
app.io.save(test_path, content, **kwargs)
39+
assert app.io.load(test_path) == content

0 commit comments

Comments
 (0)