ListType preserves the order of the input

The ListType class returns a list of items in a string.
The list was not guaranteed to be the same order as in the string;
this patch changes it so that the order is preserved.

Related-Bug: #1715541
Change-Id: Iefab751d34e97f460b6d63316eb38085e4eb1154
This commit is contained in:
Ruby Loo 2017-09-20 18:19:17 -04:00
parent 4ce27f6522
commit f8a42d366c
2 changed files with 16 additions and 13 deletions

View File

@ -162,12 +162,15 @@ class ListType(wtypes.UserType):
"""Validate and convert the input to a ListType. """Validate and convert the input to a ListType.
:param value: A comma separated string of values :param value: A comma separated string of values
:returns: A list of unique values, whose order is not guaranteed. :returns: A list of unique values (lower-cased), maintaining the
same order
""" """
items = [v.strip().lower() for v in six.text_type(value).split(',')] items = []
# filter() to remove empty items for v in six.text_type(value).split(','):
# set() to remove duplicated items v_norm = v.strip().lower()
return list(set(filter(None, items))) if v_norm and v_norm not in items:
items.append(v_norm)
return items
@staticmethod @staticmethod
def frombasetype(value): def frombasetype(value):

View File

@ -277,14 +277,14 @@ class TestListType(base.TestCase):
def test_list_type(self): def test_list_type(self):
v = types.ListType() v = types.ListType()
self.assertItemsEqual(['foo', 'bar'], v.validate('foo,bar')) self.assertEqual(['foo', 'bar'], v.validate('foo,bar'))
self.assertItemsEqual(['cat', 'meow'], v.validate("cat , meow")) self.assertNotEqual(['bar', 'foo'], v.validate('foo,bar'))
self.assertItemsEqual(['spongebob', 'squarepants'],
v.validate("SpongeBob,SquarePants")) self.assertEqual(['cat', 'meow'], v.validate("cat , meow"))
self.assertItemsEqual(['foo', 'bar'], self.assertEqual(['spongebob', 'squarepants'],
v.validate("foo, ,,bar")) v.validate("SpongeBob,SquarePants"))
self.assertItemsEqual(['foo', 'bar'], self.assertEqual(['foo', 'bar'], v.validate("foo, ,,bar"))
v.validate("foo,foo,foo,bar")) self.assertEqual(['foo', 'bar'], v.validate("foo,foo,foo,bar"))
self.assertIsInstance(v.validate('foo,bar'), list) self.assertIsInstance(v.validate('foo,bar'), list)