From 0e0284f9671ebe516139507ae9fb9feffa5507ff Mon Sep 17 00:00:00 2001 From: Chase Sterling Date: Thu, 27 Feb 2014 23:44:40 -0500 Subject: [PATCH] ColoredString doesn't attempt to decode explicitly given bytes in python 2 --- clint/textui/colored.py | 31 +++++++++++++++++-------------- test_clint.py | 8 ++++++++ 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/clint/textui/colored.py b/clint/textui/colored.py index 71f3723..86753c6 100644 --- a/clint/textui/colored.py +++ b/clint/textui/colored.py @@ -48,19 +48,19 @@ class ColoredString(object): self.bold = bold def __getattr__(self, att): - def func_help(*args, **kwargs): - result = getattr(self.s, att)(*args, **kwargs) - try: - is_result_string = isinstance(result, basestring) - except NameError: - is_result_string = isinstance(result, str) - if is_result_string: - return self._new(result) - elif isinstance(result, list): - return [self._new(x) for x in result] - else: - return result - return func_help + def func_help(*args, **kwargs): + result = getattr(self.s, att)(*args, **kwargs) + try: + is_result_string = isinstance(result, basestring) + except NameError: + is_result_string = isinstance(result, str) + if is_result_string: + return self._new(result) + elif isinstance(result, list): + return [self._new(x) for x in result] + else: + return result + return func_help @property def color_str(self): @@ -91,7 +91,10 @@ class ColoredString(object): __str__ = __unicode__ else: def __str__(self): - return unicode(self).encode('utf8') + value = self.color_str + if isinstance(value, bytes): + return value + return value.encode('utf8') def __iter__(self): return iter(self.color_str) diff --git a/test_clint.py b/test_clint.py index cd6c349..09c7a4d 100755 --- a/test_clint.py +++ b/test_clint.py @@ -42,5 +42,13 @@ class ColoredStringTestCase(unittest.TestCase): output = new_str.replace("world", "universe") assert output.s == "hello universe" + def test_py2_bytes_not_mangled(self): + from clint.textui.colored import ColoredString + # On python 2 make sure the same bytes come out as went in + new_str = ColoredString('RED', '\xe4') + assert '\xe4' in str(new_str) + from clint.textui import puts + puts(new_str) + if __name__ == '__main__': unittest.main()