Skip to content

Commit 024ec3b

Browse files
committed
[test] update import for intermediate conversion test
1 parent 107ff99 commit 024ec3b

File tree

2 files changed

+106
-1
lines changed

2 files changed

+106
-1
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from six import string_types
2+
from six.moves import reduce
3+
4+
5+
def flatten(elements):
6+
"""
7+
Flatten a list
8+
elements :: List
9+
return List
10+
"""
11+
if elements is not list:
12+
return elements
13+
else:
14+
return reduce(lambda x, y: x + flatten(y), elements, [])
15+
16+
17+
def shrink(configuration):
18+
"""
19+
configuration :: Dict
20+
return Dict
21+
"""
22+
temp = {}
23+
for key, value in configuration.items():
24+
if isinstance(value, string_types) or isinstance(value, int):
25+
temp[key] = value
26+
else:
27+
# reduce to atom list
28+
# as value could be dict or list
29+
# enclose it in a flattened list
30+
for child in intermediate_to_list(flatten([value])):
31+
for child_key, child_value in child.items():
32+
nested_key = '{key}.{subkey}'.format(key=key, subkey=child_key)
33+
temp[nested_key] = child_value
34+
return temp
35+
36+
37+
def intermediate_to_list(configuration):
38+
"""
39+
Explore the configuration tree and flatten where
40+
possible with the following policy
41+
- list -> prepend the list index to every item key
42+
- dictionary -> prepend the father key to every key
43+
44+
configuration :: List[Enum[Dict,List]]
45+
return List[Dict]
46+
47+
>>> intermediate_to_list([
48+
{
49+
'spam': {
50+
'eggs': 'spam and eggs'
51+
}
52+
}
53+
])
54+
>>>
55+
[{
56+
'spam.eggs' : 'spam and eggs'
57+
]}
58+
59+
>>> intermediate_to_list([
60+
{
61+
'spam': {
62+
'eggs': 'spam and eggs'
63+
}
64+
},
65+
[
66+
{
67+
'henry': 'the first'
68+
},
69+
{
70+
'jacob' : 'the second'
71+
}
72+
]
73+
])
74+
>>>
75+
[
76+
{
77+
'spam.eggs' : 'spam and eggs'
78+
},
79+
{
80+
'1.henry' : 'the first'
81+
},
82+
{
83+
'2.jacob' : 'the second'
84+
}
85+
]
86+
"""
87+
88+
result = []
89+
90+
for element in configuration:
91+
temp = {}
92+
if isinstance(element, list):
93+
for index, el in enumerate(element):
94+
for key, value in el.items():
95+
temp['{i}.{key}'.format(i=index + 1, key=key)] = value
96+
result = result + intermediate_to_list([temp])
97+
98+
elif isinstance(element, dict):
99+
temp.update(shrink(element))
100+
result.append(temp)
101+
102+
else:
103+
raise Exception('malformed intermediate representation')
104+
105+
return result

tests/airos/test_intermediate.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import unittest
22

3-
from netjsonconfig.backends.airos.airos import intermediate_to_list
3+
from netjsonconfig.backends.airos.intermediate import intermediate_to_list
44

55

66
class TestIntermediateConversion(unittest.TestCase):

0 commit comments

Comments
 (0)