Ticket #12849: colorize_unicode.diff
File colorize_unicode.diff, 2.8 KB (added by , 15 years ago) |
---|
-
django/utils/termcolors.py
2 2 termcolors.py 3 3 """ 4 4 5 import locale 6 from django.utils.encoding import smart_str 7 8 5 9 color_names = ('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white') 6 10 foreground = dict([(color_names[x], '3%s' % x) for x in range(8)]) 7 11 background = dict([(color_names[x], '4%s' % x) for x in range(8)]) … … 9 13 RESET = '0' 10 14 opt_dict = {'bold': '1', 'underscore': '4', 'blink': '5', 'reverse': '7', 'conceal': '8'} 11 15 12 def colorize(text= '', opts=(), **kwargs):16 def colorize(text=u'', opts=(), encoding=None, **kwargs): 13 17 """ 14 18 Returns your text, enclosed in ANSI graphics codes. 15 19 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. 18 24 19 25 Returns the RESET code if no parameters are given. 20 26 … … 38 44 print colorize('and so should this') 39 45 print 'this should not be red' 40 46 """ 41 text = str(text) 47 if encoding is None: 48 encoding = locale.getpreferredencoding() 49 text = smart_str(text, encoding=encoding) 42 50 code_list = [] 43 51 if text == '' and len(opts) == 1 and opts[0] == 'reset': 44 52 return '\x1b[%sm' % RESET -
tests/regressiontests/utils/termcolors.py
1 1 from unittest import TestCase 2 2 3 from django.utils.termcolors import parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE3 from django.utils.termcolors import colorize, parse_color_setting, PALETTES, DEFAULT_PALETTE, LIGHT_PALETTE, DARK_PALETTE, NOCOLOR_PALETTE 4 4 5 5 class TermColorTests(TestCase): 6 6 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 7 19 def test_empty_string(self): 8 20 self.assertEquals(parse_color_setting(''), PALETTES[DEFAULT_PALETTE]) 9 21