From 2ec9a2251d1faa8a167e975bccbaa2e59137e47d Mon Sep 17 00:00:00 2001 From: liyingjun Date: Tue, 21 Jul 2015 12:50:14 +0800 Subject: [PATCH] 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 --- cinderclient/tests/unit/test_utils.py | 34 +++++++++++++++++++++++++++ cinderclient/utils.py | 8 ++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/cinderclient/tests/unit/test_utils.py b/cinderclient/tests/unit/test_utils.py index 73a39b9..2d2ebd1 100644 --- a/cinderclient/tests/unit/test_utils.py +++ b/cinderclient/tests/unit/test_utils.py @@ -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()) diff --git a/cinderclient/utils.py b/cinderclient/utils.py index 896c646..89478bd 100644 --- a/cinderclient/utils.py +++ b/cinderclient/utils.py @@ -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)