From e45dc8776e7c44ffb09f650b12b65246e5d2b375 Mon Sep 17 00:00:00 2001 From: Huanxuan Ao Date: Thu, 16 Feb 2017 17:15:44 +0800 Subject: [PATCH] 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 --- osc_lib/tests/test_utils.py | 3 +++ osc_lib/utils.py | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/osc_lib/tests/test_utils.py b/osc_lib/tests/test_utils.py index 4128fac..b1bef70 100644 --- a/osc_lib/tests/test_utils.py +++ b/osc_lib/tests/test_utils.py @@ -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' diff --git a/osc_lib/utils.py b/osc_lib/utils.py index 3d7d1dc..4f3d34f 100644 --- a/osc_lib/utils.py +++ b/osc_lib/utils.py @@ -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)