Skip to content

Commit 20124ec

Browse files
sort_list support for python 3 (#115)
sort_list support for python 3 Reviewed-by: https://github.com/apps/ansible-zuul
1 parent cd2b2cc commit 20124ec

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
---
2+
bugfixes:
3+
- sort_list will sort a list of dicts using the sorted method with key as an argument.

plugins/module_utils/network/common/utils.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,15 @@ def transform_commands(module):
150150

151151
def sort_list(val):
152152
if isinstance(val, list):
153+
if isinstance(val[0], dict):
154+
sorted_keys = [tuple(sorted(dict_.keys())) for dict_ in val]
155+
# All keys should be identical
156+
if len(set(sorted_keys)) != 1:
157+
raise ValueError("dictionaries do not match")
158+
159+
return sorted(
160+
val, key=lambda d: tuple(d[k] for k in sorted_keys[0])
161+
)
153162
return sorted(val)
154163
return val
155164

tests/unit/module_utils/network/common/test_utils.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,13 +144,37 @@ def test_transform_commands():
144144
]
145145

146146

147-
def test_sort():
147+
def test_sort_list():
148148
data = [3, 1, 2]
149149
assert [1, 2, 3] == utils.sort_list(data)
150150

151-
string_data = "123"
151+
string_data = "312"
152152
assert string_data == utils.sort_list(string_data)
153153

154+
data = [{"a": 1, "b": 2}, {"a": 1, "c": 1}, {"a": 1, "b": 0}]
155+
with pytest.raises(ValueError, match="dictionaries do not match"):
156+
utils.sort_list(data)
157+
158+
data = [{"a": 1, "b": 2}, {"a": 1, "b": 1}, {"a": 0, "b": 3}]
159+
assert utils.sort_list(data) == [
160+
{"a": 0, "b": 3},
161+
{"a": 1, "b": 1},
162+
{"a": 1, "b": 2},
163+
]
164+
165+
data = [
166+
{"a": 1, "c": [1, 2, 3], "b": 1},
167+
{"a": 1, "c": [3, 4, 5], "b": 0},
168+
{"a": 1, "c": [1, 1], "b": 0},
169+
{"a": 0, "c": [99, 98, 97, 96, 95], "b": 27},
170+
]
171+
assert utils.sort_list(data) == [
172+
{"a": 0, "b": 27, "c": [99, 98, 97, 96, 95]},
173+
{"a": 1, "b": 0, "c": [1, 1]},
174+
{"a": 1, "b": 0, "c": [3, 4, 5]},
175+
{"a": 1, "b": 1, "c": [1, 2, 3]},
176+
]
177+
154178

155179
def test_dict_diff():
156180
with pytest.raises(AssertionError, match="`base` must be of type <dict>"):

0 commit comments

Comments
 (0)