Ensure list output function can support non-sorting printing

Ensure list printing function in utils can handle non-sorting
calls. Allow result list can be formatted and outputted without any
sorting field, keep natural order to the list printing. Adding necessary
checking to avoid prettytable (0.6.1 for me) exception: "Invalid field
name: None!".

Fix bug: #1099732

Change-Id: Ied869d987e608fff8b8b5f5a65d21e02f0cebeaa
Signed-off-by: zhiyanliu <lzy.dev@gmail.com>
This commit is contained in:
zhiyanliu 2013-01-17 11:51:46 +08:00
parent 24087862c7
commit 3e190c5e49
2 changed files with 68 additions and 1 deletions

View File

@ -161,7 +161,10 @@ def print_list(objs, fields, formatters={}, sortby_index=0):
row.append(data)
pt.add_row(row)
if sortby is not None:
print pt.get_string(sortby=sortby)
else:
print pt.get_string()
def print_dict(d, dict_property="Property"):

View File

@ -1,3 +1,7 @@
import StringIO
import sys
import mock
from novaclient import exceptions
from novaclient import utils
@ -99,3 +103,63 @@ class FindResourceTestCase(test_utils.TestCase):
display_manager = FakeDisplayManager(None)
output = utils.find_resource(display_manager, 'entity_three')
self.assertEqual(output, display_manager.get('4242'))
class _FakeResult(object):
def __init__(self, name, value):
self.name = name
self.value = value
class PrintResultTestCase(test_utils.TestCase):
@mock.patch('sys.stdout', StringIO.StringIO())
def test_print_list_sort_by_str(self):
objs = [_FakeResult("k1", 1),
_FakeResult("k3", 2),
_FakeResult("k2", 3)]
utils.print_list(objs, ["Name", "Value"], sortby_index=0)
self.assertEqual(sys.stdout.getvalue(),
'+------+-------+\n'
'| Name | Value |\n'
'+------+-------+\n'
'| k1 | 1 |\n'
'| k2 | 3 |\n'
'| k3 | 2 |\n'
'+------+-------+\n')
@mock.patch('sys.stdout', StringIO.StringIO())
def test_print_list_sort_by_integer(self):
objs = [_FakeResult("k1", 1),
_FakeResult("k3", 2),
_FakeResult("k2", 3)]
utils.print_list(objs, ["Name", "Value"], sortby_index=1)
self.assertEqual(sys.stdout.getvalue(),
'+------+-------+\n'
'| Name | Value |\n'
'+------+-------+\n'
'| k1 | 1 |\n'
'| k3 | 2 |\n'
'| k2 | 3 |\n'
'+------+-------+\n')
# without sorting
@mock.patch('sys.stdout', StringIO.StringIO())
def test_print_list_sort_by_none(self):
objs = [_FakeResult("k1", 1),
_FakeResult("k3", 3),
_FakeResult("k2", 2)]
utils.print_list(objs, ["Name", "Value"], sortby_index=None)
self.assertEqual(sys.stdout.getvalue(),
'+------+-------+\n'
'| Name | Value |\n'
'+------+-------+\n'
'| k1 | 1 |\n'
'| k3 | 3 |\n'
'| k2 | 2 |\n'
'+------+-------+\n')