Fixes table when there are multiline in result data

The table doesn't display right when there are multiple line in
result data. Fixes this by replace "\r" with " ".

Change-Id: I0b994466f3c65ea973e80d9f03ca9a248147d49d
Closes-bug: #1476462
This commit is contained in:
liyingjun 2015-07-21 12:50:14 +08:00
parent a0f13ea8f1
commit 2ec9a2251d
2 changed files with 41 additions and 1 deletions

View File

@ -203,4 +203,38 @@ class PrintListTestCase(test_utils.TestCase):
| 1 | 2 |
| 3 | 4 |
+---+---+
""", cso.read())
def test_print_list_with_return(self):
Row = collections.namedtuple('Row', ['a', 'b'])
to_print = [Row(a=3, b='a\r'), Row(a=1, b='c\rd')]
with CaptureStdout() as cso:
utils.print_list(to_print, ['a', 'b'])
# Output should be sorted by the first key (a)
self.assertEqual("""\
+---+-----+
| a | b |
+---+-----+
| 1 | c d |
| 3 | a |
+---+-----+
""", cso.read())
class PrintDictTestCase(test_utils.TestCase):
def test_print_dict_with_return(self):
d = {'a': 'A', 'b': 'B', 'c': 'C', 'd': 'test\rcarriage\n\rreturn'}
with CaptureStdout() as cso:
utils.print_dict(d)
self.assertEqual("""\
+----------+---------------+
| Property | Value |
+----------+---------------+
| a | A |
| b | B |
| c | C |
| d | test carriage |
| | return |
+----------+---------------+
""", cso.read())

View File

@ -141,6 +141,8 @@ def print_list(objs, fields, formatters=None, sortby_index=0):
data = getattr(o, field_name, '')
if data is None:
data = '-'
if isinstance(data, six.string_types) and "\r" in data:
data = data.replace("\r", " ")
row.append(data)
pt.add_row(row)
@ -154,7 +156,11 @@ def print_list(objs, fields, formatters=None, sortby_index=0):
def print_dict(d, property="Property"):
pt = prettytable.PrettyTable([property, 'Value'], caching=False)
pt.aligns = ['l', 'l']
[pt.add_row(list(r)) for r in six.iteritems(d)]
for r in six.iteritems(d):
r = list(r)
if isinstance(r[1], six.string_types) and "\r" in r[1]:
r[1] = r[1].replace("\r", " ")
pt.add_row(r)
_print(pt, property)