format_dict() returns no value for None

We have some subtle cases to distinguish:
* value of None   (the Python literal)
* value of ''     (an empty string)
* value of 'None' (a string)

Return no representation of data when the value is the Python literal None
rather than the string 'None' which can be confused for an actual string value.

Returning an empty string ('') can be confused for an actual empty
string so that is also not an option.  By leaving off the quotes we can accurately
reflect the distinct value of None.

Change-Id: Icdc1712e626a7e8a706348586a6be2e7612c4376
Signed-off-by: Dean Troyer <dtroyer@gmail.com>
This commit is contained in:
Dean Troyer 2019-09-02 09:37:30 -05:00
parent 6db6492a7d
commit a0d9746eb5
2 changed files with 9 additions and 7 deletions

View File

@ -690,18 +690,18 @@ class TestFindResource(test_utils.TestCase):
self.assertIsNone(utils.format_dict(None))
def test_format_dict_recursive(self):
expected = "a='b', c.1='d', c.2='e'"
expected = "a='b', c.1='d', c.2=''"
self.assertEqual(
expected,
utils.format_dict({'a': 'b', 'c': {'1': 'd', '2': 'e'}})
utils.format_dict({'a': 'b', 'c': {'1': 'd', '2': ''}})
)
self.assertEqual(
expected,
utils.format_dict({'c': {'1': 'd', '2': 'e'}, 'a': 'b'})
utils.format_dict({'c': {'1': 'd', '2': ''}, 'a': 'b'})
)
self.assertIsNone(utils.format_dict(None))
expected = "a1='A', a2.b1.c1='B', a2.b1.c2='C', a2.b2='D'"
expected = "a1='A', a2.b1.c1='B', a2.b1.c2=, a2.b2='D'"
self.assertEqual(
expected,
utils.format_dict(
@ -710,7 +710,7 @@ class TestFindResource(test_utils.TestCase):
'a2': {
'b1': {
'c1': 'B',
'c2': 'C',
'c2': None,
},
'b2': 'D',
},
@ -723,7 +723,7 @@ class TestFindResource(test_utils.TestCase):
{
'a2': {
'b1': {
'c2': 'C',
'c2': None,
'c1': 'B',
},
'b2': 'D',

View File

@ -315,8 +315,10 @@ def format_dict(data, prefix=None):
# NOTE(dtroyer): Only append the separator chars here, quoting
# is completely handled in the terminal case.
output = output + format_dict(data[s], prefix=key_str) + ", "
else:
elif data[s] is not None:
output = output + key_str + "='" + six.text_type(data[s]) + "', "
else:
output = output + key_str + "=, "
return output[:-2]