Skip to content

Commit 6442e9a

Browse files
committed
Add tests, indent in dump_json
1 parent 20de3f1 commit 6442e9a

File tree

3 files changed

+44
-5
lines changed

3 files changed

+44
-5
lines changed

src/jsonchain/__init__.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,10 @@
1+
"""
2+
A small package to aid in the use of the chaining techniques taught by Structural Python
3+
"""
4+
5+
__version__ = "0.1.0"
6+
7+
18
import json
29
import pathlib
310
from typing import Any, Optional
@@ -10,13 +17,13 @@ def load_json(filepath: str | pathlib.Path) -> dict | list:
1017
return json.load(file)
1118

1219

13-
def dump_json(object: list | dict, filepath: str | pathlib.Path) -> None:
20+
def dump_json(object: list | dict, filepath: str | pathlib.Path, indent=2) -> None:
1421
"""
1522
Dumps the 'object' (which must be JSON-serializable) into a JSON
1623
file at 'filepath'.
1724
"""
1825
with open(filepath, 'w') as file:
19-
json.dump(object, file)
26+
json.dump(object, file, indent=indent)
2027

2128

2229
def extract_keys(
@@ -55,6 +62,4 @@ def extract_keys(
5562
elif include_startswith is None:
5663
acc.append({key_name: key})
5764

58-
return acc
59-
60-
65+
return acc

tests/a.json

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"aa": 1,
3+
"ab": 2,
4+
"bc": 3
5+
}

tests/test_jsonchain.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
from jsonchain import load_json, dump_json, extract_keys
2+
3+
4+
def test_load_json():
5+
a_dict = load_json("a.json")
6+
assert a_dict['aa'] == 1
7+
assert a_dict['ab'] == 2
8+
assert a_dict['bc'] == 3
9+
10+
11+
def test_extract_keys():
12+
a_dict = load_json("a.json")
13+
loks = extract_keys(a_dict, key_name="group")
14+
assert loks == [
15+
{"group": "aa"},
16+
{"group": "ab"},
17+
{"group": "bc"}
18+
]
19+
loks_a = extract_keys(a_dict, key_name="group", include_startswith="a")
20+
assert loks_a == [
21+
{"group": "aa"},
22+
{"group": "ab"}
23+
]
24+
loks_b = extract_keys(a_dict, key_name="group", exclude_startswith="b")
25+
assert loks_b == [
26+
{"group": "aa"},
27+
{"group": "ab"},
28+
]
29+

0 commit comments

Comments
 (0)