Merge "Flatten hypervisor-show dictionary for printing"

This commit is contained in:
Jenkins 2013-11-14 07:50:57 +00:00 committed by Gerrit Code Review
commit dc0aacfd04
3 changed files with 64 additions and 8 deletions

View File

@ -163,3 +163,24 @@ class PrintResultTestCase(test_utils.TestCase):
'| k3 | 3 |\n'
'| k2 | 2 |\n'
'+------+-------+\n')
class FlattenTestCase(test_utils.TestCase):
def test_flattening(self):
squashed = utils.flatten_dict(
{'a1': {'b1': 1234,
'b2': 'string',
'b3': set((1, 2, 3)),
'b4': {'c1': ['l', 'l', ['l']],
'c2': 'string'}},
'a2': ['l'],
'a3': ('t',)})
self.assertEqual({'a1_b1': 1234,
'a1_b2': 'string',
'a1_b3': set([1, 2, 3]),
'a1_b4_c1': ['l', 'l', ['l']],
'a1_b4_c2': 'string',
'a2': ['l'],
'a3': ('t',)},
squashed)

View File

@ -1,3 +1,4 @@
import json
import os
import pkg_resources
import re
@ -177,6 +178,47 @@ def print_list(objs, fields, formatters={}, sortby_index=None):
print(result)
def _flatten(data, prefix=None):
"""Flatten a dict, using name as a prefix for the keys of dict.
>>> _flatten('cpu_info', {'arch':'x86_64'})
[('cpu_info_arch': 'x86_64')]
"""
if isinstance(data, dict):
for key, value in six.iteritems(data):
new_key = '%s_%s' % (prefix, key) if prefix else key
if isinstance(value, (dict, list)):
for item in _flatten(value, new_key):
yield item
else:
yield new_key, value
else:
yield prefix, data
def flatten_dict(data):
"""Return a new dict whose sub-dicts have been merged into the
original. Each of the parents keys are prepended to the child's
to prevent collisions. Any string elements will be JSON parsed
before flattening.
>>> flatten_dict({'service': {'host':'cloud9@compute-068', 'id': 143}})
{'service_host': colud9@compute-068', 'service_id': 143}
"""
data = data.copy()
# Try and decode any nested JSON structures.
for key, value in six.iteritems(data):
if isinstance(value, six.string_types):
try:
data[key] = json.loads(value)
except ValueError:
pass
return dict(_flatten(data))
def print_dict(d, dict_property="Property", dict_value="Value", wrap=0):
pt = prettytable.PrettyTable([dict_property, dict_value], caching=False)
pt.align = 'l'

View File

@ -2939,14 +2939,7 @@ def do_hypervisor_servers(cs, args):
def do_hypervisor_show(cs, args):
"""Display the details of the specified hypervisor."""
hyper = _find_hypervisor(cs, args.hypervisor)
# Build up the dict
info = hyper._info.copy()
info['service_id'] = info['service']['id']
info['service_host'] = info['service']['host']
del info['service']
utils.print_dict(info)
utils.print_dict(utils.flatten_dict(hyper._info))
@utils.arg('hypervisor',