userver: en/testsuite/utils/ordered_object.py Source File
Loading...
Searching...
No Matches
ordered_object.py
1import copy
2
3
4def order(source, paths):
5 sort_root = '' in paths
6 result = _order(source, paths)
7
8 if sort_root and isinstance(result, (list, tuple)):
9 result = sorted(result, key=_sort_key)
10
11 return result
12
13
14def assert_eq(first_source, second_source, paths):
15 assert order(first_source, paths) == order(second_source, paths)
16
17
18def _order(source, paths):
19 if isinstance(source, list):
20 return [_order(value, paths) for value in source]
21 elif isinstance(source, dict):
22 source_copy = copy.copy(source)
23 for path in sorted(paths, reverse=True):
24 head_tail = path.split('.', 1)
25 head = head_tail[0]
26 if head not in source_copy:
27 continue
28 value = source_copy[head]
29 if len(head_tail) == 1:
30 if isinstance(value, (list, tuple)):
31 source_copy[head] = sorted(value, key=_sort_key)
32 else:
33 source_copy[head] = _order(value, [head_tail[1]])
34 return source_copy
35
36 return source
37
38
39def _sort_key(value):
40 if isinstance(value, dict):
41 return (
42 type(value).__name__,
43 [
44 (k, _sort_key(v))
45 for k, v in sorted(value.items(), key=_sort_key)
46 ],
47 )
48 if isinstance(value, (list, tuple)):
49 return (
50 type(value).__name__,
51 [_sort_key(v) for v in sorted(value, key=_sort_key)],
52 )
53 return (type(value).__name__, value)