From 8b8edc72e0b9eedbcadbef2643dca0c69dd35dba Mon Sep 17 00:00:00 2001 From: jichenjc Date: Sat, 21 Nov 2015 01:33:10 +0800 Subject: [PATCH] Not transform to str on potential unicode fields some fields such as instance.display_name can be unicode, nova client should not translate it to 'str'. otherwise it will report UnicodeEncodeError. Change-Id: I4f6011105b3b11dbbcb23f3a7c1bbcf7f20bcc8c Closes-Bug: 1518141 --- novaclient/tests/unit/test_utils.py | 31 +++++++++++++++++++++++++++++ novaclient/utils.py | 4 ++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/novaclient/tests/unit/test_utils.py b/novaclient/tests/unit/test_utils.py index d4eff35c2..2eb3f0695 100644 --- a/novaclient/tests/unit/test_utils.py +++ b/novaclient/tests/unit/test_utils.py @@ -14,6 +14,7 @@ import sys import mock +from oslo_utils import encodeutils import six from novaclient import base @@ -215,6 +216,21 @@ class PrintResultTestCase(test_utils.TestCase): '+------+-------+\n', sys.stdout.getvalue()) + @mock.patch('sys.stdout', six.StringIO()) + def test_print_unicode_list(self): + objs = [_FakeResult("k", u'\u2026')] + utils.print_list(objs, ["Name", "Value"]) + if six.PY3: + s = u'\u2026' + else: + s = encodeutils.safe_encode(u'\u2026') + self.assertEqual('+------+-------+\n' + '| Name | Value |\n' + '+------+-------+\n' + '| k | %s |\n' + '+------+-------+\n' % s, + sys.stdout.getvalue()) + # without sorting @mock.patch('sys.stdout', six.StringIO()) def test_print_list_sort_by_none(self): @@ -280,6 +296,21 @@ class PrintResultTestCase(test_utils.TestCase): '+----------+------------------------------------------+\n', sys.stdout.getvalue()) + @mock.patch('sys.stdout', six.StringIO()) + def test_print_unicode_dict(self): + dict = {'k': u'\u2026'} + utils.print_dict(dict) + if six.PY3: + s = u'\u2026' + else: + s = encodeutils.safe_encode(u'\u2026') + self.assertEqual('+----------+-------+\n' + '| Property | Value |\n' + '+----------+-------+\n' + '| k | %s |\n' + '+----------+-------+\n' % s, + sys.stdout.getvalue()) + class FlattenTestCase(test_utils.TestCase): def test_flattening(self): diff --git a/novaclient/utils.py b/novaclient/utils.py index b420a29d9..981635c33 100644 --- a/novaclient/utils.py +++ b/novaclient/utils.py @@ -98,7 +98,7 @@ def print_list(objs, fields, formatters={}, sortby_index=None): if data is None: data = '-' # '\r' would break the table, so remove it. - data = str(data).replace("\r", "") + data = six.text_type(data).replace("\r", "") row.append(data) pt.add_row(row) @@ -162,7 +162,7 @@ def print_dict(d, dict_property="Property", dict_value="Value", wrap=0): if isinstance(v, (dict, list)): v = jsonutils.dumps(v) if wrap > 0: - v = textwrap.fill(str(v), wrap) + v = textwrap.fill(six.text_type(v), wrap) # if value has a newline, add in multiple rows # e.g. fault with stacktrace if v and isinstance(v, six.string_types) and (r'\n' in v or '\r' in v):