Ticket #12849: colorize_unicode.diff

File colorize_unicode.diff, 2.8 KB (added by Fraser Nevett, 15 years ago)
  • django/utils/termcolors.py

     
    22termcolors.py
    33"""
    44
     5import locale
     6from django.utils.encoding import smart_str
     7
     8
    59color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white')
    610foreground = dict([(color_names[x], '3%s' % x) for x in range(8)])
    711background = dict([(color_names[x], '4%s' % x) for x in range(8)])
     
    913RESET = '0'
    1014opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'}
    1115
    12 def colorize(text='', opts=(), **kwargs):
     16def colorize(text=u'', opts=(), encoding=None, **kwargs):
    1317    """
    1418    Returns your text, enclosed in ANSI graphics codes.
    1519
    16     Depends on the keyword arguments 'fg' and 'bg', and the contents of
    17     the opts tuple/list.
     20    The returned string depends on the keyword arguments 'fg' and 'bg', and
     21    the contents of the opts tuple/list. The text will be encoded using the
     22    current locale's preferred encoding unless otherwise specified in the
     23    'encoding' keyword argument.
    1824
    1925    Returns the RESET code if no parameters are given.
    2026
     
    3844        print colorize('and so should this')
    3945        print 'this should not be red'
    4046    """
    41     text = str(text)
     47    if encoding is None:
     48        encoding = locale.getpreferredencoding()
     49    text = smart_str(text, encoding=encoding)
    4250    code_list = []
    4351    if text == '' and len(opts) == 1 and opts[0] == 'reset':
    4452        return '\x1b[%sm' % RESET
  • tests/regressiontests/utils/termcolors.py

     
    11from unittest import TestCase
    22
    3 from django.utils.termcolors import parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE
     3from django.utils.termcolors import colorize, parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE
    44
    55class TermColorTests(TestCase):
    66
     7    def test_encoding(self):
     8        """Verify that unicode strings are accepted and propertly encoded."""
     9        test_data = (
     10            ('\xc2\xa3', 'utf-8', '\xc2\xa3'),
     11            ('\xc2\xa3', 'latin-1', '\xa3'),
     12            (u'\u00a3', 'utf-8', '\xc2\xa3'),
     13            (u'\u00a3', 'latin-1', '\xa3'),
     14            )
     15        for input, encoding, encoded in test_data:
     16            output = colorize(input, fg='red', encoding=encoding)
     17            self.assertEquals(output, '\x1b[31m%s\x1b[0m' % encoded)
     18
    719    def test_empty_string(self):
    820        self.assertEquals(parse_color_setting(''), PALETTES[DEFAULT_PALETTE])
    921
Back to Top