Merge "Fix sorting in Python 3"

This commit is contained in:
Zuul 2018-01-03 16:55:52 +00:00 committed by Gerrit Code Review
commit e7dc7ce546
2 changed files with 55 additions and 3 deletions

View File

@ -13,6 +13,7 @@
# under the License.
#
import six
import time
import uuid
@ -199,6 +200,43 @@ class TestUtils(test_utils.TestCase):
utils.sort_items,
items, sort_str)
def test_sort_items_with_different_type_exception(self):
item1 = {'a': 2}
item2 = {'a': 3}
item3 = {'a': None}
item4 = {'a': 1}
items = [item1, item2, item3, item4]
sort_str = 'a'
expect_items = [item3, item4, item1, item2]
if six.PY2:
self.assertEqual(expect_items, utils.sort_items(items, sort_str))
else:
self.assertRaises(TypeError, utils.sort_items, items, sort_str)
def test_sort_items_with_different_type_int(self):
item1 = {'a': 2}
item2 = {'a': 3}
item3 = {'a': None}
item4 = {'a': 1}
items = [item1, item2, item3, item4]
sort_str = 'a'
sort_type = int
expect_items = [item3, item4, item1, item2]
self.assertEqual(expect_items, utils.sort_items(items, sort_str,
sort_type))
def test_sort_items_with_different_type_str(self):
item1 = {'a': 'a'}
item2 = {'a': None}
item3 = {'a': '2'}
item4 = {'a': 'b'}
items = [item1, item2, item3, item4]
sort_str = 'a'
sort_type = str
expect_items = [item3, item2, item1, item4]
self.assertEqual(expect_items, utils.sort_items(items, sort_str,
sort_type))
@mock.patch.object(time, 'sleep')
def test_wait_for_delete_ok(self, mock_sleep):
# Tests the normal flow that the resource is deleted with a 404 coming

View File

@ -545,7 +545,7 @@ def read_blob_file_contents(blob_file):
raise exceptions.CommandError(msg % blob_file)
def sort_items(items, sort_str):
def sort_items(items, sort_str, sort_type=None):
"""Sort items based on sort keys and sort directions given by sort_str.
:param items: a list or generator object of items
@ -580,8 +580,22 @@ def sort_items(items, sort_str):
})
if direction == 'desc':
reverse = True
items.sort(key=lambda item: get_field(item, sort_key),
reverse=reverse)
def f(x):
# Attempts to convert items to same 'sort_type' if provided.
# This is due to Python 3 throwing TypeError if you attempt to
# compare different types
item = get_field(x, sort_key)
if sort_type and not isinstance(item, sort_type):
try:
item = sort_type(item)
except Exception:
# Can't convert, so no sensible way to compare
item = sort_type()
return item
items.sort(key=f, reverse=reverse)
return items