1 # -*- coding: iso-8859-1 -*-
2 """ Test script for the Unicode implementation.
4 Written by Marc-Andre Lemburg (mal@lemburg.com).
6 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
9 import sys
, struct
, codecs
10 from test
import test_support
, string_tests
12 # Error handling (bad decoder return)
13 def search_function(encoding
):
14 def decode1(input, errors
="strict"):
15 return 42 # not a tuple
16 def encode1(input, errors
="strict"):
17 return 42 # not a tuple
18 def encode2(input, errors
="strict"):
19 return (42, 42) # no unicode
20 def decode2(input, errors
="strict"):
21 return (42, 42) # no unicode
22 if encoding
=="test.unicode1":
23 return (encode1
, decode1
, None, None)
24 elif encoding
=="test.unicode2":
25 return (encode2
, decode2
, None, None)
28 codecs
.register(search_function
)
31 string_tests
.CommonTest
,
32 string_tests
.MixinStrUnicodeUserStringTest
,
33 string_tests
.MixinStrUnicodeTest
,
37 def checkequalnofix(self
, result
, object, methodname
, *args
):
38 method
= getattr(object, methodname
)
39 realresult
= method(*args
)
40 self
.assertEqual(realresult
, result
)
41 self
.assertTrue(type(realresult
) is type(result
))
43 # if the original is returned make sure that
44 # this doesn't happen with subclasses
45 if realresult
is object:
48 return 'usub(%r)' % unicode.__repr
__(self
)
50 method
= getattr(object, methodname
)
51 realresult
= method(*args
)
52 self
.assertEqual(realresult
, result
)
53 self
.assertTrue(object is not realresult
)
55 def test_literals(self
):
56 self
.assertEqual(u
'\xff', u
'\u00ff')
57 self
.assertEqual(u
'\uffff', u
'\U0000ffff')
58 self
.assertRaises(SyntaxError, eval, 'u\'\\Ufffffffe\'')
59 self
.assertRaises(SyntaxError, eval, 'u\'\\Uffffffff\'')
60 self
.assertRaises(SyntaxError, eval, 'u\'\\U%08x\'' % 0x110000)
63 if not sys
.platform
.startswith('java'):
64 # Test basic sanity of repr()
65 self
.assertEqual(repr(u
'abc'), "u'abc'")
66 self
.assertEqual(repr(u
'ab\\c'), "u'ab\\\\c'")
67 self
.assertEqual(repr(u
'ab\\'), "u'ab\\\\'")
68 self
.assertEqual(repr(u
'\\c'), "u'\\\\c'")
69 self
.assertEqual(repr(u
'\\'), "u'\\\\'")
70 self
.assertEqual(repr(u
'\n'), "u'\\n'")
71 self
.assertEqual(repr(u
'\r'), "u'\\r'")
72 self
.assertEqual(repr(u
'\t'), "u'\\t'")
73 self
.assertEqual(repr(u
'\b'), "u'\\x08'")
74 self
.assertEqual(repr(u
"'\""), """u'\\'"'""")
75 self
.assertEqual(repr(u
"'\""), """u'\\'"'""")
76 self
.assertEqual(repr(u
"'"), '''u"'"''')
77 self
.assertEqual(repr(u
'"'), """u'"'""")
79 "u'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
80 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
81 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
82 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
83 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
84 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
85 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
86 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
87 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
88 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
89 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
90 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
91 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
93 testrepr
= repr(u
''.join(map(unichr, xrange(256))))
94 self
.assertEqual(testrepr
, latin1repr
)
95 # Test repr works on wide unicode escapes without overflow.
96 self
.assertEqual(repr(u
"\U00010000" * 39 + u
"\uffff" * 4096),
97 repr(u
"\U00010000" * 39 + u
"\uffff" * 4096))
100 def test_count(self
):
101 string_tests
.CommonTest
.test_count(self
)
102 # check mixed argument types
103 self
.checkequalnofix(3, 'aaa', 'count', u
'a')
104 self
.checkequalnofix(0, 'aaa', 'count', u
'b')
105 self
.checkequalnofix(3, u
'aaa', 'count', 'a')
106 self
.checkequalnofix(0, u
'aaa', 'count', 'b')
107 self
.checkequalnofix(0, u
'aaa', 'count', 'b')
108 self
.checkequalnofix(1, u
'aaa', 'count', 'a', -1)
109 self
.checkequalnofix(3, u
'aaa', 'count', 'a', -10)
110 self
.checkequalnofix(2, u
'aaa', 'count', 'a', 0, -1)
111 self
.checkequalnofix(0, u
'aaa', 'count', 'a', 0, -10)
114 self
.checkequalnofix(0, u
'abcdefghiabc', 'find', u
'abc')
115 self
.checkequalnofix(9, u
'abcdefghiabc', 'find', u
'abc', 1)
116 self
.checkequalnofix(-1, u
'abcdefghiabc', 'find', u
'def', 4)
118 self
.assertRaises(TypeError, u
'hello'.find
)
119 self
.assertRaises(TypeError, u
'hello'.find
, 42)
121 def test_rfind(self
):
122 string_tests
.CommonTest
.test_rfind(self
)
123 # check mixed argument types
124 self
.checkequalnofix(9, 'abcdefghiabc', 'rfind', u
'abc')
125 self
.checkequalnofix(12, 'abcdefghiabc', 'rfind', u
'')
126 self
.checkequalnofix(12, u
'abcdefghiabc', 'rfind', '')
128 def test_index(self
):
129 string_tests
.CommonTest
.test_index(self
)
130 # check mixed argument types
131 for (t1
, t2
) in ((str, unicode), (unicode, str)):
132 self
.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2(''))
133 self
.checkequalnofix(3, t1('abcdefghiabc'), 'index', t2('def'))
134 self
.checkequalnofix(0, t1('abcdefghiabc'), 'index', t2('abc'))
135 self
.checkequalnofix(9, t1('abcdefghiabc'), 'index', t2('abc'), 1)
136 self
.assertRaises(ValueError, t1('abcdefghiabc').index
, t2('hib'))
137 self
.assertRaises(ValueError, t1('abcdefghiab').index
, t2('abc'), 1)
138 self
.assertRaises(ValueError, t1('abcdefghi').index
, t2('ghi'), 8)
139 self
.assertRaises(ValueError, t1('abcdefghi').index
, t2('ghi'), -1)
141 def test_rindex(self
):
142 string_tests
.CommonTest
.test_rindex(self
)
143 # check mixed argument types
144 for (t1
, t2
) in ((str, unicode), (unicode, str)):
145 self
.checkequalnofix(12, t1('abcdefghiabc'), 'rindex', t2(''))
146 self
.checkequalnofix(3, t1('abcdefghiabc'), 'rindex', t2('def'))
147 self
.checkequalnofix(9, t1('abcdefghiabc'), 'rindex', t2('abc'))
148 self
.checkequalnofix(0, t1('abcdefghiabc'), 'rindex', t2('abc'), 0, -1)
150 self
.assertRaises(ValueError, t1('abcdefghiabc').rindex
, t2('hib'))
151 self
.assertRaises(ValueError, t1('defghiabc').rindex
, t2('def'), 1)
152 self
.assertRaises(ValueError, t1('defghiabc').rindex
, t2('abc'), 0, -1)
153 self
.assertRaises(ValueError, t1('abcdefghi').rindex
, t2('ghi'), 0, 8)
154 self
.assertRaises(ValueError, t1('abcdefghi').rindex
, t2('ghi'), 0, -1)
156 def test_translate(self
):
157 self
.checkequalnofix(u
'bbbc', u
'abababc', 'translate', {ord('a'):None})
158 self
.checkequalnofix(u
'iiic', u
'abababc', 'translate', {ord('a'):None, ord('b'):ord('i')})
159 self
.checkequalnofix(u
'iiix', u
'abababc', 'translate', {ord('a'):None, ord('b'):ord('i'), ord('c'):u
'x'})
160 self
.checkequalnofix(u
'<i><i><i>c', u
'abababc', 'translate', {ord('a'):None, ord('b'):u
'<i>'})
161 self
.checkequalnofix(u
'c', u
'abababc', 'translate', {ord('a'):None, ord('b'):u
''})
162 self
.checkequalnofix(u
'xyyx', u
'xzx', 'translate', {ord('z'):u
'yy'})
164 self
.assertRaises(TypeError, u
'hello'.translate
)
165 self
.assertRaises(TypeError, u
'abababc'.translate
, {ord('a'):''})
167 def test_split(self
):
168 string_tests
.CommonTest
.test_split(self
)
171 self
.checkequalnofix([u
'a', u
'b', u
'c', u
'd'], u
'a//b//c//d', 'split', '//')
172 self
.checkequalnofix([u
'a', u
'b', u
'c', u
'd'], 'a//b//c//d', 'split', u
'//')
173 self
.checkequalnofix([u
'endcase ', u
''], u
'endcase test', 'split', 'test')
176 string_tests
.MixinStrUnicodeUserStringTest
.test_join(self
)
179 self
.checkequalnofix(u
'a b c d', u
' ', 'join', ['a', 'b', u
'c', u
'd'])
180 self
.checkequalnofix(u
'abcd', u
'', 'join', (u
'a', u
'b', u
'c', u
'd'))
181 self
.checkequalnofix(u
'w x y z', u
' ', 'join', string_tests
.Sequence('wxyz'))
182 self
.checkequalnofix(u
'a b c d', ' ', 'join', [u
'a', u
'b', u
'c', u
'd'])
183 self
.checkequalnofix(u
'a b c d', ' ', 'join', ['a', 'b', u
'c', u
'd'])
184 self
.checkequalnofix(u
'abcd', '', 'join', (u
'a', u
'b', u
'c', u
'd'))
185 self
.checkequalnofix(u
'w x y z', ' ', 'join', string_tests
.Sequence(u
'wxyz'))
187 def test_strip(self
):
188 string_tests
.CommonTest
.test_strip(self
)
189 self
.assertRaises(UnicodeError, u
"hello".strip
, "\xff")
191 def test_replace(self
):
192 string_tests
.CommonTest
.test_replace(self
)
194 # method call forwarded from str implementation because of unicode argument
195 self
.checkequalnofix(u
'one@two!three!', 'one!two!three!', 'replace', u
'!', u
'@', 1)
196 self
.assertRaises(TypeError, 'replace'.replace
, u
"r", 42)
198 def test_comparison(self
):
200 self
.assertEqual(u
'abc', 'abc')
201 self
.assertEqual('abc', u
'abc')
202 self
.assertEqual(u
'abc', u
'abc')
203 self
.assertTrue(u
'abcd' > 'abc')
204 self
.assertTrue('abcd' > u
'abc')
205 self
.assertTrue(u
'abcd' > u
'abc')
206 self
.assertTrue(u
'abc' < 'abcd')
207 self
.assertTrue('abc' < u
'abcd')
208 self
.assertTrue(u
'abc' < u
'abcd')
211 # Move these tests to a Unicode collation module test...
212 # Testing UTF-16 code point order comparisons...
214 # No surrogates, no fixup required.
215 self
.assertTrue(u
'\u0061' < u
'\u20ac')
216 # Non surrogate below surrogate value, no fixup required
217 self
.assertTrue(u
'\u0061' < u
'\ud800\udc02')
219 # Non surrogate above surrogate value, fixup required
220 def test_lecmp(s
, s2
):
221 self
.assertTrue(s
< s2
)
257 test_fixup(u
'\ue000')
258 test_fixup(u
'\uff61')
260 # Surrogates on both sides, no fixup required
261 self
.assertTrue(u
'\ud800\udc02' < u
'\ud84d\udc56')
263 def test_islower(self
):
264 string_tests
.MixinStrUnicodeUserStringTest
.test_islower(self
)
265 self
.checkequalnofix(False, u
'\u1FFc', 'islower')
267 def test_isupper(self
):
268 string_tests
.MixinStrUnicodeUserStringTest
.test_isupper(self
)
269 if not sys
.platform
.startswith('java'):
270 self
.checkequalnofix(False, u
'\u1FFc', 'isupper')
272 def test_istitle(self
):
273 string_tests
.MixinStrUnicodeUserStringTest
.test_title(self
)
274 self
.checkequalnofix(True, u
'\u1FFc', 'istitle')
275 self
.checkequalnofix(True, u
'Greek \u1FFcitlecases ...', 'istitle')
277 def test_isspace(self
):
278 string_tests
.MixinStrUnicodeUserStringTest
.test_isspace(self
)
279 self
.checkequalnofix(True, u
'\u2000', 'isspace')
280 self
.checkequalnofix(True, u
'\u200a', 'isspace')
281 self
.checkequalnofix(False, u
'\u2014', 'isspace')
283 def test_isalpha(self
):
284 string_tests
.MixinStrUnicodeUserStringTest
.test_isalpha(self
)
285 self
.checkequalnofix(True, u
'\u1FFc', 'isalpha')
287 def test_isdecimal(self
):
288 self
.checkequalnofix(False, u
'', 'isdecimal')
289 self
.checkequalnofix(False, u
'a', 'isdecimal')
290 self
.checkequalnofix(True, u
'0', 'isdecimal')
291 self
.checkequalnofix(False, u
'\u2460', 'isdecimal') # CIRCLED DIGIT ONE
292 self
.checkequalnofix(False, u
'\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
293 self
.checkequalnofix(True, u
'\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
294 self
.checkequalnofix(True, u
'0123456789', 'isdecimal')
295 self
.checkequalnofix(False, u
'0123456789a', 'isdecimal')
297 self
.checkraises(TypeError, 'abc', 'isdecimal', 42)
299 def test_isdigit(self
):
300 string_tests
.MixinStrUnicodeUserStringTest
.test_isdigit(self
)
301 self
.checkequalnofix(True, u
'\u2460', 'isdigit')
302 self
.checkequalnofix(False, u
'\xbc', 'isdigit')
303 self
.checkequalnofix(True, u
'\u0660', 'isdigit')
305 def test_isnumeric(self
):
306 self
.checkequalnofix(False, u
'', 'isnumeric')
307 self
.checkequalnofix(False, u
'a', 'isnumeric')
308 self
.checkequalnofix(True, u
'0', 'isnumeric')
309 self
.checkequalnofix(True, u
'\u2460', 'isnumeric')
310 self
.checkequalnofix(True, u
'\xbc', 'isnumeric')
311 self
.checkequalnofix(True, u
'\u0660', 'isnumeric')
312 self
.checkequalnofix(True, u
'0123456789', 'isnumeric')
313 self
.checkequalnofix(False, u
'0123456789a', 'isnumeric')
315 self
.assertRaises(TypeError, u
"abc".isnumeric
, 42)
317 def test_contains(self
):
318 # Testing Unicode contains method
319 self
.assertIn('a', u
'abdb')
320 self
.assertIn('a', u
'bdab')
321 self
.assertIn('a', u
'bdaba')
322 self
.assertIn('a', u
'bdba')
323 self
.assertIn('a', u
'bdba')
324 self
.assertIn(u
'a', u
'bdba')
325 self
.assertNotIn(u
'a', u
'bdb')
326 self
.assertNotIn(u
'a', 'bdb')
327 self
.assertIn(u
'a', 'bdba')
328 self
.assertIn(u
'a', ('a',1,None))
329 self
.assertIn(u
'a', (1,None,'a'))
330 self
.assertIn(u
'a', (1,None,u
'a'))
331 self
.assertIn('a', ('a',1,None))
332 self
.assertIn('a', (1,None,'a'))
333 self
.assertIn('a', (1,None,u
'a'))
334 self
.assertNotIn('a', ('x',1,u
'y'))
335 self
.assertNotIn('a', ('x',1,None))
336 self
.assertNotIn(u
'abcd', u
'abcxxxx')
337 self
.assertIn(u
'ab', u
'abcd')
338 self
.assertIn('ab', u
'abc')
339 self
.assertIn(u
'ab', 'abc')
340 self
.assertIn(u
'ab', (1,None,u
'ab'))
341 self
.assertIn(u
'', u
'abc')
342 self
.assertIn('', u
'abc')
344 # If the following fails either
345 # the contains operator does not propagate UnicodeErrors or
346 # someone has changed the default encoding
347 self
.assertRaises(UnicodeDecodeError, 'g\xe2teau'.__contains
__, u
'\xe2')
348 self
.assertRaises(UnicodeDecodeError, u
'g\xe2teau'.__contains
__, '\xe2')
350 self
.assertIn(u
'', '')
351 self
.assertIn('', u
'')
352 self
.assertIn(u
'', u
'')
353 self
.assertIn(u
'', 'abc')
354 self
.assertIn('', u
'abc')
355 self
.assertIn(u
'', u
'abc')
356 self
.assertNotIn(u
'\0', 'abc')
357 self
.assertNotIn('\0', u
'abc')
358 self
.assertNotIn(u
'\0', u
'abc')
359 self
.assertIn(u
'\0', '\0abc')
360 self
.assertIn('\0', u
'\0abc')
361 self
.assertIn(u
'\0', u
'\0abc')
362 self
.assertIn(u
'\0', 'abc\0')
363 self
.assertIn('\0', u
'abc\0')
364 self
.assertIn(u
'\0', u
'abc\0')
365 self
.assertIn(u
'a', '\0abc')
366 self
.assertIn('a', u
'\0abc')
367 self
.assertIn(u
'a', u
'\0abc')
368 self
.assertIn(u
'asdf', 'asdf')
369 self
.assertIn('asdf', u
'asdf')
370 self
.assertIn(u
'asdf', u
'asdf')
371 self
.assertNotIn(u
'asdf', 'asd')
372 self
.assertNotIn('asdf', u
'asd')
373 self
.assertNotIn(u
'asdf', u
'asd')
374 self
.assertNotIn(u
'asdf', '')
375 self
.assertNotIn('asdf', u
'')
376 self
.assertNotIn(u
'asdf', u
'')
378 self
.assertRaises(TypeError, u
"abc".__contains
__)
379 self
.assertRaises(TypeError, u
"abc".__contains
__, object())
381 def test_formatting(self
):
382 string_tests
.MixinStrUnicodeUserStringTest
.test_formatting(self
)
383 # Testing Unicode formatting strings...
384 self
.assertEqual(u
"%s, %s" % (u
"abc", "abc"), u
'abc, abc')
385 self
.assertEqual(u
"%s, %s, %i, %f, %5.2f" % (u
"abc", "abc", 1, 2, 3), u
'abc, abc, 1, 2.000000, 3.00')
386 self
.assertEqual(u
"%s, %s, %i, %f, %5.2f" % (u
"abc", "abc", 1, -2, 3), u
'abc, abc, 1, -2.000000, 3.00')
387 self
.assertEqual(u
"%s, %s, %i, %f, %5.2f" % (u
"abc", "abc", -1, -2, 3.5), u
'abc, abc, -1, -2.000000, 3.50')
388 self
.assertEqual(u
"%s, %s, %i, %f, %5.2f" % (u
"abc", "abc", -1, -2, 3.57), u
'abc, abc, -1, -2.000000, 3.57')
389 self
.assertEqual(u
"%s, %s, %i, %f, %5.2f" % (u
"abc", "abc", -1, -2, 1003.57), u
'abc, abc, -1, -2.000000, 1003.57')
390 if not sys
.platform
.startswith('java'):
391 self
.assertEqual(u
"%r, %r" % (u
"abc", "abc"), u
"u'abc', 'abc'")
392 self
.assertEqual(u
"%(x)s, %(y)s" % {'x':u
"abc", 'y':"def"}, u
'abc, def')
393 self
.assertEqual(u
"%(x)s, %(\xfc)s" % {'x':u
"abc", u
'\xfc':"def"}, u
'abc, def')
395 self
.assertEqual(u
'%c' % 0x1234, u
'\u1234')
396 self
.assertRaises(OverflowError, u
"%c".__mod
__, (sys
.maxunicode
+1,))
398 for num
in range(0x00,0x80):
400 self
.assertEqual(u
"%c" % char
, char
)
401 self
.assertEqual(u
"%c" % num
, char
)
403 for num
in range(0x80,0x100):
405 self
.assertEqual(uchar
, u
"%c" % num
) # works only with ints
406 self
.assertEqual(uchar
, u
"%c" % uchar
) # and unicode chars
407 # the implicit decoding should fail for non-ascii chars
408 self
.assertRaises(UnicodeDecodeError, u
"%c".__mod
__, chr(num
))
409 self
.assertRaises(UnicodeDecodeError, u
"%s".__mod
__, chr(num
))
411 # formatting jobs delegated from the string implementation:
412 self
.assertEqual('...%(foo)s...' % {'foo':u
"abc"}, u
'...abc...')
413 self
.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
414 self
.assertEqual('...%(foo)s...' % {u
'foo':"abc"}, '...abc...')
415 self
.assertEqual('...%(foo)s...' % {u
'foo':u
"abc"}, u
'...abc...')
416 self
.assertEqual('...%(foo)s...' % {u
'foo':u
"abc",'def':123}, u
'...abc...')
417 self
.assertEqual('...%(foo)s...' % {u
'foo':u
"abc",u
'def':123}, u
'...abc...')
418 self
.assertEqual('...%s...%s...%s...%s...' % (1,2,3,u
"abc"), u
'...1...2...3...abc...')
419 self
.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,u
"abc"), u
'...%...%s...1...2...3...abc...')
420 self
.assertEqual('...%s...' % u
"abc", u
'...abc...')
421 self
.assertEqual('%*s' % (5,u
'abc',), u
' abc')
422 self
.assertEqual('%*s' % (-5,u
'abc',), u
'abc ')
423 self
.assertEqual('%*.*s' % (5,2,u
'abc',), u
' ab')
424 self
.assertEqual('%*.*s' % (5,3,u
'abc',), u
' abc')
425 self
.assertEqual('%i %*.*s' % (10, 5,3,u
'abc',), u
'10 abc')
426 self
.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, u
'abc',), u
'103 abc')
427 self
.assertEqual('%c' % u
'a', u
'a')
431 self
.assertEqual('%s' % Wrapper(), u
'\u1234')
433 @test_support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
434 def test_format_float(self
):
435 # should not format with a comma, but always with C locale
436 self
.assertEqual(u
'1.0', u
'%.1f' % 1.0)
438 def test_constructor(self
):
439 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
442 unicode(u
'unicode remains unicode'),
443 u
'unicode remains unicode'
446 class UnicodeSubclass(unicode):
450 unicode(UnicodeSubclass('unicode subclass becomes unicode')),
451 u
'unicode subclass becomes unicode'
455 unicode('strings are converted to unicode'),
456 u
'strings are converted to unicode'
460 def __init__(self
, x
):
462 def __unicode__(self
):
466 unicode(UnicodeCompat('__unicode__ compatible objects are recognized')),
467 u
'__unicode__ compatible objects are recognized')
470 def __init__(self
, x
):
476 unicode(StringCompat('__str__ compatible objects are recognized')),
477 u
'__str__ compatible objects are recognized'
480 # unicode(obj) is compatible to str():
482 o
= StringCompat('unicode(obj) is compatible to str()')
483 self
.assertEqual(unicode(o
), u
'unicode(obj) is compatible to str()')
484 self
.assertEqual(str(o
), 'unicode(obj) is compatible to str()')
486 # %-formatting and .__unicode__()
487 self
.assertEqual(u
'%s' %
488 UnicodeCompat(u
"u'%s' % obj uses obj.__unicode__()"),
489 u
"u'%s' % obj uses obj.__unicode__()")
490 self
.assertEqual(u
'%s' %
491 UnicodeCompat(u
"u'%s' % obj falls back to obj.__str__()"),
492 u
"u'%s' % obj falls back to obj.__str__()")
494 for obj
in (123, 123.45, 123L):
495 self
.assertEqual(unicode(obj
), unicode(str(obj
)))
497 # unicode(obj, encoding, error) tests (this maps to
498 # PyUnicode_FromEncodedObject() at C level)
500 if not sys
.platform
.startswith('java'):
504 u
'decoding unicode is not supported',
510 unicode('strings are decoded to unicode', 'utf-8', 'strict'),
511 u
'strings are decoded to unicode'
514 if not sys
.platform
.startswith('java'):
515 with test_support
.check_py3k_warnings():
516 buf
= buffer('character buffers are decoded to unicode')
523 u
'character buffers are decoded to unicode'
526 self
.assertRaises(TypeError, unicode, 42, 42, 42)
528 def test_codecs_utf7(self
):
530 (u
'A\u2262\u0391.', 'A+ImIDkQ.'), # RFC2152 example
531 (u
'Hi Mom -\u263a-!', 'Hi Mom -+Jjo--!'), # RFC2152 example
532 (u
'\u65E5\u672C\u8A9E', '+ZeVnLIqe-'), # RFC2152 example
533 (u
'Item 3 is \u00a31.', 'Item 3 is +AKM-1.'), # RFC2152 example
539 (ur
'\\?', '+AFwAXA?'),
540 (ur
'\\\?', '+AFwAXABc?'),
541 (ur
'++--', '+-+---'),
542 (u
'\U000abcde', '+2m/c3g-'), # surrogate pairs
546 for (x
, y
) in utfTests
:
547 self
.assertEqual(x
.encode('utf-7'), y
)
549 # Unpaired surrogates not supported
550 self
.assertRaises(UnicodeError, unicode, '+3ADYAA-', 'utf-7')
552 self
.assertEqual(unicode('+3ADYAA-', 'utf-7', 'replace'), u
'\ufffd\ufffd')
554 # Direct encoded characters
555 set_d
= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
556 # Optional direct characters
557 set_o
= '!"#$%&*;<=>@[]^_`{|}'
559 self
.assertEqual(c
.encode('utf7'), c
.encode('ascii'))
560 self
.assertEqual(c
.encode('ascii').decode('utf7'), c
)
562 self
.assertEqual(c
.encode('ascii').decode('utf7'), c
)
564 def test_codecs_utf8(self
):
565 self
.assertEqual(u
''.encode('utf-8'), '')
566 self
.assertEqual(u
'\u20ac'.encode('utf-8'), '\xe2\x82\xac')
567 self
.assertEqual(u
'\ud800\udc02'.encode('utf-8'), '\xf0\x90\x80\x82')
568 self
.assertEqual(u
'\ud84d\udc56'.encode('utf-8'), '\xf0\xa3\x91\x96')
569 self
.assertEqual(u
'\ud800'.encode('utf-8'), '\xed\xa0\x80')
570 self
.assertEqual(u
'\udc00'.encode('utf-8'), '\xed\xb0\x80')
572 (u
'\ud800\udc02'*1000).encode('utf-8'),
573 '\xf0\x90\x80\x82'*1000
576 u
'\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
577 u
'\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
578 u
'\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
579 u
'\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
580 u
'\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
581 u
' Nunstuck git und'.encode('utf-8'),
582 '\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
583 '\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
584 '\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
585 '\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
586 '\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
587 '\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
588 '\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
589 '\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
590 '\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
591 '\xe3\x80\x8cWenn ist das Nunstuck git und'
594 # UTF-8 specific decoding tests
595 self
.assertEqual(unicode('\xf0\xa3\x91\x96', 'utf-8'), u
'\U00023456' )
596 self
.assertEqual(unicode('\xf0\x90\x80\x82', 'utf-8'), u
'\U00010002' )
597 self
.assertEqual(unicode('\xe2\x82\xac', 'utf-8'), u
'\u20ac' )
599 # Other possible utf-8 test cases:
600 # * strict decoding testing for all of the
601 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
603 def test_utf8_decode_valid_sequences(self
):
606 ('\x00', u
'\x00'), ('a', u
'a'), ('\x7f', u
'\x7f'),
608 ('\xc2\x80', u
'\x80'), ('\xdf\xbf', u
'\u07ff'),
610 ('\xe0\xa0\x80', u
'\u0800'), ('\xed\x9f\xbf', u
'\ud7ff'),
611 ('\xee\x80\x80', u
'\uE000'), ('\xef\xbf\xbf', u
'\uffff'),
613 ('\xF0\x90\x80\x80', u
'\U00010000'),
614 ('\xf4\x8f\xbf\xbf', u
'\U0010FFFF')
616 for seq
, res
in sequences
:
617 self
.assertEqual(seq
.decode('utf-8'), res
)
619 for ch
in map(unichr, range(0, sys
.maxunicode
)):
620 self
.assertEqual(ch
, ch
.encode('utf-8').decode('utf-8'))
622 def test_utf8_decode_invalid_sequences(self
):
623 # continuation bytes in a sequence of 2, 3, or 4 bytes
624 continuation_bytes
= map(chr, range(0x80, 0xC0))
625 # start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
626 invalid_2B_seq_start_bytes
= map(chr, range(0xC0, 0xC2))
627 # start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
628 invalid_4B_seq_start_bytes
= map(chr, range(0xF5, 0xF8))
629 invalid_start_bytes
= (
630 continuation_bytes
+ invalid_2B_seq_start_bytes
+
631 invalid_4B_seq_start_bytes
+ map(chr, range(0xF7, 0x100))
634 for byte
in invalid_start_bytes
:
635 self
.assertRaises(UnicodeDecodeError, byte
.decode
, 'utf-8')
637 for sb
in invalid_2B_seq_start_bytes
:
638 for cb
in continuation_bytes
:
639 self
.assertRaises(UnicodeDecodeError, (sb
+cb
).decode
, 'utf-8')
641 for sb
in invalid_4B_seq_start_bytes
:
642 for cb1
in continuation_bytes
[:3]:
643 for cb3
in continuation_bytes
[:3]:
644 self
.assertRaises(UnicodeDecodeError,
645 (sb
+cb1
+'\x80'+cb3
).decode
, 'utf-8')
647 for cb
in map(chr, range(0x80, 0xA0)):
648 self
.assertRaises(UnicodeDecodeError,
649 ('\xE0'+cb
+'\x80').decode
, 'utf-8')
650 self
.assertRaises(UnicodeDecodeError,
651 ('\xE0'+cb
+'\xBF').decode
, 'utf-8')
652 # XXX: surrogates shouldn't be valid UTF-8!
653 # see http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf
654 # (table 3-7) and http://www.rfc-editor.org/rfc/rfc3629.txt
655 #for cb in map(chr, range(0xA0, 0xC0)):
656 #sys.__stdout__.write('\\xED\\x%02x\\x80\n' % ord(cb))
657 #self.assertRaises(UnicodeDecodeError,
658 #('\xED'+cb+'\x80').decode, 'utf-8')
659 #self.assertRaises(UnicodeDecodeError,
660 #('\xED'+cb+'\xBF').decode, 'utf-8')
661 for cb
in map(chr, range(0x80, 0x90)):
662 self
.assertRaises(UnicodeDecodeError,
663 ('\xF0'+cb
+'\x80\x80').decode
, 'utf-8')
664 self
.assertRaises(UnicodeDecodeError,
665 ('\xF0'+cb
+'\xBF\xBF').decode
, 'utf-8')
666 for cb
in map(chr, range(0x90, 0xC0)):
667 self
.assertRaises(UnicodeDecodeError,
668 ('\xF4'+cb
+'\x80\x80').decode
, 'utf-8')
669 self
.assertRaises(UnicodeDecodeError,
670 ('\xF4'+cb
+'\xBF\xBF').decode
, 'utf-8')
672 def test_issue8271(self
):
673 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
674 # only the start byte and the continuation byte(s) are now considered
675 # invalid, instead of the number of bytes specified by the start byte.
676 # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
677 # table 3-8, Row 2) for more information about the algorithm used.
680 # invalid start bytes
681 ('\x80', FFFD
), # continuation byte
682 ('\x80\x80', FFFD
*2), # 2 continuation bytes
684 ('\xc0\xc0', FFFD
*2),
686 ('\xc1\xc0', FFFD
*2),
687 ('\xc0\xc1', FFFD
*2),
688 # with start byte of a 2-byte sequence
689 ('\xc2', FFFD
), # only the start byte
690 ('\xc2\xc2', FFFD
*2), # 2 start bytes
691 ('\xc2\xc2\xc2', FFFD
*3), # 2 start bytes
692 ('\xc2\x41', FFFD
+'A'), # invalid continuation byte
693 # with start byte of a 3-byte sequence
694 ('\xe1', FFFD
), # only the start byte
695 ('\xe1\xe1', FFFD
*2), # 2 start bytes
696 ('\xe1\xe1\xe1', FFFD
*3), # 3 start bytes
697 ('\xe1\xe1\xe1\xe1', FFFD
*4), # 4 start bytes
698 ('\xe1\x80', FFFD
), # only 1 continuation byte
699 ('\xe1\x41', FFFD
+'A'), # invalid continuation byte
700 ('\xe1\x41\x80', FFFD
+'A'+FFFD
), # invalid cb followed by valid cb
701 ('\xe1\x41\x41', FFFD
+'AA'), # 2 invalid continuation bytes
702 ('\xe1\x80\x41', FFFD
+'A'), # only 1 valid continuation byte
703 ('\xe1\x80\xe1\x41', FFFD
*2+'A'), # 1 valid and the other invalid
704 ('\xe1\x41\xe1\x80', FFFD
+'A'+FFFD
), # 1 invalid and the other valid
705 # with start byte of a 4-byte sequence
706 ('\xf1', FFFD
), # only the start byte
707 ('\xf1\xf1', FFFD
*2), # 2 start bytes
708 ('\xf1\xf1\xf1', FFFD
*3), # 3 start bytes
709 ('\xf1\xf1\xf1\xf1', FFFD
*4), # 4 start bytes
710 ('\xf1\xf1\xf1\xf1\xf1', FFFD
*5), # 5 start bytes
711 ('\xf1\x80', FFFD
), # only 1 continuation bytes
712 ('\xf1\x80\x80', FFFD
), # only 2 continuation bytes
713 ('\xf1\x80\x41', FFFD
+'A'), # 1 valid cb and 1 invalid
714 ('\xf1\x80\x41\x41', FFFD
+'AA'), # 1 valid cb and 1 invalid
715 ('\xf1\x80\x80\x41', FFFD
+'A'), # 2 valid cb and 1 invalid
716 ('\xf1\x41\x80', FFFD
+'A'+FFFD
), # 1 invalid cv and 1 valid
717 ('\xf1\x41\x80\x80', FFFD
+'A'+FFFD
*2), # 1 invalid cb and 2 invalid
718 ('\xf1\x41\x80\x41', FFFD
+'A'+FFFD
+'A'), # 2 invalid cb and 1 invalid
719 ('\xf1\x41\x41\x80', FFFD
+'AA'+FFFD
), # 1 valid cb and 1 invalid
720 ('\xf1\x41\xf1\x80', FFFD
+'A'+FFFD
),
721 ('\xf1\x41\x80\xf1', FFFD
+'A'+FFFD
*2),
722 ('\xf1\xf1\x80\x41', FFFD
*2+'A'),
723 ('\xf1\x41\xf1\xf1', FFFD
+'A'+FFFD
*2),
724 # with invalid start byte of a 4-byte sequence (rfc2279)
725 ('\xf5', FFFD
), # only the start byte
726 ('\xf5\xf5', FFFD
*2), # 2 start bytes
727 ('\xf5\x80', FFFD
*2), # only 1 continuation byte
728 ('\xf5\x80\x80', FFFD
*3), # only 2 continuation byte
729 ('\xf5\x80\x80\x80', FFFD
*4), # 3 continuation bytes
730 ('\xf5\x80\x41', FFFD
*2+'A'), # 1 valid cb and 1 invalid
731 ('\xf5\x80\x41\xf5', FFFD
*2+'A'+FFFD
),
732 ('\xf5\x41\x80\x80\x41', FFFD
+'A'+FFFD
*2+'A'),
733 # with invalid start byte of a 5-byte sequence (rfc2279)
734 ('\xf8', FFFD
), # only the start byte
735 ('\xf8\xf8', FFFD
*2), # 2 start bytes
736 ('\xf8\x80', FFFD
*2), # only one continuation byte
737 ('\xf8\x80\x41', FFFD
*2 + 'A'), # 1 valid cb and 1 invalid
738 ('\xf8\x80\x80\x80\x80', FFFD
*5), # invalid 5 bytes seq with 5 bytes
739 # with invalid start byte of a 6-byte sequence (rfc2279)
740 ('\xfc', FFFD
), # only the start byte
741 ('\xfc\xfc', FFFD
*2), # 2 start bytes
742 ('\xfc\x80\x80', FFFD
*3), # only 2 continuation bytes
743 ('\xfc\x80\x80\x80\x80\x80', FFFD
*6), # 6 continuation bytes
746 ('\xfe\x80\x80', FFFD
*3),
748 ('\xf1\x80\x41\x42\x43', u
'\ufffd\x41\x42\x43'),
749 ('\xf1\x80\xff\x42\x43', u
'\ufffd\ufffd\x42\x43'),
750 ('\xf1\x80\xc2\x81\x43', u
'\ufffd\x81\x43'),
751 ('\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
752 u
'\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
754 for n
, (seq
, res
) in enumerate(sequences
):
755 self
.assertRaises(UnicodeDecodeError, seq
.decode
, 'utf-8', 'strict')
756 self
.assertEqual(seq
.decode('utf-8', 'replace'), res
)
757 self
.assertEqual((seq
+'b').decode('utf-8', 'replace'), res
+'b')
758 self
.assertEqual(seq
.decode('utf-8', 'ignore'),
759 res
.replace(u
'\uFFFD', ''))
761 def test_codecs_idna(self
):
762 # Test whether trailing dot is preserved
763 self
.assertEqual(u
"www.python.org.".encode("idna"), "www.python.org.")
765 def test_codecs_errors(self
):
766 # Error handling (encoding)
767 self
.assertRaises(UnicodeError, u
'Andr\202 x'.encode
, 'ascii')
768 self
.assertRaises(UnicodeError, u
'Andr\202 x'.encode
, 'ascii','strict')
769 self
.assertEqual(u
'Andr\202 x'.encode('ascii','ignore'), "Andr x")
770 self
.assertEqual(u
'Andr\202 x'.encode('ascii','replace'), "Andr? x")
771 self
.assertEqual(u
'Andr\202 x'.encode('ascii', 'replace'),
772 u
'Andr\202 x'.encode('ascii', errors
='replace'))
773 self
.assertEqual(u
'Andr\202 x'.encode('ascii', 'ignore'),
774 u
'Andr\202 x'.encode(encoding
='ascii', errors
='ignore'))
776 # Error handling (decoding)
777 self
.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii')
778 self
.assertRaises(UnicodeError, unicode, 'Andr\202 x', 'ascii','strict')
779 self
.assertEqual(unicode('Andr\202 x','ascii','ignore'), u
"Andr x")
780 self
.assertEqual(unicode('Andr\202 x','ascii','replace'), u
'Andr\uFFFD x')
781 self
.assertEqual(u
'abcde'.decode('ascii', 'ignore'),
782 u
'abcde'.decode('ascii', errors
='ignore'))
783 self
.assertEqual(u
'abcde'.decode('ascii', 'replace'),
784 u
'abcde'.decode(encoding
='ascii', errors
='replace'))
786 # Error handling (unknown character names)
787 self
.assertEqual("\\N{foo}xx".decode("unicode-escape", "ignore"), u
"xx")
789 # Error handling (truncated escape sequence)
790 self
.assertRaises(UnicodeError, "\\".decode
, "unicode-escape")
792 self
.assertRaises(TypeError, "hello".decode
, "test.unicode1")
793 self
.assertRaises(TypeError, unicode, "hello", "test.unicode2")
794 self
.assertRaises(TypeError, u
"hello".encode
, "test.unicode1")
795 self
.assertRaises(TypeError, u
"hello".encode
, "test.unicode2")
796 # executes PyUnicode_Encode()
801 "non-existing module",
802 [u
"non-existing dir"]
805 # Error handling (wrong arguments)
806 self
.assertRaises(TypeError, u
"hello".encode
, 42, 42, 42)
808 # Error handling (PyUnicode_EncodeDecimal())
809 self
.assertRaises(UnicodeError, int, u
"\u0200")
811 def test_codecs(self
):
813 self
.assertEqual(u
'hello'.encode('ascii'), 'hello')
814 self
.assertEqual(u
'hello'.encode('utf-7'), 'hello')
815 self
.assertEqual(u
'hello'.encode('utf-8'), 'hello')
816 self
.assertEqual(u
'hello'.encode('utf8'), 'hello')
817 self
.assertEqual(u
'hello'.encode('utf-16-le'), 'h\000e\000l\000l\000o\000')
818 self
.assertEqual(u
'hello'.encode('utf-16-be'), '\000h\000e\000l\000l\000o')
819 self
.assertEqual(u
'hello'.encode('latin-1'), 'hello')
821 # Roundtrip safety for BMP (just the first 1024 chars)
822 for c
in xrange(1024):
824 for encoding
in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
825 'utf-16-be', 'raw_unicode_escape',
826 'unicode_escape', 'unicode_internal'):
827 self
.assertEqual(unicode(u
.encode(encoding
),encoding
), u
)
829 # Roundtrip safety for BMP (just the first 256 chars)
830 for c
in xrange(256):
832 for encoding
in ('latin-1',):
833 self
.assertEqual(unicode(u
.encode(encoding
),encoding
), u
)
835 # Roundtrip safety for BMP (just the first 128 chars)
836 for c
in xrange(128):
838 for encoding
in ('ascii',):
839 self
.assertEqual(unicode(u
.encode(encoding
),encoding
), u
)
841 # Roundtrip safety for non-BMP (just a few chars)
842 u
= u
'\U00010001\U00020002\U00030003\U00040004\U00050005'
843 for encoding
in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
844 #'raw_unicode_escape',
845 'unicode_escape', 'unicode_internal'):
846 self
.assertEqual(unicode(u
.encode(encoding
),encoding
), u
)
848 # UTF-8 must be roundtrip safe for all UCS-2 code points
849 # This excludes surrogates: in the full range, there would be
850 # a surrogate pair (\udbff\udc00), which gets converted back
851 # to a non-BMP character (\U0010fc00)
852 u
= u
''.join(map(unichr, range(0,0xd800)+range(0xe000,0x10000)))
853 for encoding
in ('utf-8',):
854 self
.assertEqual(unicode(u
.encode(encoding
),encoding
), u
)
856 def test_codecs_charmap(self
):
858 s
= ''.join(map(chr, xrange(128)))
861 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
862 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
863 'cp863', 'cp865', 'cp866',
864 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
865 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
866 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
867 'mac_cyrillic', 'mac_latin2',
869 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
870 'cp1256', 'cp1257', 'cp1258',
871 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
873 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
874 'cp1006', 'iso8859_8',
876 ### These have undefined mappings:
879 ### These fail the round-trip:
883 self
.assertEqual(unicode(s
, encoding
).encode(encoding
), s
)
886 s
= ''.join(map(chr, xrange(128, 256)))
889 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
890 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
891 'cp863', 'cp865', 'cp866',
892 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
893 'iso8859_2', 'iso8859_4', 'iso8859_5',
894 'iso8859_9', 'koi8_r', 'latin_1',
895 'mac_cyrillic', 'mac_latin2',
897 ### These have undefined mappings:
898 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
899 #'cp1256', 'cp1257', 'cp1258',
900 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
901 #'iso8859_3', 'iso8859_6', 'iso8859_7',
902 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
904 ### These fail the round-trip:
905 #'cp1006', 'cp875', 'iso8859_8',
908 self
.assertEqual(unicode(s
, encoding
).encode(encoding
), s
)
910 def test_concatenation(self
):
911 self
.assertEqual((u
"abc" u
"def"), u
"abcdef")
912 self
.assertEqual(("abc" u
"def"), u
"abcdef")
913 self
.assertEqual((u
"abc" "def"), u
"abcdef")
914 self
.assertEqual((u
"abc" u
"def" "ghi"), u
"abcdefghi")
915 self
.assertEqual(("abc" "def" u
"ghi"), u
"abcdefghi")
917 def test_printing(self
):
919 def write(self
, text
):
924 print >>out
, u
'abc', u
'def'
925 print >>out
, u
'abc', 'def'
926 print >>out
, 'abc', u
'def'
927 print >>out
, u
'abc\n'
928 print >>out
, u
'abc\n',
929 print >>out
, u
'abc\n',
930 print >>out
, u
'def\n'
931 print >>out
, u
'def\n'
935 y
= x
.encode("raw-unicode-escape").decode("raw-unicode-escape")
936 self
.assertEqual(x
, y
)
939 x
= y
.decode("raw-unicode-escape").encode("raw-unicode-escape")
940 self
.assertEqual(x
, y
)
942 x
= y
.decode("raw-unicode-escape").encode("raw-unicode-escape")
943 self
.assertEqual(x
, y
)
946 '\U11111111'.decode("raw-unicode-escape")
947 except UnicodeDecodeError as e
:
948 self
.assertEqual(e
.start
, 0)
949 self
.assertEqual(e
.end
, 10)
951 self
.fail("Should have raised UnicodeDecodeError")
953 def test_conversion(self
):
954 # Make sure __unicode__() works properly
960 def __unicode__(self
):
964 def __unicode__(self
):
968 def __unicode__(self
):
972 def __unicode__(self
):
976 def __unicode__(self
):
983 def __unicode__(self
):
989 def __unicode__(self
):
993 def __new__(cls
, content
=""):
994 return unicode.__new
__(cls
, 2*content
)
995 def __unicode__(self
):
1001 def __unicode__(self
):
1002 return "not unicode"
1004 self
.assertEqual(unicode(Foo0()), u
"foo")
1005 self
.assertEqual(unicode(Foo1()), u
"foo")
1006 self
.assertEqual(unicode(Foo2()), u
"foo")
1007 self
.assertEqual(unicode(Foo3()), u
"foo")
1008 self
.assertEqual(unicode(Foo4("bar")), u
"foo")
1009 self
.assertEqual(unicode(Foo5("bar")), u
"foo")
1010 self
.assertEqual(unicode(Foo6("bar")), u
"foou")
1011 self
.assertEqual(unicode(Foo7("bar")), u
"foou")
1012 self
.assertEqual(unicode(Foo8("foo")), u
"foofoo")
1013 self
.assertEqual(str(Foo9("foo")), "string")
1014 self
.assertEqual(unicode(Foo9("foo")), u
"not unicode")
1016 def test_unicode_repr(self
):
1025 self
.assertEqual(repr(s1()), '\\n')
1026 self
.assertEqual(repr(s2()), '\\n')
1028 def test_expandtabs_overflows_gracefully(self
):
1029 # This test only affects 32-bit platforms because expandtabs can only take
1030 # an int as the max value, not a 64-bit C long. If expandtabs is changed
1031 # to take a 64-bit long, this test should apply to all platforms.
1032 if sys
.maxint
> (1 << 32) or struct
.calcsize('P') != 4:
1034 self
.assertRaises(OverflowError, u
't\tt\t'.expandtabs
, sys
.maxint
)
1036 def test__format__(self
):
1037 def test(value
, format
, expected
):
1038 # test both with and without the trailing 's'
1039 self
.assertEqual(value
.__format
__(format
), expected
)
1040 self
.assertEqual(value
.__format
__(format
+ u
's'), expected
)
1043 test(u
'abc', u
'', u
'abc')
1044 test(u
'abc', u
'.3', u
'abc')
1045 test(u
'ab', u
'.3', u
'ab')
1046 test(u
'abcdef', u
'.3', u
'abc')
1047 test(u
'abcdef', u
'.0', u
'')
1048 test(u
'abc', u
'3.3', u
'abc')
1049 test(u
'abc', u
'2.3', u
'abc')
1050 test(u
'abc', u
'2.2', u
'ab')
1051 test(u
'abc', u
'3.2', u
'ab ')
1052 test(u
'result', u
'x<0', u
'result')
1053 test(u
'result', u
'x<5', u
'result')
1054 test(u
'result', u
'x<6', u
'result')
1055 test(u
'result', u
'x<7', u
'resultx')
1056 test(u
'result', u
'x<8', u
'resultxx')
1057 test(u
'result', u
' <7', u
'result ')
1058 test(u
'result', u
'<7', u
'result ')
1059 test(u
'result', u
'>7', u
' result')
1060 test(u
'result', u
'>8', u
' result')
1061 test(u
'result', u
'^8', u
' result ')
1062 test(u
'result', u
'^9', u
' result ')
1063 test(u
'result', u
'^10', u
' result ')
1064 test(u
'a', u
'10000', u
'a' + u
' ' * 9999)
1065 test(u
'', u
'10000', u
' ' * 10000)
1066 test(u
'', u
'10000000', u
' ' * 10000000)
1068 # test mixing unicode and str
1069 self
.assertEqual(u
'abc'.__format
__('s'), u
'abc')
1070 self
.assertEqual(u
'abc'.__format
__('->10s'), u
'-------abc')
1072 def test_format(self
):
1073 self
.assertEqual(u
''.format(), u
'')
1074 self
.assertEqual(u
'a'.format(), u
'a')
1075 self
.assertEqual(u
'ab'.format(), u
'ab')
1076 self
.assertEqual(u
'a{{'.format(), u
'a{')
1077 self
.assertEqual(u
'a}}'.format(), u
'a}')
1078 self
.assertEqual(u
'{{b'.format(), u
'{b')
1079 self
.assertEqual(u
'}}b'.format(), u
'}b')
1080 self
.assertEqual(u
'a{{b'.format(), u
'a{b')
1082 # examples from the PEP:
1084 self
.assertEqual(u
"My name is {0}".format(u
'Fred'), u
"My name is Fred")
1085 self
.assertEqual(u
"My name is {0[name]}".format(dict(name
=u
'Fred')),
1087 self
.assertEqual(u
"My name is {0} :-{{}}".format(u
'Fred'),
1088 u
"My name is Fred :-{}")
1090 # datetime.__format__ doesn't work with unicode
1091 #d = datetime.date(2007, 8, 18)
1092 #self.assertEqual("The year is {0.year}".format(d),
1093 # "The year is 2007")
1095 # classes we'll use for testing
1097 def __init__(self
, x
=100):
1099 def __format__(self
, spec
):
1103 def __init__(self
, x
):
1105 def __format__(self
, spec
):
1108 # class with __str__, but no __format__
1110 def __init__(self
, x
):
1113 return u
'E(' + self
.x
+ u
')'
1115 # class with __repr__, but no __format__ or __str__
1117 def __init__(self
, x
):
1120 return u
'F(' + self
.x
+ u
')'
1122 # class with __format__ that forwards to string, for some format_spec's
1124 def __init__(self
, x
):
1127 return u
"string is " + self
.x
1128 def __format__(self
, format_spec
):
1129 if format_spec
== 'd':
1130 return u
'G(' + self
.x
+ u
')'
1131 return object.__format
__(self
, format_spec
)
1133 # class that returns a bad type from __format__
1135 def __format__(self
, format_spec
):
1138 class I(datetime
.date
):
1139 def __format__(self
, format_spec
):
1140 return self
.strftime(format_spec
)
1143 def __format__(self
, format_spec
):
1144 return int.__format
__(self
* 2, format_spec
)
1147 self
.assertEqual(u
''.format(), u
'')
1148 self
.assertEqual(u
'abc'.format(), u
'abc')
1149 self
.assertEqual(u
'{0}'.format(u
'abc'), u
'abc')
1150 self
.assertEqual(u
'{0:}'.format(u
'abc'), u
'abc')
1151 self
.assertEqual(u
'X{0}'.format(u
'abc'), u
'Xabc')
1152 self
.assertEqual(u
'{0}X'.format(u
'abc'), u
'abcX')
1153 self
.assertEqual(u
'X{0}Y'.format(u
'abc'), u
'XabcY')
1154 self
.assertEqual(u
'{1}'.format(1, u
'abc'), u
'abc')
1155 self
.assertEqual(u
'X{1}'.format(1, u
'abc'), u
'Xabc')
1156 self
.assertEqual(u
'{1}X'.format(1, u
'abc'), u
'abcX')
1157 self
.assertEqual(u
'X{1}Y'.format(1, u
'abc'), u
'XabcY')
1158 self
.assertEqual(u
'{0}'.format(-15), u
'-15')
1159 self
.assertEqual(u
'{0}{1}'.format(-15, u
'abc'), u
'-15abc')
1160 self
.assertEqual(u
'{0}X{1}'.format(-15, u
'abc'), u
'-15Xabc')
1161 self
.assertEqual(u
'{{'.format(), u
'{')
1162 self
.assertEqual(u
'}}'.format(), u
'}')
1163 self
.assertEqual(u
'{{}}'.format(), u
'{}')
1164 self
.assertEqual(u
'{{x}}'.format(), u
'{x}')
1165 self
.assertEqual(u
'{{{0}}}'.format(123), u
'{123}')
1166 self
.assertEqual(u
'{{{{0}}}}'.format(), u
'{{0}}')
1167 self
.assertEqual(u
'}}{{'.format(), u
'}{')
1168 self
.assertEqual(u
'}}x{{'.format(), u
'}x{')
1171 self
.assertEqual(u
"{0[foo-bar]}".format({u
'foo-bar':u
'baz'}), u
'baz')
1172 self
.assertEqual(u
"{0[foo bar]}".format({u
'foo bar':u
'baz'}), u
'baz')
1173 self
.assertEqual(u
"{0[ ]}".format({u
' ':3}), u
'3')
1175 self
.assertEqual(u
'{foo._x}'.format(foo
=C(20)), u
'20')
1176 self
.assertEqual(u
'{1}{0}'.format(D(10), D(20)), u
'2010')
1177 self
.assertEqual(u
'{0._x.x}'.format(C(D(u
'abc'))), u
'abc')
1178 self
.assertEqual(u
'{0[0]}'.format([u
'abc', u
'def']), u
'abc')
1179 self
.assertEqual(u
'{0[1]}'.format([u
'abc', u
'def']), u
'def')
1180 self
.assertEqual(u
'{0[1][0]}'.format([u
'abc', [u
'def']]), u
'def')
1181 self
.assertEqual(u
'{0[1][0].x}'.format(['abc', [D(u
'def')]]), u
'def')
1184 self
.assertEqual(u
'{0:.3s}'.format(u
'abc'), u
'abc')
1185 self
.assertEqual(u
'{0:.3s}'.format(u
'ab'), u
'ab')
1186 self
.assertEqual(u
'{0:.3s}'.format(u
'abcdef'), u
'abc')
1187 self
.assertEqual(u
'{0:.0s}'.format(u
'abcdef'), u
'')
1188 self
.assertEqual(u
'{0:3.3s}'.format(u
'abc'), u
'abc')
1189 self
.assertEqual(u
'{0:2.3s}'.format(u
'abc'), u
'abc')
1190 self
.assertEqual(u
'{0:2.2s}'.format(u
'abc'), u
'ab')
1191 self
.assertEqual(u
'{0:3.2s}'.format(u
'abc'), u
'ab ')
1192 self
.assertEqual(u
'{0:x<0s}'.format(u
'result'), u
'result')
1193 self
.assertEqual(u
'{0:x<5s}'.format(u
'result'), u
'result')
1194 self
.assertEqual(u
'{0:x<6s}'.format(u
'result'), u
'result')
1195 self
.assertEqual(u
'{0:x<7s}'.format(u
'result'), u
'resultx')
1196 self
.assertEqual(u
'{0:x<8s}'.format(u
'result'), u
'resultxx')
1197 self
.assertEqual(u
'{0: <7s}'.format(u
'result'), u
'result ')
1198 self
.assertEqual(u
'{0:<7s}'.format(u
'result'), u
'result ')
1199 self
.assertEqual(u
'{0:>7s}'.format(u
'result'), u
' result')
1200 self
.assertEqual(u
'{0:>8s}'.format(u
'result'), u
' result')
1201 self
.assertEqual(u
'{0:^8s}'.format(u
'result'), u
' result ')
1202 self
.assertEqual(u
'{0:^9s}'.format(u
'result'), u
' result ')
1203 self
.assertEqual(u
'{0:^10s}'.format(u
'result'), u
' result ')
1204 self
.assertEqual(u
'{0:10000}'.format(u
'a'), u
'a' + u
' ' * 9999)
1205 self
.assertEqual(u
'{0:10000}'.format(u
''), u
' ' * 10000)
1206 self
.assertEqual(u
'{0:10000000}'.format(u
''), u
' ' * 10000000)
1208 # format specifiers for user defined type
1209 self
.assertEqual(u
'{0:abc}'.format(C()), u
'abc')
1211 # !r and !s coersions
1212 self
.assertEqual(u
'{0!s}'.format(u
'Hello'), u
'Hello')
1213 self
.assertEqual(u
'{0!s:}'.format(u
'Hello'), u
'Hello')
1214 self
.assertEqual(u
'{0!s:15}'.format(u
'Hello'), u
'Hello ')
1215 self
.assertEqual(u
'{0!s:15s}'.format(u
'Hello'), u
'Hello ')
1216 self
.assertEqual(u
'{0!r}'.format(u
'Hello'), u
"u'Hello'")
1217 self
.assertEqual(u
'{0!r:}'.format(u
'Hello'), u
"u'Hello'")
1218 self
.assertEqual(u
'{0!r}'.format(F(u
'Hello')), u
'F(Hello)')
1220 # test fallback to object.__format__
1221 self
.assertEqual(u
'{0}'.format({}), u
'{}')
1222 self
.assertEqual(u
'{0}'.format([]), u
'[]')
1223 self
.assertEqual(u
'{0}'.format([1]), u
'[1]')
1224 self
.assertEqual(u
'{0}'.format(E(u
'data')), u
'E(data)')
1225 self
.assertEqual(u
'{0:^10}'.format(E(u
'data')), u
' E(data) ')
1226 self
.assertEqual(u
'{0:^10s}'.format(E(u
'data')), u
' E(data) ')
1227 self
.assertEqual(u
'{0:d}'.format(G(u
'data')), u
'G(data)')
1228 self
.assertEqual(u
'{0:>15s}'.format(G(u
'data')), u
' string is data')
1229 self
.assertEqual(u
'{0!s}'.format(G(u
'data')), u
'string is data')
1231 self
.assertEqual(u
"{0:date: %Y-%m-%d}".format(I(year
=2007,
1234 u
"date: 2007-08-27")
1236 # test deriving from a builtin type and overriding __format__
1237 self
.assertEqual(u
"{0}".format(J(10)), u
"20")
1240 # string format specifiers
1241 self
.assertEqual(u
'{0:}'.format('a'), u
'a')
1243 # computed format specifiers
1244 self
.assertEqual(u
"{0:.{1}}".format(u
'hello world', 5), u
'hello')
1245 self
.assertEqual(u
"{0:.{1}s}".format(u
'hello world', 5), u
'hello')
1246 self
.assertEqual(u
"{0:.{precision}s}".format('hello world', precision
=5), u
'hello')
1247 self
.assertEqual(u
"{0:{width}.{precision}s}".format('hello world', width
=10, precision
=5), u
'hello ')
1248 self
.assertEqual(u
"{0:{width}.{precision}s}".format('hello world', width
='10', precision
='5'), u
'hello ')
1250 # test various errors
1251 self
.assertRaises(ValueError, u
'{'.format
)
1252 self
.assertRaises(ValueError, u
'}'.format
)
1253 self
.assertRaises(ValueError, u
'a{'.format
)
1254 self
.assertRaises(ValueError, u
'a}'.format
)
1255 self
.assertRaises(ValueError, u
'{a'.format
)
1256 self
.assertRaises(ValueError, u
'}a'.format
)
1257 self
.assertRaises(IndexError, u
'{0}'.format
)
1258 self
.assertRaises(IndexError, u
'{1}'.format
, u
'abc')
1259 self
.assertRaises(KeyError, u
'{x}'.format
)
1260 self
.assertRaises(ValueError, u
"}{".format
)
1261 self
.assertRaises(ValueError, u
"{".format
)
1262 self
.assertRaises(ValueError, u
"}".format
)
1263 self
.assertRaises(ValueError, u
"abc{0:{}".format
)
1264 self
.assertRaises(ValueError, u
"{0".format
)
1265 self
.assertRaises(IndexError, u
"{0.}".format
)
1266 self
.assertRaises(ValueError, u
"{0.}".format
, 0)
1267 self
.assertRaises(IndexError, u
"{0[}".format
)
1268 self
.assertRaises(ValueError, u
"{0[}".format
, [])
1269 self
.assertRaises(KeyError, u
"{0]}".format
)
1270 self
.assertRaises(ValueError, u
"{0.[]}".format
, 0)
1271 self
.assertRaises(ValueError, u
"{0..foo}".format
, 0)
1272 self
.assertRaises(ValueError, u
"{0[0}".format
, 0)
1273 self
.assertRaises(ValueError, u
"{0[0:foo}".format
, 0)
1274 self
.assertRaises(KeyError, u
"{c]}".format
)
1275 self
.assertRaises(ValueError, u
"{{ {{{0}}".format
, 0)
1276 self
.assertRaises(ValueError, u
"{0}}".format
, 0)
1277 self
.assertRaises(KeyError, u
"{foo}".format
, bar
=3)
1278 self
.assertRaises(ValueError, u
"{0!x}".format
, 3)
1279 self
.assertRaises(ValueError, u
"{0!}".format
, 0)
1280 self
.assertRaises(ValueError, u
"{0!rs}".format
, 0)
1281 self
.assertRaises(ValueError, u
"{!}".format
)
1282 self
.assertRaises(IndexError, u
"{:}".format
)
1283 self
.assertRaises(IndexError, u
"{:s}".format
)
1284 self
.assertRaises(IndexError, u
"{}".format
)
1285 big
= u
"23098475029384702983476098230754973209482573"
1286 self
.assertRaises(ValueError, (u
"{" + big
+ u
"}").format
)
1287 self
.assertRaises(ValueError, (u
"{[" + big
+ u
"]}").format
, [0])
1290 self
.assertRaises(ValueError, u
"{0[0]x}".format
, [None])
1291 self
.assertRaises(ValueError, u
"{0[0](10)}".format
, [None])
1293 # can't have a replacement on the field name portion
1294 self
.assertRaises(TypeError, u
'{0[{1}]}'.format
, u
'abcdefg', 4)
1296 # exceed maximum recursion depth
1297 self
.assertRaises(ValueError, u
"{0:{1:{2}}}".format
, u
'abc', u
's', u
'')
1298 self
.assertRaises(ValueError, u
"{0:{1:{2:{3:{4:{5:{6}}}}}}}".format
,
1299 0, 1, 2, 3, 4, 5, 6, 7)
1301 # string format spec errors
1302 self
.assertRaises(ValueError, u
"{0:-s}".format
, u
'')
1303 self
.assertRaises(ValueError, format
, u
"", u
"-")
1304 self
.assertRaises(ValueError, u
"{0:=s}".format
, u
'')
1306 # test combining string and unicode
1307 self
.assertEqual(u
"foo{0}".format('bar'), u
'foobar')
1308 # This will try to convert the argument from unicode to str, which
1310 self
.assertEqual("foo{0}".format(u
'bar'), 'foobar')
1311 # This will try to convert the argument from unicode to str, which
1313 self
.assertRaises(UnicodeEncodeError, "foo{0}".format
, u
'\u1000bar')
1315 def test_format_auto_numbering(self
):
1317 def __init__(self
, x
=100):
1319 def __format__(self
, spec
):
1322 self
.assertEqual(u
'{}'.format(10), u
'10')
1323 self
.assertEqual(u
'{:5}'.format('s'), u
's ')
1324 self
.assertEqual(u
'{!r}'.format('s'), u
"'s'")
1325 self
.assertEqual(u
'{._x}'.format(C(10)), u
'10')
1326 self
.assertEqual(u
'{[1]}'.format([1, 2]), u
'2')
1327 self
.assertEqual(u
'{[a]}'.format({'a':4, 'b':2}), u
'4')
1328 self
.assertEqual(u
'a{}b{}c'.format(0, 1), u
'a0b1c')
1330 self
.assertEqual(u
'a{:{}}b'.format('x', '^10'), u
'a x b')
1331 self
.assertEqual(u
'a{:{}x}b'.format(20, '#'), u
'a0x14b')
1333 # can't mix and match numbering and auto-numbering
1334 self
.assertRaises(ValueError, u
'{}{1}'.format
, 1, 2)
1335 self
.assertRaises(ValueError, u
'{1}{}'.format
, 1, 2)
1336 self
.assertRaises(ValueError, u
'{:{1}}'.format
, 1, 2)
1337 self
.assertRaises(ValueError, u
'{0:{}}'.format
, 1, 2)
1339 # can mix and match auto-numbering and named
1340 self
.assertEqual(u
'{f}{}'.format(4, f
='test'), u
'test4')
1341 self
.assertEqual(u
'{}{f}'.format(4, f
='test'), u
'4test')
1342 self
.assertEqual(u
'{:{f}}{g}{}'.format(1, 3, g
='g', f
=2), u
' 1g3')
1343 self
.assertEqual(u
'{f:{}}{}{g}'.format(2, 4, f
=1, g
='g'), u
' 14g')
1345 def test_raiseMemError(self
):
1346 # Ensure that the freelist contains a consistent object, even
1347 # when a string allocation fails with a MemoryError.
1348 # This used to crash the interpreter,
1349 # or leak references when the number was smaller.
1350 charwidth
= 4 if sys
.maxunicode
>= 0x10000 else 2
1351 # Note: sys.maxsize is half of the actual max allocation because of
1352 # the signedness of Py_ssize_t.
1353 alloc
= lambda: u
"a" * (sys
.maxsize
// charwidth
* 2)
1354 self
.assertRaises(MemoryError, alloc
)
1355 self
.assertRaises(MemoryError, alloc
)
1357 def test_format_subclass(self
):
1359 def __unicode__(self
):
1360 return u
'__unicode__ overridden'
1362 self
.assertEquals("%s" % u
, u
'__unicode__ overridden')
1363 self
.assertEquals("{}".format(u
), u
'__unicode__ overridden')
1367 test_support
.run_unittest(__name__
)
1369 if __name__
== "__main__":