Avoid 'NoneType' error when format conversion

Error raise when changing a 'None' data to a new format:
"TypeError: 'NoneType' object is not iterable"
we also met that bug before in the previous patch [1]

This change is to handle the 'None' data and avoid
the error

[1] https://review.openstack.org/#/c/420420/

Change-Id: I649b4fc65ef7c19b8193b07f3bd59f00e6095f9f
Closes-bug: #1656363
This commit is contained in:
Huanxuan Ao 2017-02-16 17:15:44 +08:00
parent 8b5f50dae3
commit e45dc8776e
2 changed files with 10 additions and 0 deletions

View File

@ -498,11 +498,13 @@ class TestFindResource(test_utils.TestCase):
utils.format_dict({'a': 'b', 'c': 'd', 'e': 'f'}))
self.assertEqual(expected,
utils.format_dict({'e': 'f', 'c': 'd', 'a': 'b'}))
self.assertEqual(None, utils.format_dict(None))
def test_format_list(self):
expected = 'a, b, c'
self.assertEqual(expected, utils.format_list(['a', 'b', 'c']))
self.assertEqual(expected, utils.format_list(['c', 'b', 'a']))
self.assertEqual(None, utils.format_list(None))
def test_format_list_of_dicts(self):
expected = "a='b', c='d'\ne='f'"
@ -512,6 +514,7 @@ class TestFindResource(test_utils.TestCase):
self.assertEqual(expected, utils.format_list_of_dicts(unsorted_data))
self.assertEqual('', utils.format_list_of_dicts([]))
self.assertEqual('', utils.format_list_of_dicts([{}]))
self.assertEqual(None, utils.format_list_of_dicts(None))
def test_format_list_separator(self):
expected = 'a\nb\nc'

View File

@ -192,6 +192,9 @@ def format_dict(data):
:rtype: a string formatted to key='value'
"""
if data is None:
return None
output = ""
for s in sorted(data):
output = output + s + "='" + six.text_type(data[s]) + "', "
@ -205,6 +208,8 @@ def format_list(data, separator=', '):
:param separator: the separator to use between strings (default: ', ')
:rtype: a string formatted based on separator
"""
if data is None:
return None
return separator.join(sorted(data))
@ -215,6 +220,8 @@ def format_list_of_dicts(data):
:param data: a list of dicts
:rtype: a string formatted to key='value' with dicts separated by new line
"""
if data is None:
return None
return '\n'.join(format_dict(i) for i in data)