-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
test_json_flatten.py
90 lines (84 loc) · 3.14 KB
/
test_json_flatten.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
from json_flatten import flatten, unflatten
import pytest
@pytest.mark.parametrize(
"test_name,unflattened,flattened",
[
# test_name, unflattened, flattened
("simple", {"foo": "bar"}, {"foo": "bar"}),
("nested", {"foo": {"bar": "baz"}}, {"foo.bar": "baz"}),
("list_with_one_item", {"foo": ["item"]}, {"foo.[0]": "item"}),
("nested_lists", {"foo": [["item"]]}, {"foo.[0].[0]": "item"}),
(
"list",
{"foo": {"bar": ["one", "two"]}},
{"foo.bar.[0]": "one", "foo.bar.[1]": "two"},
),
("int", {"foo": 5}, {"foo$int": "5"}),
("none", {"foo": None}, {"foo$none": "None"}),
("bool_true", {"foo": True}, {"foo$bool": "True"}),
("bool_false", {"foo": False}, {"foo$bool": "False"}),
("float", {"foo": 2.5}, {"foo$float": "2.5"}),
(
"complex",
{
"this": {
"is": {
"nested": [{"nested_dict_one": 10}, {"nested_dict_two": 20.5}]
},
"other_types": {"false": False, "true": True, "none": None},
}
},
{
"this.is.nested.[0].nested_dict_one$int": "10",
"this.is.nested.[1].nested_dict_two$float": "20.5",
"this.other_types.true$bool": "True",
"this.other_types.false$bool": "False",
"this.other_types.none$none": "None",
},
),
(
"dollar_signs_that_are_not_type_indicators",
{
"foo": [
{
"emails": ["bar@example.com"],
"phones": {"_$!<home>!$_": "555-555-5555"},
}
]
},
{
"foo.[0].emails.[0]": "bar@example.com",
"foo.[0].phones._$!<home>!$_": "555-555-5555",
},
),
("empty_object", {}, {"$empty": "{}"}),
(
"nested_empty_objects",
{"nested": {"foo": {}, "bar": {}}},
{"nested.foo$empty": "{}", "nested.bar$empty": "{}"},
),
("empty_nested_list", {"empty": []}, {"empty$emptylist": "[]"}),
(
"empty_nested_list_complex",
{"foo": {"bar": []}, "nested": [[], []]},
{
"foo.bar$emptylist": "[]",
"nested.[0]$emptylist": "[]",
"nested.[1]$emptylist": "[]",
},
),
("dict_with_numeric_key", {"bob": {"24": 4}}, {"bob.24$int": "4"}),
],
)
def test_flatten_unflatten(test_name, unflattened, flattened):
actual_flattened = flatten(unflattened)
assert actual_flattened == flattened
actual_unflattened = unflatten(actual_flattened)
assert actual_unflattened == unflattened
def test_integers_with_gaps_does_not_create_sparse_array():
assert unflatten({"list.[10]": "three", "list.[5]": "two", "list.[0]": "one"}) == {
"list": ["one", "two", "three"]
}
def test_list_as_base_level_object_rejected_with_error():
with pytest.raises(TypeError):
flatten([{"name": "john"}])