blob: f359082267dca83f5b7231931dff4bceb5dcf3dc [file] [log] [blame]
Guido van Rossuma831cac2000-03-10 23:23:21 +00001""" Test script for the Unicode implementation.
2
Guido van Rossuma831cac2000-03-10 23:23:21 +00003Written by Marc-Andre Lemburg (mal@lemburg.com).
4
5(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
6
Marc-André Lemburg36619082001-01-17 19:11:13 +00007"""#"
Victor Stinner040e16e2011-11-15 22:44:05 +01008import _string
Guido van Rossum98297ee2007-11-06 21:34:58 +00009import codecs
10import struct
11import sys
12import unittest
13import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support, string_tests
Guido van Rossuma831cac2000-03-10 23:23:21 +000015
Neal Norwitz430f68b2005-11-24 22:00:56 +000016# Error handling (bad decoder return)
17def search_function(encoding):
18 def decode1(input, errors="strict"):
19 return 42 # not a tuple
20 def encode1(input, errors="strict"):
21 return 42 # not a tuple
22 def encode2(input, errors="strict"):
23 return (42, 42) # no unicode
24 def decode2(input, errors="strict"):
25 return (42, 42) # no unicode
26 if encoding=="test.unicode1":
27 return (encode1, decode1, None, None)
28 elif encoding=="test.unicode2":
29 return (encode2, decode2, None, None)
30 else:
31 return None
32codecs.register(search_function)
33
Brett Cannon226b2302010-03-20 22:22:22 +000034class UnicodeTest(string_tests.CommonTest,
35 string_tests.MixinStrUnicodeUserStringTest,
Ezio Melotti0dceb562013-01-10 07:43:26 +020036 string_tests.MixinStrUnicodeTest,
37 unittest.TestCase):
Brett Cannon226b2302010-03-20 22:22:22 +000038
Guido van Rossumef87d6e2007-05-02 19:09:54 +000039 type2test = str
Walter Dörwald0fd583c2003-02-21 12:53:50 +000040
41 def checkequalnofix(self, result, object, methodname, *args):
42 method = getattr(object, methodname)
43 realresult = method(*args)
44 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000045 self.assertTrue(type(realresult) is type(result))
Walter Dörwald0fd583c2003-02-21 12:53:50 +000046
47 # if the original is returned make sure that
48 # this doesn't happen with subclasses
49 if realresult is object:
Guido van Rossumef87d6e2007-05-02 19:09:54 +000050 class usub(str):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000051 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000052 return 'usub(%r)' % str.__repr__(self)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000053 object = usub(object)
54 method = getattr(object, methodname)
55 realresult = method(*args)
56 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000057 self.assertTrue(object is not realresult)
Guido van Rossume4874ae2001-09-21 15:36:41 +000058
Jeremy Hylton504de6b2003-10-06 05:08:26 +000059 def test_literals(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000060 self.assertEqual('\xff', '\u00ff')
61 self.assertEqual('\uffff', '\U0000ffff')
Guido van Rossum36e0a922007-07-20 04:05:57 +000062 self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
63 self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
64 self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
Benjamin Petersoncd76c272008-04-05 15:09:30 +000065 # raw strings should not have unicode escapes
Florent Xiclunaa87b3832010-09-13 02:28:18 +000066 self.assertNotEqual(r"\u0020", " ")
Jeremy Hylton504de6b2003-10-06 05:08:26 +000067
Georg Brandl559e5d72008-06-11 18:37:52 +000068 def test_ascii(self):
69 if not sys.platform.startswith('java'):
70 # Test basic sanity of repr()
71 self.assertEqual(ascii('abc'), "'abc'")
72 self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
73 self.assertEqual(ascii('ab\\'), "'ab\\\\'")
74 self.assertEqual(ascii('\\c'), "'\\\\c'")
75 self.assertEqual(ascii('\\'), "'\\\\'")
76 self.assertEqual(ascii('\n'), "'\\n'")
77 self.assertEqual(ascii('\r'), "'\\r'")
78 self.assertEqual(ascii('\t'), "'\\t'")
79 self.assertEqual(ascii('\b'), "'\\x08'")
80 self.assertEqual(ascii("'\""), """'\\'"'""")
81 self.assertEqual(ascii("'\""), """'\\'"'""")
82 self.assertEqual(ascii("'"), '''"'"''')
83 self.assertEqual(ascii('"'), """'"'""")
84 latin1repr = (
85 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
86 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
87 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
88 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
89 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
90 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
91 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
92 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
93 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
94 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
95 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
96 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
97 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
98 "\\xfe\\xff'")
99 testrepr = ascii(''.join(map(chr, range(256))))
100 self.assertEqual(testrepr, latin1repr)
101 # Test ascii works on wide unicode escapes without overflow.
102 self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
103 ascii("\U00010000" * 39 + "\uffff" * 4096))
104
105 class WrongRepr:
106 def __repr__(self):
107 return b'byte-repr'
108 self.assertRaises(TypeError, ascii, WrongRepr())
109
Walter Dörwald28256f22003-01-19 16:59:20 +0000110 def test_repr(self):
111 if not sys.platform.startswith('java'):
112 # Test basic sanity of repr()
Walter Dörwald67e83882007-05-05 12:26:27 +0000113 self.assertEqual(repr('abc'), "'abc'")
114 self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
115 self.assertEqual(repr('ab\\'), "'ab\\\\'")
116 self.assertEqual(repr('\\c'), "'\\\\c'")
117 self.assertEqual(repr('\\'), "'\\\\'")
118 self.assertEqual(repr('\n'), "'\\n'")
119 self.assertEqual(repr('\r'), "'\\r'")
120 self.assertEqual(repr('\t'), "'\\t'")
121 self.assertEqual(repr('\b'), "'\\x08'")
122 self.assertEqual(repr("'\""), """'\\'"'""")
123 self.assertEqual(repr("'\""), """'\\'"'""")
124 self.assertEqual(repr("'"), '''"'"''')
125 self.assertEqual(repr('"'), """'"'""")
Walter Dörwald28256f22003-01-19 16:59:20 +0000126 latin1repr = (
Walter Dörwald67e83882007-05-05 12:26:27 +0000127 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
Walter Dörwald28256f22003-01-19 16:59:20 +0000128 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
129 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
130 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
131 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
132 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
Georg Brandl559e5d72008-06-11 18:37:52 +0000133 "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
134 "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
135 "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
136 "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
137 "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
138 "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
139 "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
140 "\xfe\xff'")
Guido van Rossum805365e2007-05-07 22:24:25 +0000141 testrepr = repr(''.join(map(chr, range(256))))
Walter Dörwald28256f22003-01-19 16:59:20 +0000142 self.assertEqual(testrepr, latin1repr)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000143 # Test repr works on wide unicode escapes without overflow.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000144 self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
145 repr("\U00010000" * 39 + "\uffff" * 4096))
Walter Dörwald28256f22003-01-19 16:59:20 +0000146
Georg Brandl559e5d72008-06-11 18:37:52 +0000147 class WrongRepr:
148 def __repr__(self):
149 return b'byte-repr'
150 self.assertRaises(TypeError, repr, WrongRepr())
151
Guido van Rossum49d6b072006-08-17 21:11:47 +0000152 def test_iterators(self):
153 # Make sure unicode objects have an __iter__ method
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000154 it = "\u1111\u2222\u3333".__iter__()
155 self.assertEqual(next(it), "\u1111")
156 self.assertEqual(next(it), "\u2222")
157 self.assertEqual(next(it), "\u3333")
Georg Brandla18af4e2007-04-21 15:47:16 +0000158 self.assertRaises(StopIteration, next, it)
Guido van Rossum49d6b072006-08-17 21:11:47 +0000159
Walter Dörwald28256f22003-01-19 16:59:20 +0000160 def test_count(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000161 string_tests.CommonTest.test_count(self)
162 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000163 self.checkequalnofix(3, 'aaa', 'count', 'a')
164 self.checkequalnofix(0, 'aaa', 'count', 'b')
165 self.checkequalnofix(3, 'aaa', 'count', 'a')
166 self.checkequalnofix(0, 'aaa', 'count', 'b')
167 self.checkequalnofix(0, 'aaa', 'count', 'b')
168 self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
169 self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
170 self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
171 self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000172
Walter Dörwald28256f22003-01-19 16:59:20 +0000173 def test_find(self):
Antoine Pitrouc0bbe7d2011-10-08 22:41:35 +0200174 string_tests.CommonTest.test_find(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200175 # test implementation details of the memchr fast path
176 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
177 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
178 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
179 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
180 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
181 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
182 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
183 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000184 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
185 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
186 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000187
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000188 self.assertRaises(TypeError, 'hello'.find)
189 self.assertRaises(TypeError, 'hello'.find, 42)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000190
Walter Dörwald28256f22003-01-19 16:59:20 +0000191 def test_rfind(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000192 string_tests.CommonTest.test_rfind(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200193 # test implementation details of the memrchr fast path
194 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
195 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
196 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
197 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
198 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
199 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
200 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000201 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000202 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
203 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
204 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
Guido van Rossum8b264542000-12-19 02:22:31 +0000205
Walter Dörwald28256f22003-01-19 16:59:20 +0000206 def test_index(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000207 string_tests.CommonTest.test_index(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000208 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
209 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
210 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
211 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
212 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
213 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
214 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
215 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000216
Walter Dörwald28256f22003-01-19 16:59:20 +0000217 def test_rindex(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000218 string_tests.CommonTest.test_rindex(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000219 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
220 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
221 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
222 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000223
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000224 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
225 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
226 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
227 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
228 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000229
Georg Brandlceee0772007-11-27 23:48:05 +0000230 def test_maketrans_translate(self):
231 # these work with plain translate()
232 self.checkequalnofix('bbbc', 'abababc', 'translate',
233 {ord('a'): None})
234 self.checkequalnofix('iiic', 'abababc', 'translate',
235 {ord('a'): None, ord('b'): ord('i')})
236 self.checkequalnofix('iiix', 'abababc', 'translate',
237 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
238 self.checkequalnofix('c', 'abababc', 'translate',
239 {ord('a'): None, ord('b'): ''})
240 self.checkequalnofix('xyyx', 'xzx', 'translate',
241 {ord('z'): 'yy'})
242 # this needs maketrans()
243 self.checkequalnofix('abababc', 'abababc', 'translate',
244 {'b': '<i>'})
245 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
246 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
247 # test alternative way of calling maketrans()
248 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
249 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
250
251 self.assertRaises(TypeError, self.type2test.maketrans)
252 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
253 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
254 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
255 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
256 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
257 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
Guido van Rossuma831cac2000-03-10 23:23:21 +0000258
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000259 self.assertRaises(TypeError, 'hello'.translate)
Walter Dörwald67e83882007-05-05 12:26:27 +0000260 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000261
Walter Dörwald28256f22003-01-19 16:59:20 +0000262 def test_split(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000263 string_tests.CommonTest.test_split(self)
Andrew M. Kuchlingeddd68d2002-03-29 16:21:44 +0000264
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000265 # Mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000266 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
267 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
268 self.checkequalnofix(['endcase ', ''], 'endcase test', 'split', 'test')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000269
Walter Dörwald28256f22003-01-19 16:59:20 +0000270 def test_join(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000271 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +0000272
Guido van Rossumf1044292007-09-27 18:01:22 +0000273 class MyWrapper:
274 def __init__(self, sval): self.sval = sval
275 def __str__(self): return self.sval
276
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000277 # mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000278 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
279 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
280 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
281 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
282 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
283 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
284 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000285 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
286 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
287 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
288 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
Marc-André Lemburge5034372000-08-08 08:04:29 +0000289
Walter Dörwald28256f22003-01-19 16:59:20 +0000290 def test_replace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000291 string_tests.CommonTest.test_replace(self)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000292
Walter Dörwald28256f22003-01-19 16:59:20 +0000293 # method call forwarded from str implementation because of unicode argument
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000294 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
295 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000296
Victor Stinner59de0ee2011-10-07 10:01:28 +0200297 @support.cpython_only
298 def test_replace_id(self):
Victor Stinner1d972ad2011-10-07 13:31:46 +0200299 pattern = 'abc'
300 text = 'abc def'
301 self.assertIs(text.replace(pattern, pattern), text)
Victor Stinner59de0ee2011-10-07 10:01:28 +0200302
Guido van Rossum98297ee2007-11-06 21:34:58 +0000303 def test_bytes_comparison(self):
Brett Cannon226b2302010-03-20 22:22:22 +0000304 with support.check_warnings():
305 warnings.simplefilter('ignore', BytesWarning)
306 self.assertEqual('abc' == b'abc', False)
307 self.assertEqual('abc' != b'abc', True)
308 self.assertEqual('abc' == bytearray(b'abc'), False)
309 self.assertEqual('abc' != bytearray(b'abc'), True)
Brett Cannon40430012007-10-22 20:24:51 +0000310
Walter Dörwald28256f22003-01-19 16:59:20 +0000311 def test_comparison(self):
312 # Comparisons:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000313 self.assertEqual('abc', 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000314 self.assertTrue('abcd' > 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertTrue('abc' < 'abcd')
Walter Dörwald28256f22003-01-19 16:59:20 +0000316
317 if 0:
318 # Move these tests to a Unicode collation module test...
319 # Testing UTF-16 code point order comparisons...
320
321 # No surrogates, no fixup required.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000322 self.assertTrue('\u0061' < '\u20ac')
Walter Dörwald28256f22003-01-19 16:59:20 +0000323 # Non surrogate below surrogate value, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000324 self.assertTrue('\u0061' < '\ud800\udc02')
Walter Dörwald28256f22003-01-19 16:59:20 +0000325
326 # Non surrogate above surrogate value, fixup required
327 def test_lecmp(s, s2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000328 self.assertTrue(s < s2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000329
330 def test_fixup(s):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000331 s2 = '\ud800\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000332 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000333 s2 = '\ud900\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000334 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000335 s2 = '\uda00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000336 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000337 s2 = '\udb00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000338 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000339 s2 = '\ud800\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000340 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000341 s2 = '\ud900\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000342 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000343 s2 = '\uda00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000344 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000345 s2 = '\udb00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000346 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000347 s2 = '\ud800\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000348 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000349 s2 = '\ud900\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000350 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000351 s2 = '\uda00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000352 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000353 s2 = '\udb00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000354 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000355 s2 = '\ud800\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000356 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000357 s2 = '\ud900\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000358 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000359 s2 = '\uda00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000360 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000361 s2 = '\udb00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000362 test_lecmp(s, s2)
363
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000364 test_fixup('\ue000')
365 test_fixup('\uff61')
Walter Dörwald28256f22003-01-19 16:59:20 +0000366
367 # Surrogates on both sides, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000368 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
Walter Dörwald28256f22003-01-19 16:59:20 +0000369
Walter Dörwald28256f22003-01-19 16:59:20 +0000370 def test_islower(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000371 string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000372 self.checkequalnofix(False, '\u1FFc', 'islower')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500373 self.assertFalse('\u2167'.islower())
374 self.assertTrue('\u2177'.islower())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300375 # non-BMP, uppercase
376 self.assertFalse('\U00010401'.islower())
377 self.assertFalse('\U00010427'.islower())
378 # non-BMP, lowercase
379 self.assertTrue('\U00010429'.islower())
380 self.assertTrue('\U0001044E'.islower())
381 # non-BMP, non-cased
382 self.assertFalse('\U0001F40D'.islower())
383 self.assertFalse('\U0001F46F'.islower())
Walter Dörwald28256f22003-01-19 16:59:20 +0000384
385 def test_isupper(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000386 string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
387 if not sys.platform.startswith('java'):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000388 self.checkequalnofix(False, '\u1FFc', 'isupper')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500389 self.assertTrue('\u2167'.isupper())
390 self.assertFalse('\u2177'.isupper())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300391 # non-BMP, uppercase
392 self.assertTrue('\U00010401'.isupper())
393 self.assertTrue('\U00010427'.isupper())
394 # non-BMP, lowercase
395 self.assertFalse('\U00010429'.isupper())
396 self.assertFalse('\U0001044E'.isupper())
397 # non-BMP, non-cased
398 self.assertFalse('\U0001F40D'.isupper())
399 self.assertFalse('\U0001F46F'.isupper())
Walter Dörwald28256f22003-01-19 16:59:20 +0000400
401 def test_istitle(self):
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300402 string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000403 self.checkequalnofix(True, '\u1FFc', 'istitle')
404 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
Walter Dörwald28256f22003-01-19 16:59:20 +0000405
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300406 # non-BMP, uppercase + lowercase
407 self.assertTrue('\U00010401\U00010429'.istitle())
408 self.assertTrue('\U00010427\U0001044E'.istitle())
409 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
410 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
411 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
412
Walter Dörwald28256f22003-01-19 16:59:20 +0000413 def test_isspace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000414 string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000415 self.checkequalnofix(True, '\u2000', 'isspace')
416 self.checkequalnofix(True, '\u200a', 'isspace')
417 self.checkequalnofix(False, '\u2014', 'isspace')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300418 # apparently there are no non-BMP spaces chars in Unicode 6
419 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
420 '\U0001F40D', '\U0001F46F']:
421 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
422
423 def test_isalnum(self):
424 string_tests.MixinStrUnicodeUserStringTest.test_isalnum(self)
425 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
426 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
427 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
Walter Dörwald28256f22003-01-19 16:59:20 +0000428
429 def test_isalpha(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000430 string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000431 self.checkequalnofix(True, '\u1FFc', 'isalpha')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300432 # non-BMP, cased
433 self.assertTrue('\U00010401'.isalpha())
434 self.assertTrue('\U00010427'.isalpha())
435 self.assertTrue('\U00010429'.isalpha())
436 self.assertTrue('\U0001044E'.isalpha())
437 # non-BMP, non-cased
438 self.assertFalse('\U0001F40D'.isalpha())
439 self.assertFalse('\U0001F46F'.isalpha())
Walter Dörwald28256f22003-01-19 16:59:20 +0000440
441 def test_isdecimal(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000442 self.checkequalnofix(False, '', 'isdecimal')
443 self.checkequalnofix(False, 'a', 'isdecimal')
444 self.checkequalnofix(True, '0', 'isdecimal')
445 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
446 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
447 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
448 self.checkequalnofix(True, '0123456789', 'isdecimal')
449 self.checkequalnofix(False, '0123456789a', 'isdecimal')
Walter Dörwald28256f22003-01-19 16:59:20 +0000450
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000451 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000452
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300453 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
454 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
455 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
456 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
457 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
458
Walter Dörwald28256f22003-01-19 16:59:20 +0000459 def test_isdigit(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000460 string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000461 self.checkequalnofix(True, '\u2460', 'isdigit')
462 self.checkequalnofix(False, '\xbc', 'isdigit')
463 self.checkequalnofix(True, '\u0660', 'isdigit')
Walter Dörwald28256f22003-01-19 16:59:20 +0000464
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300465 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
466 '\U0001F40D', '\U0001F46F', '\U00011065']:
467 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
468 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
469 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
470
Walter Dörwald28256f22003-01-19 16:59:20 +0000471 def test_isnumeric(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000472 self.checkequalnofix(False, '', 'isnumeric')
473 self.checkequalnofix(False, 'a', 'isnumeric')
474 self.checkequalnofix(True, '0', 'isnumeric')
475 self.checkequalnofix(True, '\u2460', 'isnumeric')
476 self.checkequalnofix(True, '\xbc', 'isnumeric')
477 self.checkequalnofix(True, '\u0660', 'isnumeric')
478 self.checkequalnofix(True, '0123456789', 'isnumeric')
479 self.checkequalnofix(False, '0123456789a', 'isnumeric')
Walter Dörwald28256f22003-01-19 16:59:20 +0000480
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000481 self.assertRaises(TypeError, "abc".isnumeric, 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000482
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300483 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
484 '\U0001F40D', '\U0001F46F']:
485 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
486 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
487 '\U000104A0', '\U0001F107']:
488 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
489
Martin v. Löwis47383402007-08-15 07:32:56 +0000490 def test_isidentifier(self):
491 self.assertTrue("a".isidentifier())
492 self.assertTrue("Z".isidentifier())
493 self.assertTrue("_".isidentifier())
494 self.assertTrue("b0".isidentifier())
495 self.assertTrue("bc".isidentifier())
496 self.assertTrue("b_".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000497 self.assertTrue("µ".isidentifier())
Benjamin Petersonf413b802011-08-12 22:17:18 -0500498 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000499
500 self.assertFalse(" ".isidentifier())
501 self.assertFalse("[".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000502 self.assertFalse("©".isidentifier())
Georg Brandld52429f2008-07-04 15:55:02 +0000503 self.assertFalse("0".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000504
Georg Brandl559e5d72008-06-11 18:37:52 +0000505 def test_isprintable(self):
506 self.assertTrue("".isprintable())
Benjamin Peterson09832742009-03-26 17:15:46 +0000507 self.assertTrue(" ".isprintable())
Georg Brandl559e5d72008-06-11 18:37:52 +0000508 self.assertTrue("abcdefg".isprintable())
509 self.assertFalse("abcdefg\n".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000510 # some defined Unicode character
511 self.assertTrue("\u0374".isprintable())
512 # undefined character
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000513 self.assertFalse("\u0378".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000514 # single surrogate character
Georg Brandl559e5d72008-06-11 18:37:52 +0000515 self.assertFalse("\ud800".isprintable())
516
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300517 self.assertTrue('\U0001F46F'.isprintable())
518 self.assertFalse('\U000E0020'.isprintable())
519
520 def test_surrogates(self):
521 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
522 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
523 self.assertTrue(s.islower())
524 self.assertFalse(s.isupper())
525 self.assertFalse(s.istitle())
526 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
527 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
528 self.assertFalse(s.islower())
529 self.assertTrue(s.isupper())
530 self.assertTrue(s.istitle())
531
532 for meth_name in ('islower', 'isupper', 'istitle'):
533 meth = getattr(str, meth_name)
534 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
535 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
536
537 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
538 'isdecimal', 'isnumeric',
539 'isidentifier', 'isprintable'):
540 meth = getattr(str, meth_name)
541 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
542 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
543 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
544 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
545
546
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300547 def test_lower(self):
548 string_tests.CommonTest.test_lower(self)
549 self.assertEqual('\U00010427'.lower(), '\U0001044F')
550 self.assertEqual('\U00010427\U00010427'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300551 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300552 self.assertEqual('\U00010427\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300553 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300554 self.assertEqual('X\U00010427x\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300555 'x\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500556 self.assertEqual('fi'.lower(), 'fi')
557 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
558 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
559 self.assertEqual('\u03a3'.lower(), '\u03c3')
560 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
561 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
562 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
563 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
564 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
565 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
566 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
567 self.assertEqual('\u2177'.lower(), '\u2177')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300568
Benjamin Petersond5890c82012-01-14 13:23:30 -0500569 def test_casefold(self):
570 self.assertEqual('hello'.casefold(), 'hello')
571 self.assertEqual('hELlo'.casefold(), 'hello')
572 self.assertEqual('ß'.casefold(), 'ss')
573 self.assertEqual('fi'.casefold(), 'fi')
574 self.assertEqual('\u03a3'.casefold(), '\u03c3')
575 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
Benjamin Peterson4eda9372012-08-05 15:05:34 -0700576 self.assertEqual('\u00b5'.casefold(), '\u03bc')
Benjamin Petersond5890c82012-01-14 13:23:30 -0500577
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300578 def test_upper(self):
579 string_tests.CommonTest.test_upper(self)
580 self.assertEqual('\U0001044F'.upper(), '\U00010427')
581 self.assertEqual('\U0001044F\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300582 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300583 self.assertEqual('\U00010427\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300584 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300585 self.assertEqual('X\U00010427x\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300586 'X\U00010427X\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500587 self.assertEqual('fi'.upper(), 'FI')
588 self.assertEqual('\u0130'.upper(), '\u0130')
589 self.assertEqual('\u03a3'.upper(), '\u03a3')
590 self.assertEqual('ß'.upper(), 'SS')
591 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
592 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
593 self.assertEqual('\u2177'.upper(), '\u2167')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300594
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300595 def test_capitalize(self):
596 string_tests.CommonTest.test_capitalize(self)
597 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
598 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300599 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300600 self.assertEqual('\U00010427\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300601 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300602 self.assertEqual('\U0001044F\U00010427'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300603 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300604 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300605 'X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500606 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
607 exp = '\u0399\u0308\u0300\u0069\u0307'
608 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
609 self.assertEqual('finnish'.capitalize(), 'FInnish')
610 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300611
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300612 def test_title(self):
613 string_tests.MixinStrUnicodeUserStringTest.test_title(self)
614 self.assertEqual('\U0001044F'.title(), '\U00010427')
615 self.assertEqual('\U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300616 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300617 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300618 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300619 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300620 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300621 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300622 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300623 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300624 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500625 self.assertEqual('fiNNISH'.title(), 'Finnish')
626 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
627 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300628
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300629 def test_swapcase(self):
630 string_tests.CommonTest.test_swapcase(self)
631 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
632 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
633 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300634 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300635 self.assertEqual('\U00010427\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300636 '\U0001044F\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300637 self.assertEqual('\U0001044F\U00010427'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300638 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300639 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300640 'x\U0001044FX\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500641 self.assertEqual('fi'.swapcase(), 'FI')
642 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
643 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
644 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
645 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
646 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
647 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
648 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
649 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
650 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
651 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
652 self.assertEqual('ß'.swapcase(), 'SS')
653 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300654
Ezio Melottif84e01d2013-07-08 17:48:29 +0200655 def test_center(self):
656 string_tests.CommonTest.test_center(self)
657 self.assertEqual('x'.center(2, '\U0010FFFF'),
658 'x\U0010FFFF')
659 self.assertEqual('x'.center(3, '\U0010FFFF'),
660 '\U0010FFFFx\U0010FFFF')
661 self.assertEqual('x'.center(4, '\U0010FFFF'),
662 '\U0010FFFFx\U0010FFFF\U0010FFFF')
663
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400664 @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
Benjamin Peterson4d856892014-10-15 13:39:46 -0400665 @support.cpython_only
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400666 def test_case_operation_overflow(self):
667 # Issue #22643
668 self.assertRaises(OverflowError, ("ü"*(2**32//12 + 1)).upper)
669
Walter Dörwald28256f22003-01-19 16:59:20 +0000670 def test_contains(self):
671 # Testing Unicode contains method
Benjamin Peterson577473f2010-01-19 00:09:57 +0000672 self.assertIn('a', 'abdb')
673 self.assertIn('a', 'bdab')
674 self.assertIn('a', 'bdaba')
675 self.assertIn('a', 'bdba')
676 self.assertNotIn('a', 'bdb')
677 self.assertIn('a', 'bdba')
678 self.assertIn('a', ('a',1,None))
679 self.assertIn('a', (1,None,'a'))
680 self.assertIn('a', ('a',1,None))
681 self.assertIn('a', (1,None,'a'))
682 self.assertNotIn('a', ('x',1,'y'))
683 self.assertNotIn('a', ('x',1,None))
684 self.assertNotIn('abcd', 'abcxxxx')
685 self.assertIn('ab', 'abcd')
686 self.assertIn('ab', 'abc')
687 self.assertIn('ab', (1,None,'ab'))
688 self.assertIn('', 'abc')
689 self.assertIn('', '')
690 self.assertIn('', 'abc')
691 self.assertNotIn('\0', 'abc')
692 self.assertIn('\0', '\0abc')
693 self.assertIn('\0', 'abc\0')
694 self.assertIn('a', '\0abc')
695 self.assertIn('asdf', 'asdf')
696 self.assertNotIn('asdf', 'asd')
697 self.assertNotIn('asdf', '')
Walter Dörwald28256f22003-01-19 16:59:20 +0000698
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000699 self.assertRaises(TypeError, "abc".__contains__)
Walter Dörwald28256f22003-01-19 16:59:20 +0000700
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +0300701 def test_issue18183(self):
702 '\U00010000\U00100000'.lower()
703 '\U00010000\U00100000'.casefold()
704 '\U00010000\U00100000'.upper()
705 '\U00010000\U00100000'.capitalize()
706 '\U00010000\U00100000'.title()
707 '\U00010000\U00100000'.swapcase()
708 '\U00100000'.center(3, '\U00010000')
709 '\U00100000'.ljust(3, '\U00010000')
710 '\U00100000'.rjust(3, '\U00010000')
711
Eric Smith8c663262007-08-25 02:26:07 +0000712 def test_format(self):
713 self.assertEqual(''.format(), '')
714 self.assertEqual('a'.format(), 'a')
715 self.assertEqual('ab'.format(), 'ab')
716 self.assertEqual('a{{'.format(), 'a{')
717 self.assertEqual('a}}'.format(), 'a}')
718 self.assertEqual('{{b'.format(), '{b')
719 self.assertEqual('}}b'.format(), '}b')
720 self.assertEqual('a{{b'.format(), 'a{b')
721
722 # examples from the PEP:
723 import datetime
724 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
725 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
726 "My name is Fred")
727 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
728 "My name is Fred :-{}")
729
730 d = datetime.date(2007, 8, 18)
731 self.assertEqual("The year is {0.year}".format(d),
732 "The year is 2007")
733
Eric Smith8c663262007-08-25 02:26:07 +0000734 # classes we'll use for testing
735 class C:
736 def __init__(self, x=100):
737 self._x = x
738 def __format__(self, spec):
739 return spec
740
741 class D:
742 def __init__(self, x):
743 self.x = x
744 def __format__(self, spec):
745 return str(self.x)
746
747 # class with __str__, but no __format__
748 class E:
749 def __init__(self, x):
750 self.x = x
751 def __str__(self):
752 return 'E(' + self.x + ')'
753
754 # class with __repr__, but no __format__ or __str__
755 class F:
756 def __init__(self, x):
757 self.x = x
758 def __repr__(self):
759 return 'F(' + self.x + ')'
760
761 # class with __format__ that forwards to string, for some format_spec's
762 class G:
763 def __init__(self, x):
764 self.x = x
765 def __str__(self):
766 return "string is " + self.x
767 def __format__(self, format_spec):
768 if format_spec == 'd':
769 return 'G(' + self.x + ')'
770 return object.__format__(self, format_spec)
771
Eric Smith739e2ad2007-08-27 19:07:22 +0000772 class I(datetime.date):
773 def __format__(self, format_spec):
774 return self.strftime(format_spec)
775
Eric Smith185e30c2007-08-30 22:23:08 +0000776 class J(int):
777 def __format__(self, format_spec):
778 return int.__format__(self * 2, format_spec)
779
Eric Smith8c663262007-08-25 02:26:07 +0000780
781 self.assertEqual(''.format(), '')
782 self.assertEqual('abc'.format(), 'abc')
783 self.assertEqual('{0}'.format('abc'), 'abc')
784 self.assertEqual('{0:}'.format('abc'), 'abc')
785# self.assertEqual('{ 0 }'.format('abc'), 'abc')
786 self.assertEqual('X{0}'.format('abc'), 'Xabc')
787 self.assertEqual('{0}X'.format('abc'), 'abcX')
788 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
789 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
790 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
791 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
792 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
793 self.assertEqual('{0}'.format(-15), '-15')
794 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
795 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
796 self.assertEqual('{{'.format(), '{')
797 self.assertEqual('}}'.format(), '}')
798 self.assertEqual('{{}}'.format(), '{}')
799 self.assertEqual('{{x}}'.format(), '{x}')
800 self.assertEqual('{{{0}}}'.format(123), '{123}')
801 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
802 self.assertEqual('}}{{'.format(), '}{')
803 self.assertEqual('}}x{{'.format(), '}x{')
804
Eric Smith7ade6482007-08-26 22:27:13 +0000805 # weird field names
806 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
807 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
Eric Smith4cb4e4e2007-09-03 08:40:29 +0000808 self.assertEqual("{0[ ]}".format({' ':3}), '3')
Eric Smith7ade6482007-08-26 22:27:13 +0000809
Eric Smith8c663262007-08-25 02:26:07 +0000810 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
811 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
812 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
813 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
814 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
815 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
816 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
817
Eric Smith8c663262007-08-25 02:26:07 +0000818 # strings
819 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
820 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
821 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
822 self.assertEqual('{0:.0s}'.format('abcdef'), '')
823 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
824 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
825 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
826 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
827 self.assertEqual('{0:x<0s}'.format('result'), 'result')
828 self.assertEqual('{0:x<5s}'.format('result'), 'result')
829 self.assertEqual('{0:x<6s}'.format('result'), 'result')
830 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
831 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
832 self.assertEqual('{0: <7s}'.format('result'), 'result ')
833 self.assertEqual('{0:<7s}'.format('result'), 'result ')
834 self.assertEqual('{0:>7s}'.format('result'), ' result')
835 self.assertEqual('{0:>8s}'.format('result'), ' result')
836 self.assertEqual('{0:^8s}'.format('result'), ' result ')
837 self.assertEqual('{0:^9s}'.format('result'), ' result ')
838 self.assertEqual('{0:^10s}'.format('result'), ' result ')
839 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
840 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
841 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
842
843 # format specifiers for user defined type
844 self.assertEqual('{0:abc}'.format(C()), 'abc')
845
Georg Brandld52429f2008-07-04 15:55:02 +0000846 # !r, !s and !a coercions
Eric Smith8c663262007-08-25 02:26:07 +0000847 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
848 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
849 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
850 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
851 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
852 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
853 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000854 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +0000855 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
856 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
Georg Brandl559e5d72008-06-11 18:37:52 +0000857 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000858 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +0000859 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
Georg Brandl559e5d72008-06-11 18:37:52 +0000860 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
861 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
Georg Brandld52429f2008-07-04 15:55:02 +0000862 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
Eric Smith8c663262007-08-25 02:26:07 +0000863
Eric Smith8c663262007-08-25 02:26:07 +0000864 # test fallback to object.__format__
865 self.assertEqual('{0}'.format({}), '{}')
866 self.assertEqual('{0}'.format([]), '[]')
867 self.assertEqual('{0}'.format([1]), '[1]')
Eric Smithe4d63172010-09-13 20:48:43 +0000868
Eric Smith8c663262007-08-25 02:26:07 +0000869 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
Eric Smith8c663262007-08-25 02:26:07 +0000870 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
871
Eric Smithe4d63172010-09-13 20:48:43 +0000872 msg = 'object.__format__ with a non-empty format string is deprecated'
Eric V. Smithb9cd3532011-03-12 10:08:48 -0500873 with support.check_warnings((msg, DeprecationWarning)):
Eric Smithe4d63172010-09-13 20:48:43 +0000874 self.assertEqual('{0:^10}'.format(E('data')), ' E(data) ')
875 self.assertEqual('{0:^10s}'.format(E('data')), ' E(data) ')
876 self.assertEqual('{0:>15s}'.format(G('data')), ' string is data')
877
Eric Smith739e2ad2007-08-27 19:07:22 +0000878 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
879 month=8,
880 day=27)),
881 "date: 2007-08-27")
882
Eric Smith185e30c2007-08-30 22:23:08 +0000883 # test deriving from a builtin type and overriding __format__
884 self.assertEqual("{0}".format(J(10)), "20")
885
886
Eric Smith8c663262007-08-25 02:26:07 +0000887 # string format specifiers
888 self.assertEqual('{0:}'.format('a'), 'a')
889
890 # computed format specifiers
891 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
892 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
893 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
894 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
895 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
896
897 # test various errors
898 self.assertRaises(ValueError, '{'.format)
899 self.assertRaises(ValueError, '}'.format)
900 self.assertRaises(ValueError, 'a{'.format)
901 self.assertRaises(ValueError, 'a}'.format)
902 self.assertRaises(ValueError, '{a'.format)
903 self.assertRaises(ValueError, '}a'.format)
Eric Smith11529192007-09-04 23:04:22 +0000904 self.assertRaises(IndexError, '{0}'.format)
905 self.assertRaises(IndexError, '{1}'.format, 'abc')
906 self.assertRaises(KeyError, '{x}'.format)
Eric Smith8c663262007-08-25 02:26:07 +0000907 self.assertRaises(ValueError, "}{".format)
Eric Smith8c663262007-08-25 02:26:07 +0000908 self.assertRaises(ValueError, "abc{0:{}".format)
909 self.assertRaises(ValueError, "{0".format)
Eric Smith11529192007-09-04 23:04:22 +0000910 self.assertRaises(IndexError, "{0.}".format)
911 self.assertRaises(ValueError, "{0.}".format, 0)
912 self.assertRaises(IndexError, "{0[}".format)
Eric Smith4cb4e4e2007-09-03 08:40:29 +0000913 self.assertRaises(ValueError, "{0[}".format, [])
Eric Smith11529192007-09-04 23:04:22 +0000914 self.assertRaises(KeyError, "{0]}".format)
915 self.assertRaises(ValueError, "{0.[]}".format, 0)
Eric Smith7ade6482007-08-26 22:27:13 +0000916 self.assertRaises(ValueError, "{0..foo}".format, 0)
Eric Smith11529192007-09-04 23:04:22 +0000917 self.assertRaises(ValueError, "{0[0}".format, 0)
918 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
919 self.assertRaises(KeyError, "{c]}".format)
920 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
921 self.assertRaises(ValueError, "{0}}".format, 0)
922 self.assertRaises(KeyError, "{foo}".format, bar=3)
Eric Smith8c663262007-08-25 02:26:07 +0000923 self.assertRaises(ValueError, "{0!x}".format, 3)
Eric Smith11529192007-09-04 23:04:22 +0000924 self.assertRaises(ValueError, "{0!}".format, 0)
925 self.assertRaises(ValueError, "{0!rs}".format, 0)
Eric Smith8c663262007-08-25 02:26:07 +0000926 self.assertRaises(ValueError, "{!}".format)
Eric Smith8ec90442009-03-14 12:29:34 +0000927 self.assertRaises(IndexError, "{:}".format)
928 self.assertRaises(IndexError, "{:s}".format)
929 self.assertRaises(IndexError, "{}".format)
Benjamin Peterson59a1b2f2010-06-07 22:31:26 +0000930 big = "23098475029384702983476098230754973209482573"
931 self.assertRaises(ValueError, ("{" + big + "}").format)
932 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
Eric Smith8c663262007-08-25 02:26:07 +0000933
Eric Smith41669ca2009-05-23 14:23:22 +0000934 # issue 6089
935 self.assertRaises(ValueError, "{0[0]x}".format, [None])
936 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
937
Eric Smith8c663262007-08-25 02:26:07 +0000938 # can't have a replacement on the field name portion
939 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
940
941 # exceed maximum recursion depth
942 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
943 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
944 0, 1, 2, 3, 4, 5, 6, 7)
945
946 # string format spec errors
947 self.assertRaises(ValueError, "{0:-s}".format, '')
948 self.assertRaises(ValueError, format, "", "-")
949 self.assertRaises(ValueError, "{0:=s}".format, '')
950
Eric Smithb1ebcc62008-07-15 13:02:41 +0000951 # Alternate formatting is not supported
952 self.assertRaises(ValueError, format, '', '#')
953 self.assertRaises(ValueError, format, '', '#20')
954
Victor Stinnerece58de2012-04-23 23:36:38 +0200955 # Non-ASCII
956 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
957 'ABC\u0410\u0411\u0412')
958 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
959 'ABC')
960 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
961 '')
962
Benjamin Petersond2b58a92013-05-17 17:34:30 -0500963 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
Benjamin Peterson0ee22bf2013-11-26 19:22:36 -0600964 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
Benjamin Petersond2b58a92013-05-17 17:34:30 -0500965
Eric Smith27bbca62010-11-04 17:06:58 +0000966 def test_format_map(self):
967 self.assertEqual(''.format_map({}), '')
968 self.assertEqual('a'.format_map({}), 'a')
969 self.assertEqual('ab'.format_map({}), 'ab')
970 self.assertEqual('a{{'.format_map({}), 'a{')
971 self.assertEqual('a}}'.format_map({}), 'a}')
972 self.assertEqual('{{b'.format_map({}), '{b')
973 self.assertEqual('}}b'.format_map({}), '}b')
974 self.assertEqual('a{{b'.format_map({}), 'a{b')
975
976 # using mappings
977 class Mapping(dict):
978 def __missing__(self, key):
979 return key
980 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
981 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
982
983 class InternalMapping:
984 def __init__(self):
985 self.mapping = {'a': 'hello'}
986 def __getitem__(self, key):
987 return self.mapping[key]
988 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
989
990
Eric Smith27bbca62010-11-04 17:06:58 +0000991 class C:
992 def __init__(self, x=100):
993 self._x = x
994 def __format__(self, spec):
995 return spec
Eric Smith27bbca62010-11-04 17:06:58 +0000996 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
997
998 # test various errors
Eric V. Smithedbb6ca2012-03-12 15:16:22 -0700999 self.assertRaises(TypeError, ''.format_map)
1000 self.assertRaises(TypeError, 'a'.format_map)
1001
1002 self.assertRaises(ValueError, '{'.format_map, {})
1003 self.assertRaises(ValueError, '}'.format_map, {})
1004 self.assertRaises(ValueError, 'a{'.format_map, {})
1005 self.assertRaises(ValueError, 'a}'.format_map, {})
1006 self.assertRaises(ValueError, '{a'.format_map, {})
1007 self.assertRaises(ValueError, '}a'.format_map, {})
Eric Smith27bbca62010-11-04 17:06:58 +00001008
Eric V. Smith12ebefc2011-07-18 14:03:41 -04001009 # issue #12579: can't supply positional params to format_map
1010 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1011 self.assertRaises(ValueError, '{}'.format_map, 'a')
1012 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1013
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001014 def test_format_huge_precision(self):
1015 format_string = ".{}f".format(sys.maxsize + 1)
1016 with self.assertRaises(ValueError):
1017 result = format(2.34, format_string)
1018
1019 def test_format_huge_width(self):
1020 format_string = "{}f".format(sys.maxsize + 1)
1021 with self.assertRaises(ValueError):
1022 result = format(2.34, format_string)
1023
1024 def test_format_huge_item_number(self):
1025 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1026 with self.assertRaises(ValueError):
1027 result = format_string.format(2.34)
1028
Eric Smith8ec90442009-03-14 12:29:34 +00001029 def test_format_auto_numbering(self):
1030 class C:
1031 def __init__(self, x=100):
1032 self._x = x
1033 def __format__(self, spec):
1034 return spec
1035
1036 self.assertEqual('{}'.format(10), '10')
1037 self.assertEqual('{:5}'.format('s'), 's ')
1038 self.assertEqual('{!r}'.format('s'), "'s'")
1039 self.assertEqual('{._x}'.format(C(10)), '10')
1040 self.assertEqual('{[1]}'.format([1, 2]), '2')
1041 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1042 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1043
1044 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1045 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1046
1047 # can't mix and match numbering and auto-numbering
1048 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1049 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1050 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1051 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1052
1053 # can mix and match auto-numbering and named
1054 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1055 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1056 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1057 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1058
Walter Dörwald28256f22003-01-19 16:59:20 +00001059 def test_formatting(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001060 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
Walter Dörwald28256f22003-01-19 16:59:20 +00001061 # Testing Unicode formatting strings...
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001062 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1063 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1064 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1065 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1066 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1067 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57')
Walter Dörwald28256f22003-01-19 16:59:20 +00001068 if not sys.platform.startswith('java'):
Walter Dörwald67e83882007-05-05 12:26:27 +00001069 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
Georg Brandl559e5d72008-06-11 18:37:52 +00001070 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1071 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001072 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1073 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
Walter Dörwald56fbcb52003-03-31 18:18:41 +00001074
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001075 self.assertEqual('%c' % 0x1234, '\u1234')
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00001076 self.assertEqual('%c' % 0x21483, '\U00021483')
1077 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1078 self.assertEqual('%c' % '\U00021483', '\U00021483')
1079 self.assertRaises(TypeError, "%c".__mod__, "aa")
Stefan Krah99212f62010-07-19 17:58:26 +00001080 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07001081 self.assertRaises(TypeError, "%i".__mod__, "aa")
Walter Dörwald28256f22003-01-19 16:59:20 +00001082
1083 # formatting jobs delegated from the string implementation:
Walter Dörwald28256f22003-01-19 16:59:20 +00001084 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001085 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1086 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1087 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1088 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1089 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1090 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1091 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1092 self.assertEqual('...%s...' % "abc", '...abc...')
1093 self.assertEqual('%*s' % (5,'abc',), ' abc')
1094 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1095 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1096 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1097 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1098 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1099 self.assertEqual('%c' % 'a', 'a')
Neil Schemenauercf52c072005-08-12 17:34:58 +00001100 class Wrapper:
1101 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001102 return '\u1234'
1103 self.assertEqual('%s' % Wrapper(), '\u1234')
Walter Dörwald28256f22003-01-19 16:59:20 +00001104
Eric Smith741191f2009-05-06 13:08:15 +00001105 # issue 3382
1106 NAN = float('nan')
1107 INF = float('inf')
1108 self.assertEqual('%f' % NAN, 'nan')
1109 self.assertEqual('%F' % NAN, 'NAN')
1110 self.assertEqual('%f' % INF, 'inf')
1111 self.assertEqual('%F' % INF, 'INF')
1112
Victor Stinnerf59c28c2012-05-09 03:24:14 +02001113 # PEP 393
1114 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1115 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1116
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001117 def test_formatting_huge_precision(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001118 format_string = "%.{}f".format(sys.maxsize + 1)
1119 with self.assertRaises(ValueError):
1120 result = format_string % 2.34
1121
1122 @support.cpython_only
1123 def test_formatting_huge_precision_c_limits(self):
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001124 from _testcapi import INT_MAX
1125 format_string = "%.{}f".format(INT_MAX + 1)
1126 with self.assertRaises(ValueError):
1127 result = format_string % 2.34
1128
1129 def test_formatting_huge_width(self):
1130 format_string = "%{}f".format(sys.maxsize + 1)
1131 with self.assertRaises(ValueError):
1132 result = format_string % 2.34
1133
Ezio Melottiba42fd52011-04-26 06:09:45 +03001134 def test_startswith_endswith_errors(self):
1135 for meth in ('foo'.startswith, 'foo'.endswith):
Ezio Melottif2b3f782011-04-26 06:40:59 +03001136 with self.assertRaises(TypeError) as cm:
Ezio Melottiba42fd52011-04-26 06:09:45 +03001137 meth(['f'])
Ezio Melottif2b3f782011-04-26 06:40:59 +03001138 exc = str(cm.exception)
Ezio Melottiba42fd52011-04-26 06:09:45 +03001139 self.assertIn('str', exc)
1140 self.assertIn('tuple', exc)
1141
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001142 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
Georg Brandlda6b1072006-01-20 17:48:54 +00001143 def test_format_float(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001144 # should not format with a comma, but always with C locale
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001145 self.assertEqual('1.0', '%.1f' % 1.0)
Georg Brandlda6b1072006-01-20 17:48:54 +00001146
Walter Dörwald28256f22003-01-19 16:59:20 +00001147 def test_constructor(self):
1148 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1149
1150 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001151 str('unicode remains unicode'),
1152 'unicode remains unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001153 )
1154
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001155 class UnicodeSubclass(str):
Marc-André Lemburg79f57832002-12-29 19:44:06 +00001156 pass
Guido van Rossuma831cac2000-03-10 23:23:21 +00001157
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001158 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
1159 subclass = UnicodeSubclass(text)
1160 self.assertEqual(str(subclass), text)
1161 self.assertEqual(len(subclass), len(text))
1162 if text == 'ascii':
1163 self.assertEqual(subclass.encode('ascii'), b'ascii')
1164 self.assertEqual(subclass.encode('utf-8'), b'ascii')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001165
Walter Dörwald28256f22003-01-19 16:59:20 +00001166 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001167 str('strings are converted to unicode'),
1168 'strings are converted to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001169 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001170
Walter Dörwald28256f22003-01-19 16:59:20 +00001171 class StringCompat:
1172 def __init__(self, x):
1173 self.x = x
1174 def __str__(self):
1175 return self.x
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001176
Walter Dörwald28256f22003-01-19 16:59:20 +00001177 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001178 str(StringCompat('__str__ compatible objects are recognized')),
1179 '__str__ compatible objects are recognized'
Walter Dörwald28256f22003-01-19 16:59:20 +00001180 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001181
Walter Dörwald28256f22003-01-19 16:59:20 +00001182 # unicode(obj) is compatible to str():
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001183
Walter Dörwald28256f22003-01-19 16:59:20 +00001184 o = StringCompat('unicode(obj) is compatible to str()')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001185 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Walter Dörwald28256f22003-01-19 16:59:20 +00001186 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001187
Guido van Rossume2a383d2007-01-15 16:59:06 +00001188 for obj in (123, 123.45, 123):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001189 self.assertEqual(str(obj), str(str(obj)))
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001190
Walter Dörwald28256f22003-01-19 16:59:20 +00001191 # unicode(obj, encoding, error) tests (this maps to
1192 # PyUnicode_FromEncodedObject() at C level)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001193
Walter Dörwald28256f22003-01-19 16:59:20 +00001194 if not sys.platform.startswith('java'):
1195 self.assertRaises(
1196 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001197 str,
1198 'decoding unicode is not supported',
Walter Dörwald28256f22003-01-19 16:59:20 +00001199 'utf-8',
1200 'strict'
1201 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001202
Walter Dörwald28256f22003-01-19 16:59:20 +00001203 self.assertEqual(
Walter Dörwald67e83882007-05-05 12:26:27 +00001204 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001205 'strings are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001206 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001207
Walter Dörwald28256f22003-01-19 16:59:20 +00001208 if not sys.platform.startswith('java'):
1209 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001210 str(
Guido van Rossumbae07c92007-10-08 02:46:15 +00001211 memoryview(b'character buffers are decoded to unicode'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001212 'utf-8',
1213 'strict'
1214 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001215 'character buffers are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001216 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001217
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001218 self.assertRaises(TypeError, str, 42, 42, 42)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001219
Chris Jerdonek5fae0e52012-11-20 17:45:51 -08001220 def test_constructor_keyword_args(self):
1221 """Pass various keyword argument combinations to the constructor."""
1222 # The object argument can be passed as a keyword.
1223 self.assertEqual(str(object='foo'), 'foo')
1224 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1225 # The errors argument without encoding triggers "decode" mode.
1226 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1227 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1228
1229 def test_constructor_defaults(self):
1230 """Check the constructor argument defaults."""
1231 # The object argument defaults to '' or b''.
1232 self.assertEqual(str(), '')
1233 self.assertEqual(str(errors='strict'), '')
1234 utf8_cent = '¢'.encode('utf-8')
1235 # The encoding argument defaults to utf-8.
1236 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1237 # The errors argument defaults to strict.
1238 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1239
Walter Dörwald28256f22003-01-19 16:59:20 +00001240 def test_codecs_utf7(self):
1241 utfTests = [
Walter Dörwald67e83882007-05-05 12:26:27 +00001242 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1243 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1244 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1245 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1246 ('+', b'+-'),
1247 ('+-', b'+--'),
1248 ('+?', b'+-?'),
1249 ('\?', b'+AFw?'),
1250 ('+?', b'+-?'),
1251 (r'\\?', b'+AFwAXA?'),
1252 (r'\\\?', b'+AFwAXABc?'),
Antoine Pitrou244651a2009-05-04 18:56:13 +00001253 (r'++--', b'+-+---'),
1254 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1255 ('/', b'/'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001256 ]
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001257
Walter Dörwald28256f22003-01-19 16:59:20 +00001258 for (x, y) in utfTests:
1259 self.assertEqual(x.encode('utf-7'), y)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001260
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001261 # Unpaired surrogates are passed through
1262 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1263 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1264 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1265 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1266 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1267 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1268 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1269 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001270
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001271 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1272 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001273
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001274 # Issue #2242: crash on some Windows/MSVC versions
Antoine Pitrou244651a2009-05-04 18:56:13 +00001275 self.assertEqual(b'+\xc1'.decode('utf-7'), '\xc1')
1276
1277 # Direct encoded characters
1278 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1279 # Optional direct characters
1280 set_o = '!"#$%&*;<=>@[]^_`{|}'
1281 for c in set_d:
1282 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1283 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1284 for c in set_o:
1285 self.assertEqual(c.encode('ascii').decode('utf7'), c)
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001286
Walter Dörwald28256f22003-01-19 16:59:20 +00001287 def test_codecs_utf8(self):
Walter Dörwald67e83882007-05-05 12:26:27 +00001288 self.assertEqual(''.encode('utf-8'), b'')
1289 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001290 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1291 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001292 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1293 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001294 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1295 b'\xf0\x90\x80\x82'*10)
Walter Dörwald28256f22003-01-19 16:59:20 +00001296 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001297 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1298 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1299 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1300 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1301 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1302 ' Nunstuck git und'.encode('utf-8'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001303 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1304 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1305 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1306 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1307 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1308 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1309 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1310 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1311 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1312 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
Walter Dörwald28256f22003-01-19 16:59:20 +00001313 )
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001314
Walter Dörwald28256f22003-01-19 16:59:20 +00001315 # UTF-8 specific decoding tests
Walter Dörwald67e83882007-05-05 12:26:27 +00001316 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1317 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1318 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001319
Walter Dörwald28256f22003-01-19 16:59:20 +00001320 # Other possible utf-8 test cases:
1321 # * strict decoding testing for all of the
1322 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001323
Ezio Melotti57221d02010-07-01 07:32:02 +00001324 def test_utf8_decode_valid_sequences(self):
1325 sequences = [
1326 # single byte
1327 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1328 # 2 bytes
1329 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1330 # 3 bytes
1331 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1332 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1333 # 4 bytes
1334 (b'\xF0\x90\x80\x80', '\U00010000'),
1335 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1336 ]
1337 for seq, res in sequences:
1338 self.assertEqual(seq.decode('utf-8'), res)
1339
1340
1341 def test_utf8_decode_invalid_sequences(self):
1342 # continuation bytes in a sequence of 2, 3, or 4 bytes
1343 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
1344 # start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
1345 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
1346 # start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
1347 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1348 invalid_start_bytes = (
1349 continuation_bytes + invalid_2B_seq_start_bytes +
1350 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1351 )
1352
1353 for byte in invalid_start_bytes:
1354 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1355
1356 for sb in invalid_2B_seq_start_bytes:
1357 for cb in continuation_bytes:
1358 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1359
1360 for sb in invalid_4B_seq_start_bytes:
1361 for cb1 in continuation_bytes[:3]:
1362 for cb3 in continuation_bytes[:3]:
1363 self.assertRaises(UnicodeDecodeError,
1364 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1365
1366 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1367 self.assertRaises(UnicodeDecodeError,
1368 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1369 self.assertRaises(UnicodeDecodeError,
1370 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1371 # surrogates
1372 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1373 self.assertRaises(UnicodeDecodeError,
1374 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1375 self.assertRaises(UnicodeDecodeError,
1376 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1377 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1378 self.assertRaises(UnicodeDecodeError,
1379 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1380 self.assertRaises(UnicodeDecodeError,
1381 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1382 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1383 self.assertRaises(UnicodeDecodeError,
1384 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1385 self.assertRaises(UnicodeDecodeError,
1386 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1387
1388 def test_issue8271(self):
1389 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1390 # only the start byte and the continuation byte(s) are now considered
1391 # invalid, instead of the number of bytes specified by the start byte.
1392 # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
1393 # table 3-8, Row 2) for more information about the algorithm used.
1394 FFFD = '\ufffd'
1395 sequences = [
1396 # invalid start bytes
1397 (b'\x80', FFFD), # continuation byte
1398 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1399 (b'\xc0', FFFD),
1400 (b'\xc0\xc0', FFFD*2),
1401 (b'\xc1', FFFD),
1402 (b'\xc1\xc0', FFFD*2),
1403 (b'\xc0\xc1', FFFD*2),
1404 # with start byte of a 2-byte sequence
1405 (b'\xc2', FFFD), # only the start byte
1406 (b'\xc2\xc2', FFFD*2), # 2 start bytes
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001407 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
Ezio Melotti57221d02010-07-01 07:32:02 +00001408 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1409 # with start byte of a 3-byte sequence
1410 (b'\xe1', FFFD), # only the start byte
1411 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1412 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1413 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1414 (b'\xe1\x80', FFFD), # only 1 continuation byte
1415 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1416 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1417 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1418 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1419 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1420 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1421 # with start byte of a 4-byte sequence
1422 (b'\xf1', FFFD), # only the start byte
1423 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1424 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1425 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1426 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1427 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1428 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1429 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1430 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1431 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1432 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1433 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1434 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1435 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1436 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1437 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1438 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1439 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1440 # with invalid start byte of a 4-byte sequence (rfc2279)
1441 (b'\xf5', FFFD), # only the start byte
1442 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1443 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1444 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1445 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1446 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1447 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1448 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1449 # with invalid start byte of a 5-byte sequence (rfc2279)
1450 (b'\xf8', FFFD), # only the start byte
1451 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1452 (b'\xf8\x80', FFFD*2), # only one continuation byte
1453 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1454 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1455 # with invalid start byte of a 6-byte sequence (rfc2279)
1456 (b'\xfc', FFFD), # only the start byte
1457 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1458 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1459 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
1460 # invalid start byte
1461 (b'\xfe', FFFD),
1462 (b'\xfe\x80\x80', FFFD*3),
1463 # other sequences
1464 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
1465 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
1466 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
1467 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
1468 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
1469 ]
1470 for n, (seq, res) in enumerate(sequences):
1471 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
1472 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1473 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
1474 self.assertEqual(seq.decode('utf-8', 'ignore'),
1475 res.replace('\uFFFD', ''))
1476
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001477 def to_bytestring(self, seq):
1478 return bytes(int(c, 16) for c in seq.split())
1479
1480 def assertCorrectUTF8Decoding(self, seq, res, err):
1481 """
1482 Check that an invalid UTF-8 sequence raises an UnicodeDecodeError when
1483 'strict' is used, returns res when 'replace' is used, and that doesn't
1484 return anything when 'ignore' is used.
1485 """
1486 with self.assertRaises(UnicodeDecodeError) as cm:
1487 seq.decode('utf-8')
1488 exc = cm.exception
1489
1490 self.assertIn(err, str(exc))
1491 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1492 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
1493 'aaaa' + res + 'bbbb')
1494 res = res.replace('\ufffd', '')
1495 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
1496 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
1497 'aaaa' + res + 'bbbb')
1498
1499 def test_invalid_start_byte(self):
1500 """
1501 Test that an 'invalid start byte' error is raised when the first byte
1502 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
1503 4-bytes sequence. The invalid start byte is replaced with a single
1504 U+FFFD when errors='replace'.
1505 E.g. <80> is a continuation byte and can appear only after a start byte.
1506 """
1507 FFFD = '\ufffd'
1508 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
1509 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
1510 'invalid start byte')
1511
1512 def test_unexpected_end_of_data(self):
1513 """
1514 Test that an 'unexpected end of data' error is raised when the string
1515 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
1516 enough continuation bytes. The incomplete sequence is replaced with a
1517 single U+FFFD when errors='replace'.
1518 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
1519 sequence, but it's followed by only 2 valid continuation bytes and the
1520 last continuation bytes is missing.
1521 Note: the continuation bytes must be all valid, if one of them is
1522 invalid another error will be raised.
1523 """
1524 sequences = [
1525 'C2', 'DF',
1526 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
1527 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
1528 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
1529 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
1530 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
1531 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
1532 ]
1533 FFFD = '\ufffd'
1534 for seq in sequences:
1535 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), '\ufffd',
1536 'unexpected end of data')
1537
1538 def test_invalid_cb_for_2bytes_seq(self):
1539 """
1540 Test that an 'invalid continuation byte' error is raised when the
1541 continuation byte of a 2-bytes sequence is invalid. The start byte
1542 is replaced by a single U+FFFD and the second byte is handled
1543 separately when errors='replace'.
1544 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
1545 sequence, but 41 is not a valid continuation byte because it's the
1546 ASCII letter 'A'.
1547 """
1548 FFFD = '\ufffd'
1549 FFFDx2 = FFFD * 2
1550 sequences = [
1551 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
1552 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
1553 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
1554 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
1555 ]
1556 for seq, res in sequences:
1557 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1558 'invalid continuation byte')
1559
1560 def test_invalid_cb_for_3bytes_seq(self):
1561 """
1562 Test that an 'invalid continuation byte' error is raised when the
1563 continuation byte(s) of a 3-bytes sequence are invalid. When
1564 errors='replace', if the first continuation byte is valid, the first
1565 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
1566 third byte is handled separately, otherwise only the start byte is
1567 replaced with a U+FFFD and the other continuation bytes are handled
1568 separately.
1569 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1570 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1571 because it's the ASCII letter 'A'.
1572 Note: when the start byte is E0 or ED, the valid ranges for the first
1573 continuation byte are limited to A0..BF and 80..9F respectively.
1574 Python 2 used to consider all the bytes in range 80..BF valid when the
1575 start byte was ED. This is fixed in Python 3.
1576 """
1577 FFFD = '\ufffd'
1578 FFFDx2 = FFFD * 2
1579 sequences = [
1580 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
1581 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
1582 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
1583 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
1584 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
1585 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
1586 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
1587 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
1588 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
1589 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
1590 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
1591 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
1592 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
1593 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
1594 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
1595 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
1596 ('ED 7F', FFFD+'\x7f'),
1597 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
1598 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
1599 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
1600 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
1601 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
1602 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
1603 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
1604 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
1605 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
1606 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
1607 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
1608 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
1609 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
1610 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
1611 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
1612 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
1613 ]
1614 for seq, res in sequences:
1615 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1616 'invalid continuation byte')
1617
1618 def test_invalid_cb_for_4bytes_seq(self):
1619 """
1620 Test that an 'invalid continuation byte' error is raised when the
1621 continuation byte(s) of a 4-bytes sequence are invalid. When
1622 errors='replace',the start byte and all the following valid
1623 continuation bytes are replaced with a single U+FFFD, and all the bytes
1624 starting from the first invalid continuation bytes (included) are
1625 handled separately.
1626 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1627 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1628 because it's the ASCII letter 'A'.
1629 Note: when the start byte is E0 or ED, the valid ranges for the first
1630 continuation byte are limited to A0..BF and 80..9F respectively.
1631 However, when the start byte is ED, Python 2 considers all the bytes
1632 in range 80..BF valid. This is fixed in Python 3.
1633 """
1634 FFFD = '\ufffd'
1635 FFFDx2 = FFFD * 2
1636 sequences = [
1637 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
1638 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
1639 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
1640 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
1641 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
1642 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
1643 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
1644 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
1645 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
1646 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
1647 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
1648 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
1649 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
1650 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
1651 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
1652 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
1653 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
1654 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
1655 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
1656 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
1657 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
1658 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
1659 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
1660 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
1661 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
1662 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
1663 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
1664 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
1665 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
1666 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
1667 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
1668 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
1669 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
1670 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
1671 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
1672 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
1673 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
1674 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
1675 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
1676 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
1677 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
1678 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
1679 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
1680 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
1681 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
1682 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
1683 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
1684 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
1685 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
1686 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
1687 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
1688 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
1689 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
1690 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
1691 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
1692 ]
1693 for seq, res in sequences:
1694 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1695 'invalid continuation byte')
1696
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001697 def test_codecs_idna(self):
1698 # Test whether trailing dot is preserved
Walter Dörwald1324c6f2007-05-11 19:57:05 +00001699 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001700
Walter Dörwald28256f22003-01-19 16:59:20 +00001701 def test_codecs_errors(self):
1702 # Error handling (encoding)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001703 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
1704 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
Walter Dörwald67e83882007-05-05 12:26:27 +00001705 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
1706 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
Benjamin Peterson308d6372009-09-18 21:42:35 +00001707 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
1708 'Andr\202 x'.encode('ascii', errors='replace'))
1709 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
1710 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001711
Walter Dörwald28256f22003-01-19 16:59:20 +00001712 # Error handling (decoding)
Walter Dörwald67e83882007-05-05 12:26:27 +00001713 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
1714 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
1715 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
1716 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001717
Walter Dörwald28256f22003-01-19 16:59:20 +00001718 # Error handling (unknown character names)
Guido van Rossum39478e82007-08-27 17:23:59 +00001719 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
Marc-André Lemburg3688a882002-02-06 18:09:02 +00001720
Walter Dörwald28256f22003-01-19 16:59:20 +00001721 # Error handling (truncated escape sequence)
Guido van Rossum9c627722007-08-27 18:31:48 +00001722 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001723
Guido van Rossum9c627722007-08-27 18:31:48 +00001724 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
1725 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001726 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
1727 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001728
Walter Dörwald28256f22003-01-19 16:59:20 +00001729 # Error handling (wrong arguments)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001730 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001731
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001732 # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001733 self.assertRaises(UnicodeError, float, "\ud800")
1734 self.assertRaises(UnicodeError, float, "\udf00")
1735 self.assertRaises(UnicodeError, complex, "\ud800")
1736 self.assertRaises(UnicodeError, complex, "\udf00")
Guido van Rossum97064862000-04-10 13:52:48 +00001737
Walter Dörwald28256f22003-01-19 16:59:20 +00001738 def test_codecs(self):
1739 # Encoding
Walter Dörwald67e83882007-05-05 12:26:27 +00001740 self.assertEqual('hello'.encode('ascii'), b'hello')
1741 self.assertEqual('hello'.encode('utf-7'), b'hello')
1742 self.assertEqual('hello'.encode('utf-8'), b'hello')
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001743 self.assertEqual('hello'.encode('utf-8'), b'hello')
Walter Dörwald67e83882007-05-05 12:26:27 +00001744 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
1745 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
1746 self.assertEqual('hello'.encode('latin-1'), b'hello')
Guido van Rossum97064862000-04-10 13:52:48 +00001747
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001748 # Default encoding is utf-8
1749 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
1750
Walter Dörwald28256f22003-01-19 16:59:20 +00001751 # Roundtrip safety for BMP (just the first 1024 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001752 for c in range(1024):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001753 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001754 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
1755 'utf-16-be', 'raw_unicode_escape',
1756 'unicode_escape', 'unicode_internal'):
Victor Stinner040e16e2011-11-15 22:44:05 +01001757 with warnings.catch_warnings():
1758 # unicode-internal has been deprecated
1759 warnings.simplefilter("ignore", DeprecationWarning)
1760
1761 self.assertEqual(str(u.encode(encoding),encoding), u)
Martin v. Löwis047c05e2002-03-21 08:55:28 +00001762
Walter Dörwald28256f22003-01-19 16:59:20 +00001763 # Roundtrip safety for BMP (just the first 256 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001764 for c in range(256):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001765 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001766 for encoding in ('latin-1',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001767 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001768
Walter Dörwald28256f22003-01-19 16:59:20 +00001769 # Roundtrip safety for BMP (just the first 128 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001770 for c in range(128):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001771 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001772 for encoding in ('ascii',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001773 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001774
Walter Dörwald28256f22003-01-19 16:59:20 +00001775 # Roundtrip safety for non-BMP (just a few chars)
Victor Stinner040e16e2011-11-15 22:44:05 +01001776 with warnings.catch_warnings():
1777 # unicode-internal has been deprecated
1778 warnings.simplefilter("ignore", DeprecationWarning)
1779
1780 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
1781 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
1782 'raw_unicode_escape',
1783 'unicode_escape', 'unicode_internal'):
1784 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001785
Antoine Pitrou51f66482011-11-11 13:35:44 +01001786 # UTF-8 must be roundtrip safe for all code points
1787 # (except surrogates, which are forbidden).
1788 u = ''.join(map(chr, list(range(0, 0xd800)) +
Ezio Melotti40dc9192011-11-11 17:00:46 +02001789 list(range(0xe000, 0x110000))))
Walter Dörwald28256f22003-01-19 16:59:20 +00001790 for encoding in ('utf-8',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001791 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001792
Walter Dörwald28256f22003-01-19 16:59:20 +00001793 def test_codecs_charmap(self):
1794 # 0-127
Guido van Rossum805365e2007-05-07 22:24:25 +00001795 s = bytes(range(128))
Walter Dörwald28256f22003-01-19 16:59:20 +00001796 for encoding in (
1797 'cp037', 'cp1026',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001798 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
1799 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Walter Dörwald28256f22003-01-19 16:59:20 +00001800 'cp863', 'cp865', 'cp866',
1801 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
1802 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
1803 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
1804 'mac_cyrillic', 'mac_latin2',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00001805
Walter Dörwald28256f22003-01-19 16:59:20 +00001806 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
1807 'cp1256', 'cp1257', 'cp1258',
1808 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00001809
Walter Dörwald28256f22003-01-19 16:59:20 +00001810 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
1811 'cp1006', 'iso8859_8',
Guido van Rossum9e896b32000-04-05 20:11:21 +00001812
Walter Dörwald28256f22003-01-19 16:59:20 +00001813 ### These have undefined mappings:
1814 #'cp424',
Guido van Rossum9e896b32000-04-05 20:11:21 +00001815
Walter Dörwald28256f22003-01-19 16:59:20 +00001816 ### These fail the round-trip:
1817 #'cp875'
Guido van Rossum9e896b32000-04-05 20:11:21 +00001818
Walter Dörwald28256f22003-01-19 16:59:20 +00001819 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001820 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001821
Walter Dörwald28256f22003-01-19 16:59:20 +00001822 # 128-255
Guido van Rossum805365e2007-05-07 22:24:25 +00001823 s = bytes(range(128, 256))
Walter Dörwald28256f22003-01-19 16:59:20 +00001824 for encoding in (
1825 'cp037', 'cp1026',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001826 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
1827 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Walter Dörwald28256f22003-01-19 16:59:20 +00001828 'cp863', 'cp865', 'cp866',
1829 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
1830 'iso8859_2', 'iso8859_4', 'iso8859_5',
1831 'iso8859_9', 'koi8_r', 'latin_1',
1832 'mac_cyrillic', 'mac_latin2',
Fred Drake004d5e62000-10-23 17:22:08 +00001833
Walter Dörwald28256f22003-01-19 16:59:20 +00001834 ### These have undefined mappings:
1835 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
1836 #'cp1256', 'cp1257', 'cp1258',
1837 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
1838 #'iso8859_3', 'iso8859_6', 'iso8859_7',
1839 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
Fred Drake004d5e62000-10-23 17:22:08 +00001840
Walter Dörwald28256f22003-01-19 16:59:20 +00001841 ### These fail the round-trip:
1842 #'cp1006', 'cp875', 'iso8859_8',
Tim Peters2f228e72001-05-13 00:19:31 +00001843
Walter Dörwald28256f22003-01-19 16:59:20 +00001844 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001845 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001846
Walter Dörwald28256f22003-01-19 16:59:20 +00001847 def test_concatenation(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001848 self.assertEqual(("abc" "def"), "abcdef")
1849 self.assertEqual(("abc" "def"), "abcdef")
1850 self.assertEqual(("abc" "def"), "abcdef")
1851 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
1852 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
Fred Drake004d5e62000-10-23 17:22:08 +00001853
Walter Dörwald28256f22003-01-19 16:59:20 +00001854 def test_printing(self):
1855 class BitBucket:
1856 def write(self, text):
1857 pass
Fred Drake004d5e62000-10-23 17:22:08 +00001858
Walter Dörwald28256f22003-01-19 16:59:20 +00001859 out = BitBucket()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001860 print('abc', file=out)
1861 print('abc', 'def', file=out)
1862 print('abc', 'def', file=out)
1863 print('abc', 'def', file=out)
1864 print('abc\n', file=out)
1865 print('abc\n', end=' ', file=out)
1866 print('abc\n', end=' ', file=out)
1867 print('def\n', file=out)
1868 print('def\n', file=out)
Fred Drake004d5e62000-10-23 17:22:08 +00001869
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00001870 def test_ucs4(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001871 x = '\U00100000'
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00001872 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
1873 self.assertEqual(x, y)
1874
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001875 y = br'\U00100000'
1876 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
1877 self.assertEqual(x, y)
1878 y = br'\U00010000'
1879 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
1880 self.assertEqual(x, y)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001881
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001882 try:
1883 br'\U11111111'.decode("raw-unicode-escape")
1884 except UnicodeDecodeError as e:
1885 self.assertEqual(e.start, 0)
1886 self.assertEqual(e.end, 10)
1887 else:
1888 self.fail("Should have raised UnicodeDecodeError")
Christian Heimesfe337bf2008-03-23 21:54:12 +00001889
Brett Cannonc3647ac2005-04-26 03:45:26 +00001890 def test_conversion(self):
1891 # Make sure __unicode__() works properly
1892 class Foo0:
1893 def __str__(self):
1894 return "foo"
1895
1896 class Foo1:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001897 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001898 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001899
1900 class Foo2(object):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001901 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001902 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001903
1904 class Foo3(object):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001905 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001906 return "foo"
1907
1908 class Foo4(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001909 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001910 return "foo"
1911
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001912 class Foo5(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001913 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001914 return "foo"
1915
1916 class Foo6(str):
1917 def __str__(self):
1918 return "foos"
1919
Guido van Rossum98297ee2007-11-06 21:34:58 +00001920 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001921 return "foou"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001922
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001923 class Foo7(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001924 def __str__(self):
1925 return "foos"
Guido van Rossum98297ee2007-11-06 21:34:58 +00001926 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001927 return "foou"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001928
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001929 class Foo8(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001930 def __new__(cls, content=""):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001931 return str.__new__(cls, 2*content)
Guido van Rossum98297ee2007-11-06 21:34:58 +00001932 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001933 return self
1934
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001935 class Foo9(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001936 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00001937 return "not unicode"
1938
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001939 self.assertEqual(str(Foo0()), "foo")
1940 self.assertEqual(str(Foo1()), "foo")
1941 self.assertEqual(str(Foo2()), "foo")
1942 self.assertEqual(str(Foo3()), "foo")
1943 self.assertEqual(str(Foo4("bar")), "foo")
1944 self.assertEqual(str(Foo5("bar")), "foo")
1945 self.assertEqual(str(Foo6("bar")), "foou")
1946 self.assertEqual(str(Foo7("bar")), "foou")
1947 self.assertEqual(str(Foo8("foo")), "foofoo")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001948 self.assertEqual(str(Foo9("foo")), "not unicode")
Brett Cannonc3647ac2005-04-26 03:45:26 +00001949
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001950 def test_unicode_repr(self):
1951 class s1:
1952 def __repr__(self):
1953 return '\\n'
1954
1955 class s2:
1956 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001957 return '\\n'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001958
1959 self.assertEqual(repr(s1()), '\\n')
1960 self.assertEqual(repr(s2()), '\\n')
1961
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00001962 def test_printable_repr(self):
1963 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
Martin v. Löwisbaecd722010-10-11 22:42:28 +00001964 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00001965
Zachary Ware9fe6d862013-12-08 00:20:35 -06001966 # This test only affects 32-bit platforms because expandtabs can only take
1967 # an int as the max value, not a 64-bit C long. If expandtabs is changed
1968 # to take a 64-bit long, this test should apply to all platforms.
1969 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
1970 'only applies to 32-bit platforms')
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001971 def test_expandtabs_overflows_gracefully(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +00001972 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001973
Victor Stinner1d972ad2011-10-07 13:31:46 +02001974 @support.cpython_only
Antoine Pitroue19aa382011-10-04 16:04:01 +02001975 def test_expandtabs_optimization(self):
1976 s = 'abc'
1977 self.assertIs(s.expandtabs(), s)
1978
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00001979 def test_raiseMemError(self):
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001980 if struct.calcsize('P') == 8:
1981 # 64 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02001982 ascii_struct_size = 48
1983 compact_struct_size = 72
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001984 else:
1985 # 32 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02001986 ascii_struct_size = 24
1987 compact_struct_size = 36
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02001988
1989 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
1990 code = ord(char)
1991 if code < 0x100:
1992 char_size = 1 # sizeof(Py_UCS1)
1993 struct_size = ascii_struct_size
1994 elif code < 0x10000:
1995 char_size = 2 # sizeof(Py_UCS2)
1996 struct_size = compact_struct_size
1997 else:
1998 char_size = 4 # sizeof(Py_UCS4)
1999 struct_size = compact_struct_size
2000 # Note: sys.maxsize is half of the actual max allocation because of
Martin v. Löwis287eca62011-09-28 10:03:28 +02002001 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2002 # be allocatable, given enough memory.
2003 maxlen = ((sys.maxsize - struct_size) // char_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002004 alloc = lambda: char * maxlen
2005 self.assertRaises(MemoryError, alloc)
2006 self.assertRaises(MemoryError, alloc)
Antoine Pitrou3db3e872008-08-17 17:06:51 +00002007
Victor Stinner808fc0a2010-03-22 12:50:40 +00002008 def test_format_subclass(self):
2009 class S(str):
2010 def __str__(self):
2011 return '__str__ overridden'
2012 s = S('xxx')
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002013 self.assertEqual("%s" % s, '__str__ overridden')
2014 self.assertEqual("{}".format(s), '__str__ overridden')
Victor Stinner808fc0a2010-03-22 12:50:40 +00002015
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002016 # Test PyUnicode_FromFormat()
Victor Stinner1205f272010-09-11 00:54:47 +00002017 def test_from_format(self):
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002018 support.import_module('ctypes')
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002019 from ctypes import (
2020 pythonapi, py_object, sizeof,
Victor Stinner6d970f42011-03-02 00:04:25 +00002021 c_int, c_long, c_longlong, c_ssize_t,
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002022 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002023 name = "PyUnicode_FromFormat"
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002024 _PyUnicode_FromFormat = getattr(pythonapi, name)
2025 _PyUnicode_FromFormat.restype = py_object
2026
2027 def PyUnicode_FromFormat(format, *args):
2028 cargs = tuple(
2029 py_object(arg) if isinstance(arg, str) else arg
2030 for arg in args)
2031 return _PyUnicode_FromFormat(format, *cargs)
Victor Stinner1205f272010-09-11 00:54:47 +00002032
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002033 def check_format(expected, format, *args):
2034 text = PyUnicode_FromFormat(format, *args)
2035 self.assertEqual(expected, text)
2036
Victor Stinner1205f272010-09-11 00:54:47 +00002037 # ascii format, non-ascii argument
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002038 check_format('ascii\x7f=unicode\xe9',
2039 b'ascii\x7f=%U', 'unicode\xe9')
Victor Stinner1205f272010-09-11 00:54:47 +00002040
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002041 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
2042 # raises an error
Ezio Melottied3a7d22010-12-01 02:32:32 +00002043 self.assertRaisesRegex(ValueError,
Victor Stinner1205f272010-09-11 00:54:47 +00002044 '^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
Victor Stinner4c7db312010-09-12 07:51:18 +00002045 'string, got a non-ASCII byte: 0xe9$',
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002046 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002047
Victor Stinner96865452011-03-01 23:44:09 +00002048 # test "%c"
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002049 check_format('\uabcd',
2050 b'%c', c_int(0xabcd))
2051 check_format('\U0010ffff',
2052 b'%c', c_int(0x10ffff))
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002053 with self.assertRaises(OverflowError):
2054 PyUnicode_FromFormat(b'%c', c_int(0x110000))
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +03002055 # Issue #18183
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002056 check_format('\U00010000\U00100000',
2057 b'%c%c', c_int(0x10000), c_int(0x100000))
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002058
Victor Stinner96865452011-03-01 23:44:09 +00002059 # test "%"
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002060 check_format('%',
2061 b'%')
2062 check_format('%',
2063 b'%%')
2064 check_format('%s',
2065 b'%%s')
2066 check_format('[%]',
2067 b'[%%]')
2068 check_format('%abc',
2069 b'%%%s', b'abc')
2070
2071 # test %S
2072 check_format("repr=\u20acABC",
2073 b'repr=%S', '\u20acABC')
2074
2075 # test %R
2076 check_format("repr='\u20acABC'",
2077 b'repr=%R', '\u20acABC')
Victor Stinner96865452011-03-01 23:44:09 +00002078
Victor Stinner6d970f42011-03-02 00:04:25 +00002079 # test integer formats (%i, %d, %u)
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002080 check_format('010',
2081 b'%03i', c_int(10))
2082 check_format('0010',
2083 b'%0.4i', c_int(10))
2084 check_format('-123',
2085 b'%i', c_int(-123))
2086 check_format('-123',
2087 b'%li', c_long(-123))
2088 check_format('-123',
2089 b'%lli', c_longlong(-123))
2090 check_format('-123',
2091 b'%zi', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002092
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002093 check_format('-123',
2094 b'%d', c_int(-123))
2095 check_format('-123',
2096 b'%ld', c_long(-123))
2097 check_format('-123',
2098 b'%lld', c_longlong(-123))
2099 check_format('-123',
2100 b'%zd', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002101
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002102 check_format('123',
2103 b'%u', c_uint(123))
2104 check_format('123',
2105 b'%lu', c_ulong(123))
2106 check_format('123',
2107 b'%llu', c_ulonglong(123))
2108 check_format('123',
2109 b'%zu', c_size_t(123))
2110
2111 # test long output
2112 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
2113 max_longlong = -min_longlong - 1
2114 check_format(str(min_longlong),
2115 b'%lld', c_longlong(min_longlong))
2116 check_format(str(max_longlong),
2117 b'%lld', c_longlong(max_longlong))
2118 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
2119 check_format(str(max_ulonglong),
2120 b'%llu', c_ulonglong(max_ulonglong))
2121 PyUnicode_FromFormat(b'%p', c_void_p(-1))
2122
2123 # test padding (width and/or precision)
2124 check_format('123'.rjust(10, '0'),
2125 b'%010i', c_int(123))
2126 check_format('123'.rjust(100),
2127 b'%100i', c_int(123))
2128 check_format('123'.rjust(300, '0'),
2129 b'%.300i', c_int(123))
2130 check_format('123'.rjust(80, '0').rjust(100),
2131 b'%100.80i', c_int(123))
2132
2133 check_format('123'.rjust(10, '0'),
2134 b'%010u', c_uint(123))
2135 check_format('123'.rjust(100),
2136 b'%100u', c_uint(123))
2137 check_format('123'.rjust(300, '0'),
2138 b'%.300u', c_uint(123))
2139 check_format('123'.rjust(80, '0').rjust(100),
2140 b'%100.80u', c_uint(123))
2141
2142 check_format('123'.rjust(10, '0'),
2143 b'%010x', c_int(0x123))
2144 check_format('123'.rjust(100),
2145 b'%100x', c_int(0x123))
2146 check_format('123'.rjust(300, '0'),
2147 b'%.300x', c_int(0x123))
2148 check_format('123'.rjust(80, '0').rjust(100),
2149 b'%100.80x', c_int(0x123))
Victor Stinner6d970f42011-03-02 00:04:25 +00002150
2151 # test %A
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002152 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
2153 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
Victor Stinner9a909002010-10-18 20:59:24 +00002154
Victor Stinner6d970f42011-03-02 00:04:25 +00002155 # test %V
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002156 check_format('repr=abc',
2157 b'repr=%V', 'abc', b'xyz')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002158
2159 # Test string decode from parameter of %s using utf-8.
2160 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
2161 # '\u4eba\u6c11'
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002162 check_format('repr=\u4eba\u6c11',
2163 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002164
2165 #Test replace error handler.
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002166 check_format('repr=abc\ufffd',
2167 b'repr=%V', None, b'abc\xff')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002168
Victor Stinner6d970f42011-03-02 00:04:25 +00002169 # not supported: copy the raw format string. these tests are just here
2170 # to check for crashs and should not be considered as specifications
Serhiy Storchaka4dbc3052015-01-27 22:18:46 +02002171 check_format('%s',
2172 b'%1%s', b'abc')
2173 check_format('%1abc',
2174 b'%1abc')
2175 check_format('%+i',
2176 b'%+i', c_int(10))
2177 check_format('%.%s',
2178 b'%.%s', b'abc')
Victor Stinner6d970f42011-03-02 00:04:25 +00002179
Victor Stinner1c24bd02010-10-02 11:03:13 +00002180 # Test PyUnicode_AsWideChar()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002181 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002182 def test_aswidechar(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002183 from _testcapi import unicode_aswidechar
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002184 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002185 from ctypes import c_wchar, sizeof
2186
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002187 wchar, size = unicode_aswidechar('abcdef', 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002188 self.assertEqual(size, 2)
2189 self.assertEqual(wchar, 'ab')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002190
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002191 wchar, size = unicode_aswidechar('abc', 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002192 self.assertEqual(size, 3)
2193 self.assertEqual(wchar, 'abc')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002194
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002195 wchar, size = unicode_aswidechar('abc', 4)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002196 self.assertEqual(size, 3)
2197 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002198
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002199 wchar, size = unicode_aswidechar('abc', 10)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002200 self.assertEqual(size, 3)
2201 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002202
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002203 wchar, size = unicode_aswidechar('abc\0def', 20)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002204 self.assertEqual(size, 7)
2205 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002206
Victor Stinner5593d8a2010-10-02 11:11:27 +00002207 nonbmp = chr(0x10ffff)
2208 if sizeof(c_wchar) == 2:
2209 buflen = 3
2210 nchar = 2
2211 else: # sizeof(c_wchar) == 4
2212 buflen = 2
2213 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002214 wchar, size = unicode_aswidechar(nonbmp, buflen)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002215 self.assertEqual(size, nchar)
2216 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002217
Victor Stinner1c24bd02010-10-02 11:03:13 +00002218 # Test PyUnicode_AsWideCharString()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002219 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002220 def test_aswidecharstring(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002221 from _testcapi import unicode_aswidecharstring
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002222 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002223 from ctypes import c_wchar, sizeof
2224
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002225 wchar, size = unicode_aswidecharstring('abc')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002226 self.assertEqual(size, 3)
2227 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002228
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002229 wchar, size = unicode_aswidecharstring('abc\0def')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002230 self.assertEqual(size, 7)
2231 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002232
Victor Stinner5593d8a2010-10-02 11:11:27 +00002233 nonbmp = chr(0x10ffff)
2234 if sizeof(c_wchar) == 2:
2235 nchar = 2
2236 else: # sizeof(c_wchar) == 4
2237 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002238 wchar, size = unicode_aswidecharstring(nonbmp)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002239 self.assertEqual(size, nchar)
2240 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002241
Benjamin Peterson811c2f12011-09-30 21:31:21 -04002242 def test_subclass_add(self):
2243 class S(str):
2244 def __add__(self, o):
2245 return "3"
2246 self.assertEqual(S("4") + S("5"), "3")
2247 class S(str):
2248 def __iadd__(self, o):
2249 return "3"
2250 s = S("1")
2251 s += "4"
2252 self.assertEqual(s, "3")
2253
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002254 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002255 def test_encode_decimal(self):
2256 from _testcapi import unicode_encodedecimal
2257 self.assertEqual(unicode_encodedecimal('123'),
2258 b'123')
2259 self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
2260 b'3.14')
2261 self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2262 b' 3.14 ')
2263 self.assertRaises(UnicodeEncodeError,
2264 unicode_encodedecimal, "123\u20ac", "strict")
Victor Stinner6345be92011-11-25 20:09:01 +01002265 self.assertRaisesRegex(
2266 ValueError,
2267 "^'decimal' codec can't encode character",
2268 unicode_encodedecimal, "123\u20ac", "replace")
Victor Stinner42bf7752011-11-21 22:52:58 +01002269
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002270 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002271 def test_transform_decimal(self):
2272 from _testcapi import unicode_transformdecimaltoascii as transform_decimal
2273 self.assertEqual(transform_decimal('123'),
2274 '123')
2275 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
2276 '3.14')
2277 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2278 "\N{EM SPACE}3.14\N{EN SPACE}")
2279 self.assertEqual(transform_decimal('123\u20ac'),
2280 '123\u20ac')
2281
Victor Stinnerc814a382011-11-22 01:06:15 +01002282 def test_getnewargs(self):
2283 text = 'abc'
2284 args = text.__getnewargs__()
2285 self.assertIsNot(args[0], text)
2286 self.assertEqual(args[0], text)
2287 self.assertEqual(len(args), 1)
2288
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002289 def test_resize(self):
2290 for length in range(1, 100, 7):
2291 # generate a fresh string (refcount=1)
2292 text = 'a' * length + 'b'
2293
Ezio Melotti51e243f2013-02-20 23:56:01 +02002294 with support.check_warnings(('unicode_internal codec has been '
2295 'deprecated', DeprecationWarning)):
2296 # fill wstr internal field
2297 abc = text.encode('unicode_internal')
2298 self.assertEqual(abc.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002299
Ezio Melotti51e243f2013-02-20 23:56:01 +02002300 # resize text: wstr field must be cleared and then recomputed
2301 text += 'c'
2302 abcdef = text.encode('unicode_internal')
2303 self.assertNotEqual(abc, abcdef)
2304 self.assertEqual(abcdef.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002305
Victor Stinner1c24bd02010-10-02 11:03:13 +00002306
Eric Smitha1eac722011-01-29 11:15:35 +00002307class StringModuleTest(unittest.TestCase):
2308 def test_formatter_parser(self):
2309 def parse(format):
2310 return list(_string.formatter_parser(format))
2311
2312 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2313 self.assertEqual(formatter, [
2314 ('prefix ', '2', '', 's'),
2315 ('xxx', '0', '^+10.3f', None),
2316 ('', 'obj.attr', '', 's'),
2317 (' ', 'z[0]', '10', 's'),
2318 ])
2319
2320 formatter = parse("prefix {} suffix")
2321 self.assertEqual(formatter, [
2322 ('prefix ', '', '', None),
2323 (' suffix', None, None, None),
2324 ])
2325
2326 formatter = parse("str")
2327 self.assertEqual(formatter, [
2328 ('str', None, None, None),
2329 ])
2330
2331 formatter = parse("")
2332 self.assertEqual(formatter, [])
2333
2334 formatter = parse("{0}")
2335 self.assertEqual(formatter, [
2336 ('', '0', '', None),
2337 ])
2338
2339 self.assertRaises(TypeError, _string.formatter_parser, 1)
2340
2341 def test_formatter_field_name_split(self):
2342 def split(name):
2343 items = list(_string.formatter_field_name_split(name))
2344 items[1] = list(items[1])
2345 return items
2346 self.assertEqual(split("obj"), ["obj", []])
2347 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
2348 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
2349 self.assertEqual(split("obj.arg[key1][key2]"), [
2350 "obj",
2351 [(True, 'arg'),
2352 (False, 'key1'),
2353 (False, 'key2'),
2354 ]])
2355 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
2356
2357
Walter Dörwald28256f22003-01-19 16:59:20 +00002358if __name__ == "__main__":
Ezio Melotti0dceb562013-01-10 07:43:26 +02002359 unittest.main()