Debian Codegraph @

lib-python/3/test/test_unicode.py

raw symbols SCIP
1 """ Test script for the Unicode implementation.
2
3 Written by Marc-Andre Lemburg ([email protected]).
4
5 (c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
6
7 """
8 import _string
9 import codecs
10 import itertools
11 import operator
12 import pickle
13 import struct
14 import sys
15 import textwrap
16 import unicodedata
17 import unittest
18 import warnings
19 from test.support import warnings_helper
20 from test import support, string_tests
21 from test.support.script_helper import assert_python_failure
22
23 try:
24 import _testcapi
25 except ImportError:
26 _testcapi = None
27
28 # Error handling (bad decoder return)
29 def search_function(encoding):
30 def decode1(input, errors="strict"):
31 return 42 # not a tuple
32 def encode1(input, errors="strict"):
33 return 42 # not a tuple
34 def encode2(input, errors="strict"):
35 return (42, 42) # no unicode
36 def decode2(input, errors="strict"):
37 return (42, 42) # no unicode
38 if encoding=="test.unicode1":
39 return (encode1, decode1, None, None)
40 elif encoding=="test.unicode2":
41 return (encode2, decode2, None, None)
42 else:
43 return None
44
45 def duplicate_string(text):
46 """
47 Try to get a fresh clone of the specified text:
48 new object with a reference count of 1.
49
50 This is a best-effort: latin1 single letters and the empty
51 string ('') are singletons and cannot be cloned.
52 """
53 return text.encode().decode()
54
55 class StrSubclass(str):
56 pass
57
58 class OtherStrSubclass(str):
59 pass
60
61 class WithStr:
62 def __init__(self, value):
63 self.value = value
64 def __str__(self):
65 return self.value
66
67 class WithRepr:
68 def __init__(self, value):
69 self.value = value
70 def __repr__(self):
71 return self.value
72
73 class UnicodeTest(string_tests.CommonTest,
74 string_tests.MixinStrUnicodeUserStringTest,
75 string_tests.MixinStrUnicodeTest,
76 unittest.TestCase):
77
78 type2test = str
79
80 def setUp(self):
81 codecs.register(search_function)
82 self.addCleanup(codecs.unregister, search_function)
83
84 def checkequalnofix(self, result, object, methodname, *args):
85 method = getattr(object, methodname)
86 realresult = method(*args)
87 self.assertEqual(realresult, result)
88 self.assertTrue(type(realresult) is type(result))
89
90 # if the original is returned make sure that
91 # this doesn't happen with subclasses
92 if realresult is object:
93 class usub(str):
94 def __repr__(self):
95 return 'usub(%r)' % str.__repr__(self)
96 object = usub(object)
97 method = getattr(object, methodname)
98 realresult = method(*args)
99 self.assertEqual(realresult, result)
100 self.assertTrue(object is not realresult)
101
102 def assertTypedEqual(self, actual, expected):
103 self.assertIs(type(actual), type(expected))
104 self.assertEqual(actual, expected)
105
106 def test_literals(self):
107 self.assertEqual('\xff', '\u00ff')
108 self.assertEqual('\uffff', '\U0000ffff')
109 self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
110 self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
111 self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
112 # raw strings should not have unicode escapes
113 self.assertNotEqual(r"\u0020", " ")
114
115 def test_ascii(self):
116 if not sys.platform.startswith('java'):
117 # Test basic sanity of repr()
118 self.assertEqual(ascii('abc'), "'abc'")
119 self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
120 self.assertEqual(ascii('ab\\'), "'ab\\\\'")
121 self.assertEqual(ascii('\\c'), "'\\\\c'")
122 self.assertEqual(ascii('\\'), "'\\\\'")
123 self.assertEqual(ascii('\n'), "'\\n'")
124 self.assertEqual(ascii('\r'), "'\\r'")
125 self.assertEqual(ascii('\t'), "'\\t'")
126 self.assertEqual(ascii('\b'), "'\\x08'")
127 self.assertEqual(ascii("'\""), """'\\'"'""")
128 self.assertEqual(ascii("'\""), """'\\'"'""")
129 self.assertEqual(ascii("'"), '''"'"''')
130 self.assertEqual(ascii('"'), """'"'""")
131 latin1repr = (
132 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
133 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
134 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
135 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
136 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
137 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
138 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
139 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
140 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
141 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
142 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
143 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
144 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
145 "\\xfe\\xff'")
146 testrepr = ascii(''.join(map(chr, range(256))))
147 self.assertEqual(testrepr, latin1repr)
148 # Test ascii works on wide unicode escapes without overflow.
149 self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
150 ascii("\U00010000" * 39 + "\uffff" * 4096))
151
152 self.assertTypedEqual(ascii('\U0001f40d'), r"'\U0001f40d'")
153 self.assertTypedEqual(ascii(StrSubclass('abc')), "'abc'")
154 self.assertTypedEqual(ascii(WithRepr('<abc>')), '<abc>')
155 self.assertTypedEqual(ascii(WithRepr(StrSubclass('<abc>'))), StrSubclass('<abc>'))
156 self.assertTypedEqual(ascii(WithRepr('<\U0001f40d>')), r'<\U0001f40d>')
157 self.assertTypedEqual(ascii(WithRepr(StrSubclass('<\U0001f40d>'))), r'<\U0001f40d>')
158 self.assertRaises(TypeError, ascii, WithRepr(b'byte-repr'))
159
160 def test_repr(self):
161 if not sys.platform.startswith('java'):
162 # Test basic sanity of repr()
163 self.assertEqual(repr('abc'), "'abc'")
164 self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
165 self.assertEqual(repr('ab\\'), "'ab\\\\'")
166 self.assertEqual(repr('\\c'), "'\\\\c'")
167 self.assertEqual(repr('\\'), "'\\\\'")
168 self.assertEqual(repr('\n'), "'\\n'")
169 self.assertEqual(repr('\r'), "'\\r'")
170 self.assertEqual(repr('\t'), "'\\t'")
171 self.assertEqual(repr('\b'), "'\\x08'")
172 self.assertEqual(repr("'\""), """'\\'"'""")
173 self.assertEqual(repr("'\""), """'\\'"'""")
174 self.assertEqual(repr("'"), '''"'"''')
175 self.assertEqual(repr('"'), """'"'""")
176 latin1repr = (
177 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
178 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
179 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
180 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
181 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
182 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
183 "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
184 "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
185 "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
186 "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
187 "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
188 "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
189 "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
190 "\xfe\xff'")
191 testrepr = repr(''.join(map(chr, range(256))))
192 self.assertEqual(testrepr, latin1repr)
193 # Test repr works on wide unicode escapes without overflow.
194 self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
195 repr("\U00010000" * 39 + "\uffff" * 4096))
196
197 self.assertTypedEqual(repr('\U0001f40d'), "'\U0001f40d'")
198 self.assertTypedEqual(repr(StrSubclass('abc')), "'abc'")
199 self.assertTypedEqual(repr(WithRepr('<abc>')), '<abc>')
200 self.assertTypedEqual(repr(WithRepr(StrSubclass('<abc>'))), StrSubclass('<abc>'))
201 self.assertTypedEqual(repr(WithRepr('<\U0001f40d>')), '<\U0001f40d>')
202 self.assertTypedEqual(repr(WithRepr(StrSubclass('<\U0001f40d>'))), StrSubclass('<\U0001f40d>'))
203 self.assertRaises(TypeError, repr, WithRepr(b'byte-repr'))
204
205 def test_iterators(self):
206 # Make sure unicode objects have an __iter__ method
207 it = "\u1111\u2222\u3333".__iter__()
208 self.assertEqual(next(it), "\u1111")
209 self.assertEqual(next(it), "\u2222")
210 self.assertEqual(next(it), "\u3333")
211 self.assertRaises(StopIteration, next, it)
212
213 def test_iterators_invocation(self):
214 cases = [type(iter('abc')), type(iter('🚀'))]
215 for cls in cases:
216 with self.subTest(cls=cls):
217 self.assertRaises(TypeError, cls)
218
219 def test_iteration(self):
220 cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
221 for case in cases:
222 with self.subTest(string=case):
223 self.assertEqual(case, "".join(iter(case)))
224
225 def test_exhausted_iterator(self):
226 cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
227 for case in cases:
228 with self.subTest(case=case):
229 iterator = iter(case)
230 tuple(iterator)
231 self.assertRaises(StopIteration, next, iterator)
232
233 def test_pickle_iterator(self):
234 cases = ['abc', '🚀🚀🚀', "\u1111\u2222\u3333"]
235 for case in cases:
236 with self.subTest(case=case):
237 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
238 it = iter(case)
239 with self.subTest(proto=proto):
240 pickled = "".join(pickle.loads(pickle.dumps(it, proto)))
241 self.assertEqual(case, pickled)
242
243 def test_count(self):
244 string_tests.CommonTest.test_count(self)
245 # check mixed argument types
246 self.checkequalnofix(3, 'aaa', 'count', 'a')
247 self.checkequalnofix(0, 'aaa', 'count', 'b')
248 self.checkequalnofix(3, 'aaa', 'count', 'a')
249 self.checkequalnofix(0, 'aaa', 'count', 'b')
250 self.checkequalnofix(0, 'aaa', 'count', 'b')
251 self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
252 self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
253 self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
254 self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
255 # test mixed kinds
256 self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
257 self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
258 self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
259 self.checkequal(0, 'a' * 10, 'count', '\u0102')
260 self.checkequal(0, 'a' * 10, 'count', '\U00100304')
261 self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
262 self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
263 self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
264 self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
265 self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
266 self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
267 self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
268
269 def test_find(self):
270 string_tests.CommonTest.test_find(self)
271 # test implementation details of the memchr fast path
272 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
273 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
274 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
275 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
276 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
277 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
278 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
279 # check mixed argument types
280 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
281 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
282 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
283
284 # test utf-8 non-ascii char
285 self.checkequal(0, 'тест', 'find', 'т')
286 self.checkequal(3, 'тест', 'find', 'т', 1)
287 self.checkequal(-1, 'тест', 'find', 'т', 1, 3)
288 self.checkequal(-1, 'тест', 'find', 'e') # english `e`
289 # test utf-8 non-ascii slice
290 self.checkequal(1, 'тест тест', 'find', 'ес')
291 self.checkequal(1, 'тест тест', 'find', 'ес', 1)
292 self.checkequal(1, 'тест тест', 'find', 'ес', 1, 3)
293 self.checkequal(6, 'тест тест', 'find', 'ес', 2)
294 self.checkequal(-1, 'тест тест', 'find', 'ес', 6, 7)
295 self.checkequal(-1, 'тест тест', 'find', 'ес', 7)
296 self.checkequal(-1, 'тест тест', 'find', 'ec') # english `ec`
297
298 self.assertRaises(TypeError, 'hello'.find)
299 self.assertRaises(TypeError, 'hello'.find, 42)
300 # test mixed kinds
301 self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
302 self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
303 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
304 self.checkequal(-1, 'a' * 100, 'find', '\u0102')
305 self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
306 self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
307 self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
308 self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
309 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
310 self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
311 self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
312 self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
313
314 def test_rfind(self):
315 string_tests.CommonTest.test_rfind(self)
316 # test implementation details of the memrchr fast path
317 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
318 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
319 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
320 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
321 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
322 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
323 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
324 # check mixed argument types
325 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
326 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
327 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
328 # test utf-8 non-ascii char
329 self.checkequal(1, 'тест', 'rfind', 'е')
330 self.checkequal(1, 'тест', 'rfind', 'е', 1)
331 self.checkequal(-1, 'тест', 'rfind', 'е', 2)
332 self.checkequal(-1, 'тест', 'rfind', 'e') # english `e`
333 # test utf-8 non-ascii slice
334 self.checkequal(6, 'тест тест', 'rfind', 'ес')
335 self.checkequal(6, 'тест тест', 'rfind', 'ес', 1)
336 self.checkequal(1, 'тест тест', 'rfind', 'ес', 1, 3)
337 self.checkequal(6, 'тест тест', 'rfind', 'ес', 2)
338 self.checkequal(-1, 'тест тест', 'rfind', 'ес', 6, 7)
339 self.checkequal(-1, 'тест тест', 'rfind', 'ес', 7)
340 self.checkequal(-1, 'тест тест', 'rfind', 'ec') # english `ec`
341 # test mixed kinds
342 self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
343 self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
344 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
345 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
346 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
347 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
348 self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
349 self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
350 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
351 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
352 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
353 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
354
355 def test_index(self):
356 string_tests.CommonTest.test_index(self)
357 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
358 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
359 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
360 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
361 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
362 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
363 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
364 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
365 # test mixed kinds
366 self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
367 self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
368 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
369 self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
370 self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
371 self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
372 self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
373 self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
374 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
375 self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
376 self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
377 self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
378
379 def test_rindex(self):
380 string_tests.CommonTest.test_rindex(self)
381 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
382 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
383 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
384 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
385
386 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
387 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
388 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
389 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
390 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
391 # test mixed kinds
392 self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
393 self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
394 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
395 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
396 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
397 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
398 self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
399 self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
400 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
401 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
402 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
403 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
404
405 def test_maketrans_translate(self):
406 # these work with plain translate()
407 self.checkequalnofix('bbbc', 'abababc', 'translate',
408 {ord('a'): None})
409 self.checkequalnofix('iiic', 'abababc', 'translate',
410 {ord('a'): None, ord('b'): ord('i')})
411 self.checkequalnofix('iiix', 'abababc', 'translate',
412 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
413 self.checkequalnofix('c', 'abababc', 'translate',
414 {ord('a'): None, ord('b'): ''})
415 self.checkequalnofix('xyyx', 'xzx', 'translate',
416 {ord('z'): 'yy'})
417
418 # this needs maketrans()
419 self.checkequalnofix('abababc', 'abababc', 'translate',
420 {'b': '<i>'})
421 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
422 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
423 # test alternative way of calling maketrans()
424 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
425 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
426
427 # various tests switching from ASCII to latin1 or the opposite;
428 # same length, remove a letter, or replace with a longer string.
429 self.assertEqual("[a]".translate(str.maketrans('a', 'X')),
430 "[X]")
431 self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})),
432 "[X]")
433 self.assertEqual("[a]".translate(str.maketrans({'a': None})),
434 "[]")
435 self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})),
436 "[XXX]")
437 self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})),
438 "[\xe9]")
439 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})),
440 "x123")
441 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})),
442 "x\xe9")
443
444 # test non-ASCII (don't take the fast-path)
445 self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})),
446 "[<\xe9>]")
447 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})),
448 "[a]")
449 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})),
450 "[]")
451 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})),
452 "[123]")
453 self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})),
454 "[<\u20ac>\xe9]")
455
456 # invalid Unicode characters
457 invalid_char = 0x10ffff+1
458 for before in "a\xe9\u20ac\U0010ffff":
459 mapping = str.maketrans({before: invalid_char})
460 text = "[%s]" % before
461 self.assertRaises(ValueError, text.translate, mapping)
462
463 # errors
464 self.assertRaises(TypeError, self.type2test.maketrans)
465 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
466 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
467 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
468 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
469 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
470 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
471
472 self.assertRaises(TypeError, 'hello'.translate)
473 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
474
475 def test_split(self):
476 string_tests.CommonTest.test_split(self)
477
478 # test mixed kinds
479 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
480 left *= 9
481 right *= 9
482 for delim in ('c', '\u0102', '\U00010302'):
483 self.checkequal([left + right],
484 left + right, 'split', delim)
485 self.checkequal([left, right],
486 left + delim + right, 'split', delim)
487 self.checkequal([left + right],
488 left + right, 'split', delim * 2)
489 self.checkequal([left, right],
490 left + delim * 2 + right, 'split', delim *2)
491
492 def test_rsplit(self):
493 string_tests.CommonTest.test_rsplit(self)
494 # test mixed kinds
495 for left, right in ('ba', 'юё', '\u0101\u0100', '\U00010301\U00010300'):
496 left *= 9
497 right *= 9
498 for delim in ('c', 'ы', '\u0102', '\U00010302'):
499 self.checkequal([left + right],
500 left + right, 'rsplit', delim)
501 self.checkequal([left, right],
502 left + delim + right, 'rsplit', delim)
503 self.checkequal([left + right],
504 left + right, 'rsplit', delim * 2)
505 self.checkequal([left, right],
506 left + delim * 2 + right, 'rsplit', delim *2)
507
508 # Check `None` as well:
509 self.checkequal([left + right],
510 left + right, 'rsplit', None)
511
512 def test_partition(self):
513 string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
514 # test mixed kinds
515 self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
516 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
517 left *= 9
518 right *= 9
519 for delim in ('c', '\u0102', '\U00010302'):
520 self.checkequal((left + right, '', ''),
521 left + right, 'partition', delim)
522 self.checkequal((left, delim, right),
523 left + delim + right, 'partition', delim)
524 self.checkequal((left + right, '', ''),
525 left + right, 'partition', delim * 2)
526 self.checkequal((left, delim * 2, right),
527 left + delim * 2 + right, 'partition', delim * 2)
528
529 def test_rpartition(self):
530 string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
531 # test mixed kinds
532 self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
533 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
534 left *= 9
535 right *= 9
536 for delim in ('c', '\u0102', '\U00010302'):
537 self.checkequal(('', '', left + right),
538 left + right, 'rpartition', delim)
539 self.checkequal((left, delim, right),
540 left + delim + right, 'rpartition', delim)
541 self.checkequal(('', '', left + right),
542 left + right, 'rpartition', delim * 2)
543 self.checkequal((left, delim * 2, right),
544 left + delim * 2 + right, 'rpartition', delim * 2)
545
546 def test_join(self):
547 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
548
549 class MyWrapper:
550 def __init__(self, sval): self.sval = sval
551 def __str__(self): return self.sval
552
553 # mixed arguments
554 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
555 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
556 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
557 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
558 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
559 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
560 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
561 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
562 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
563 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
564 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
565
566 @unittest.skipIf(sys.maxsize > 2**32,
567 'needs too much memory on a 64-bit platform')
568 @support.cpython_only
569 def test_join_overflow(self):
570 size = int(sys.maxsize**0.5) + 1
571 seq = ('A' * size,) * size
572 self.assertRaises(OverflowError, ''.join, seq)
573
574 def test_replace(self):
575 string_tests.CommonTest.test_replace(self)
576
577 # method call forwarded from str implementation because of unicode argument
578 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
579 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
580 # test mixed kinds
581 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
582 left *= 9
583 right *= 9
584 for delim in ('c', '\u0102', '\U00010302'):
585 for repl in ('d', '\u0103', '\U00010303'):
586 self.checkequal(left + right,
587 left + right, 'replace', delim, repl)
588 self.checkequal(left + repl + right,
589 left + delim + right,
590 'replace', delim, repl)
591 self.checkequal(left + right,
592 left + right, 'replace', delim * 2, repl)
593 self.checkequal(left + repl + right,
594 left + delim * 2 + right,
595 'replace', delim * 2, repl)
596
597 @support.cpython_only
598 def test_replace_id(self):
599 pattern = 'abc'
600 text = 'abc def'
601 self.assertIs(text.replace(pattern, pattern), text)
602
603 def test_repeat_id_preserving(self):
604 a = '123abc1@'
605 b = '456zyx-+'
606 self.assertEqual(id(a), id(a))
607 self.assertNotEqual(id(a), id(b))
608 self.assertNotEqual(id(a), id(a * -4))
609 self.assertNotEqual(id(a), id(a * 0))
610 self.assertEqual(id(a), id(a * 1))
611 self.assertEqual(id(a), id(1 * a))
612 self.assertNotEqual(id(a), id(a * 2))
613
614 class SubStr(str):
615 pass
616
617 s = SubStr('qwerty()')
618 self.assertEqual(id(s), id(s))
619 self.assertNotEqual(id(s), id(s * -4))
620 self.assertNotEqual(id(s), id(s * 0))
621 self.assertNotEqual(id(s), id(s * 1))
622 self.assertNotEqual(id(s), id(1 * s))
623 self.assertNotEqual(id(s), id(s * 2))
624
625 def test_bytes_comparison(self):
626 with warnings_helper.check_warnings():
627 warnings.simplefilter('ignore', BytesWarning)
628 self.assertEqual('abc' == b'abc', False)
629 self.assertEqual('abc' != b'abc', True)
630 self.assertEqual('abc' == bytearray(b'abc'), False)
631 self.assertEqual('abc' != bytearray(b'abc'), True)
632
633 def test_comparison(self):
634 # Comparisons:
635 self.assertEqual('abc', 'abc')
636 self.assertTrue('abcd' > 'abc')
637 self.assertTrue('abc' < 'abcd')
638
639 if 0:
640 # Move these tests to a Unicode collation module test...
641 # Testing UTF-16 code point order comparisons...
642
643 # No surrogates, no fixup required.
644 self.assertTrue('\u0061' < '\u20ac')
645 # Non surrogate below surrogate value, no fixup required
646 self.assertTrue('\u0061' < '\ud800\udc02')
647
648 # Non surrogate above surrogate value, fixup required
649 def test_lecmp(s, s2):
650 self.assertTrue(s < s2)
651
652 def test_fixup(s):
653 s2 = '\ud800\udc01'
654 test_lecmp(s, s2)
655 s2 = '\ud900\udc01'
656 test_lecmp(s, s2)
657 s2 = '\uda00\udc01'
658 test_lecmp(s, s2)
659 s2 = '\udb00\udc01'
660 test_lecmp(s, s2)
661 s2 = '\ud800\udd01'
662 test_lecmp(s, s2)
663 s2 = '\ud900\udd01'
664 test_lecmp(s, s2)
665 s2 = '\uda00\udd01'
666 test_lecmp(s, s2)
667 s2 = '\udb00\udd01'
668 test_lecmp(s, s2)
669 s2 = '\ud800\ude01'
670 test_lecmp(s, s2)
671 s2 = '\ud900\ude01'
672 test_lecmp(s, s2)
673 s2 = '\uda00\ude01'
674 test_lecmp(s, s2)
675 s2 = '\udb00\ude01'
676 test_lecmp(s, s2)
677 s2 = '\ud800\udfff'
678 test_lecmp(s, s2)
679 s2 = '\ud900\udfff'
680 test_lecmp(s, s2)
681 s2 = '\uda00\udfff'
682 test_lecmp(s, s2)
683 s2 = '\udb00\udfff'
684 test_lecmp(s, s2)
685
686 test_fixup('\ue000')
687 test_fixup('\uff61')
688
689 # Surrogates on both sides, no fixup required
690 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
691
692 def test_islower(self):
693 super().test_islower()
694 self.checkequalnofix(False, '\u1FFc', 'islower')
695 self.assertFalse('\u2167'.islower())
696 self.assertTrue('\u2177'.islower())
697 # non-BMP, uppercase
698 self.assertFalse('\U00010401'.islower())
699 self.assertFalse('\U00010427'.islower())
700 # non-BMP, lowercase
701 self.assertTrue('\U00010429'.islower())
702 self.assertTrue('\U0001044E'.islower())
703 # non-BMP, non-cased
704 self.assertFalse('\U0001F40D'.islower())
705 self.assertFalse('\U0001F46F'.islower())
706
707 def test_isupper(self):
708 super().test_isupper()
709 if not sys.platform.startswith('java'):
710 self.checkequalnofix(False, '\u1FFc', 'isupper')
711 self.assertTrue('\u2167'.isupper())
712 self.assertFalse('\u2177'.isupper())
713 # non-BMP, uppercase
714 self.assertTrue('\U00010401'.isupper())
715 self.assertTrue('\U00010427'.isupper())
716 # non-BMP, lowercase
717 self.assertFalse('\U00010429'.isupper())
718 self.assertFalse('\U0001044E'.isupper())
719 # non-BMP, non-cased
720 self.assertFalse('\U0001F40D'.isupper())
721 self.assertFalse('\U0001F46F'.isupper())
722
723 def test_istitle(self):
724 super().test_istitle()
725 self.checkequalnofix(True, '\u1FFc', 'istitle')
726 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
727
728 # non-BMP, uppercase + lowercase
729 self.assertTrue('\U00010401\U00010429'.istitle())
730 self.assertTrue('\U00010427\U0001044E'.istitle())
731 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
732 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
733 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
734
735 def test_isspace(self):
736 super().test_isspace()
737 self.checkequalnofix(True, '\u2000', 'isspace')
738 self.checkequalnofix(True, '\u200a', 'isspace')
739 self.checkequalnofix(False, '\u2014', 'isspace')
740 # There are no non-BMP whitespace chars as of Unicode 12.
741 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
742 '\U0001F40D', '\U0001F46F']:
743 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
744
745 @support.requires_resource('cpu')
746 def test_isspace_invariant(self):
747 for codepoint in range(sys.maxunicode + 1):
748 char = chr(codepoint)
749 bidirectional = unicodedata.bidirectional(char)
750 category = unicodedata.category(char)
751 self.assertEqual(char.isspace(),
752 (bidirectional in ('WS', 'B', 'S')
753 or category == 'Zs'))
754
755 def test_isalnum(self):
756 super().test_isalnum()
757 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
758 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
759 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
760
761 def test_isalpha(self):
762 super().test_isalpha()
763 self.checkequalnofix(True, '\u1FFc', 'isalpha')
764 # non-BMP, cased
765 self.assertTrue('\U00010401'.isalpha())
766 self.assertTrue('\U00010427'.isalpha())
767 self.assertTrue('\U00010429'.isalpha())
768 self.assertTrue('\U0001044E'.isalpha())
769 # non-BMP, non-cased
770 self.assertFalse('\U0001F40D'.isalpha())
771 self.assertFalse('\U0001F46F'.isalpha())
772
773 def test_isascii(self):
774 super().test_isascii()
775 self.assertFalse("\u20ac".isascii())
776 self.assertFalse("\U0010ffff".isascii())
777
778 def test_isdecimal(self):
779 self.checkequalnofix(False, '', 'isdecimal')
780 self.checkequalnofix(False, 'a', 'isdecimal')
781 self.checkequalnofix(True, '0', 'isdecimal')
782 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
783 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
784 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
785 self.checkequalnofix(True, '0123456789', 'isdecimal')
786 self.checkequalnofix(False, '0123456789a', 'isdecimal')
787
788 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
789
790 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
791 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
792 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
793 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
794 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
795
796 def test_isdigit(self):
797 super().test_isdigit()
798 self.checkequalnofix(True, '\u2460', 'isdigit')
799 self.checkequalnofix(False, '\xbc', 'isdigit')
800 self.checkequalnofix(True, '\u0660', 'isdigit')
801
802 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
803 '\U0001F40D', '\U0001F46F', '\U00011065']:
804 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
805 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
806 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
807
808 def test_isnumeric(self):
809 self.checkequalnofix(False, '', 'isnumeric')
810 self.checkequalnofix(False, 'a', 'isnumeric')
811 self.checkequalnofix(True, '0', 'isnumeric')
812 self.checkequalnofix(True, '\u2460', 'isnumeric')
813 self.checkequalnofix(True, '\xbc', 'isnumeric')
814 self.checkequalnofix(True, '\u0660', 'isnumeric')
815 self.checkequalnofix(True, '0123456789', 'isnumeric')
816 self.checkequalnofix(False, '0123456789a', 'isnumeric')
817
818 self.assertRaises(TypeError, "abc".isnumeric, 42)
819
820 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
821 '\U0001F40D', '\U0001F46F']:
822 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
823 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
824 '\U000104A0', '\U0001F107']:
825 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
826
827 def test_isidentifier(self):
828 self.assertTrue("a".isidentifier())
829 self.assertTrue("Z".isidentifier())
830 self.assertTrue("_".isidentifier())
831 self.assertTrue("b0".isidentifier())
832 self.assertTrue("bc".isidentifier())
833 self.assertTrue("b_".isidentifier())
834 self.assertTrue("µ".isidentifier())
835 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
836
837 self.assertFalse(" ".isidentifier())
838 self.assertFalse("[".isidentifier())
839 self.assertFalse("©".isidentifier())
840 self.assertFalse("0".isidentifier())
841
842 @support.cpython_only
843 @support.requires_legacy_unicode_capi
844 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
845 def test_isidentifier_legacy(self):
846 u = '𝖀𝖓𝖎𝖈𝖔𝖉𝖊'
847 self.assertTrue(u.isidentifier())
848 with warnings_helper.check_warnings():
849 warnings.simplefilter('ignore', DeprecationWarning)
850 self.assertTrue(_testcapi.unicode_legacy_string(u).isidentifier())
851
852 def test_isprintable(self):
853 self.assertTrue("".isprintable())
854 self.assertTrue(" ".isprintable())
855 self.assertTrue("abcdefg".isprintable())
856 self.assertFalse("abcdefg\n".isprintable())
857 # some defined Unicode character
858 self.assertTrue("\u0374".isprintable())
859 # undefined character
860 self.assertFalse("\u0378".isprintable())
861 # single surrogate character
862 self.assertFalse("\ud800".isprintable())
863
864 self.assertTrue('\U0001F46F'.isprintable())
865 self.assertFalse('\U000E0020'.isprintable())
866
867 def test_surrogates(self):
868 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
869 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
870 self.assertTrue(s.islower())
871 self.assertFalse(s.isupper())
872 self.assertFalse(s.istitle())
873 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
874 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
875 self.assertFalse(s.islower())
876 self.assertTrue(s.isupper())
877 self.assertTrue(s.istitle())
878
879 for meth_name in ('islower', 'isupper', 'istitle'):
880 meth = getattr(str, meth_name)
881 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
882 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
883
884 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
885 'isdecimal', 'isnumeric',
886 'isidentifier', 'isprintable'):
887 meth = getattr(str, meth_name)
888 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
889 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
890 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
891 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
892
893
894 def test_lower(self):
895 string_tests.CommonTest.test_lower(self)
896 self.assertEqual('\U00010427'.lower(), '\U0001044F')
897 self.assertEqual('\U00010427\U00010427'.lower(),
898 '\U0001044F\U0001044F')
899 self.assertEqual('\U00010427\U0001044F'.lower(),
900 '\U0001044F\U0001044F')
901 self.assertEqual('X\U00010427x\U0001044F'.lower(),
902 'x\U0001044Fx\U0001044F')
903 self.assertEqual('fi'.lower(), 'fi')
904 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
905 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
906 self.assertEqual('\u03a3'.lower(), '\u03c3')
907 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
908 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
909 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
910 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
911 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
912 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
913 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
914 self.assertEqual('\u2177'.lower(), '\u2177')
915
916 def test_casefold(self):
917 self.assertEqual('hello'.casefold(), 'hello')
918 self.assertEqual('hELlo'.casefold(), 'hello')
919 self.assertEqual('ß'.casefold(), 'ss')
920 self.assertEqual('fi'.casefold(), 'fi')
921 self.assertEqual('\u03a3'.casefold(), '\u03c3')
922 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
923 self.assertEqual('\u00b5'.casefold(), '\u03bc')
924
925 def test_upper(self):
926 string_tests.CommonTest.test_upper(self)
927 self.assertEqual('\U0001044F'.upper(), '\U00010427')
928 self.assertEqual('\U0001044F\U0001044F'.upper(),
929 '\U00010427\U00010427')
930 self.assertEqual('\U00010427\U0001044F'.upper(),
931 '\U00010427\U00010427')
932 self.assertEqual('X\U00010427x\U0001044F'.upper(),
933 'X\U00010427X\U00010427')
934 self.assertEqual('fi'.upper(), 'FI')
935 self.assertEqual('\u0130'.upper(), '\u0130')
936 self.assertEqual('\u03a3'.upper(), '\u03a3')
937 self.assertEqual('ß'.upper(), 'SS')
938 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
939 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
940 self.assertEqual('\u2177'.upper(), '\u2167')
941
942 def test_capitalize(self):
943 string_tests.CommonTest.test_capitalize(self)
944 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
945 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
946 '\U00010427\U0001044F')
947 self.assertEqual('\U00010427\U0001044F'.capitalize(),
948 '\U00010427\U0001044F')
949 self.assertEqual('\U0001044F\U00010427'.capitalize(),
950 '\U00010427\U0001044F')
951 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
952 'X\U0001044Fx\U0001044F')
953 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
954 exp = '\u0399\u0308\u0300\u0069\u0307'
955 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
956 self.assertEqual('finnish'.capitalize(), 'Finnish')
957 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
958
959 def test_title(self):
960 super().test_title()
961 self.assertEqual('\U0001044F'.title(), '\U00010427')
962 self.assertEqual('\U0001044F\U0001044F'.title(),
963 '\U00010427\U0001044F')
964 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
965 '\U00010427\U0001044F \U00010427\U0001044F')
966 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
967 '\U00010427\U0001044F \U00010427\U0001044F')
968 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
969 '\U00010427\U0001044F \U00010427\U0001044F')
970 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
971 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
972 self.assertEqual('fiNNISH'.title(), 'Finnish')
973 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
974 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
975
976 def test_swapcase(self):
977 string_tests.CommonTest.test_swapcase(self)
978 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
979 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
980 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
981 '\U00010427\U00010427')
982 self.assertEqual('\U00010427\U0001044F'.swapcase(),
983 '\U0001044F\U00010427')
984 self.assertEqual('\U0001044F\U00010427'.swapcase(),
985 '\U00010427\U0001044F')
986 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
987 'x\U0001044FX\U00010427')
988 self.assertEqual('fi'.swapcase(), 'FI')
989 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
990 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
991 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
992 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
993 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
994 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
995 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
996 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
997 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
998 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
999 self.assertEqual('ß'.swapcase(), 'SS')
1000 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
1001
1002 def test_center(self):
1003 string_tests.CommonTest.test_center(self)
1004 self.assertEqual('x'.center(2, '\U0010FFFF'),
1005 'x\U0010FFFF')
1006 self.assertEqual('x'.center(3, '\U0010FFFF'),
1007 '\U0010FFFFx\U0010FFFF')
1008 self.assertEqual('x'.center(4, '\U0010FFFF'),
1009 '\U0010FFFFx\U0010FFFF\U0010FFFF')
1010
1011 @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
1012 @support.cpython_only
1013 def test_case_operation_overflow(self):
1014 # Issue #22643
1015 size = 2**32//12 + 1
1016 try:
1017 s = "ü" * size
1018 except MemoryError:
1019 self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
1020 try:
1021 self.assertRaises(OverflowError, s.upper)
1022 finally:
1023 del s
1024
1025 def test_contains(self):
1026 # Testing Unicode contains method
1027 self.assertIn('a', 'abdb')
1028 self.assertIn('a', 'bdab')
1029 self.assertIn('a', 'bdaba')
1030 self.assertIn('a', 'bdba')
1031 self.assertNotIn('a', 'bdb')
1032 self.assertIn('a', 'bdba')
1033 self.assertIn('a', ('a',1,None))
1034 self.assertIn('a', (1,None,'a'))
1035 self.assertIn('a', ('a',1,None))
1036 self.assertIn('a', (1,None,'a'))
1037 self.assertNotIn('a', ('x',1,'y'))
1038 self.assertNotIn('a', ('x',1,None))
1039 self.assertNotIn('abcd', 'abcxxxx')
1040 self.assertIn('ab', 'abcd')
1041 self.assertIn('ab', 'abc')
1042 self.assertIn('ab', (1,None,'ab'))
1043 self.assertIn('', 'abc')
1044 self.assertIn('', '')
1045 self.assertIn('', 'abc')
1046 self.assertNotIn('\0', 'abc')
1047 self.assertIn('\0', '\0abc')
1048 self.assertIn('\0', 'abc\0')
1049 self.assertIn('a', '\0abc')
1050 self.assertIn('asdf', 'asdf')
1051 self.assertNotIn('asdf', 'asd')
1052 self.assertNotIn('asdf', '')
1053
1054 self.assertRaises(TypeError, "abc".__contains__)
1055 # test mixed kinds
1056 for fill in ('a', '\u0100', '\U00010300'):
1057 fill *= 9
1058 for delim in ('c', '\u0102', '\U00010302'):
1059 self.assertNotIn(delim, fill)
1060 self.assertIn(delim, fill + delim)
1061 self.assertNotIn(delim * 2, fill)
1062 self.assertIn(delim * 2, fill + delim * 2)
1063
1064 def test_issue18183(self):
1065 '\U00010000\U00100000'.lower()
1066 '\U00010000\U00100000'.casefold()
1067 '\U00010000\U00100000'.upper()
1068 '\U00010000\U00100000'.capitalize()
1069 '\U00010000\U00100000'.title()
1070 '\U00010000\U00100000'.swapcase()
1071 '\U00100000'.center(3, '\U00010000')
1072 '\U00100000'.ljust(3, '\U00010000')
1073 '\U00100000'.rjust(3, '\U00010000')
1074
1075 def test_format(self):
1076 self.assertEqual(''.format(), '')
1077 self.assertEqual('a'.format(), 'a')
1078 self.assertEqual('ab'.format(), 'ab')
1079 self.assertEqual('a{{'.format(), 'a{')
1080 self.assertEqual('a}}'.format(), 'a}')
1081 self.assertEqual('{{b'.format(), '{b')
1082 self.assertEqual('}}b'.format(), '}b')
1083 self.assertEqual('a{{b'.format(), 'a{b')
1084
1085 # examples from the PEP:
1086 import datetime
1087 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
1088 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
1089 "My name is Fred")
1090 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
1091 "My name is Fred :-{}")
1092
1093 d = datetime.date(2007, 8, 18)
1094 self.assertEqual("The year is {0.year}".format(d),
1095 "The year is 2007")
1096
1097 # classes we'll use for testing
1098 class C:
1099 def __init__(self, x=100):
1100 self._x = x
1101 def __format__(self, spec):
1102 return spec
1103
1104 class D:
1105 def __init__(self, x):
1106 self.x = x
1107 def __format__(self, spec):
1108 return str(self.x)
1109
1110 # class with __str__, but no __format__
1111 class E:
1112 def __init__(self, x):
1113 self.x = x
1114 def __str__(self):
1115 return 'E(' + self.x + ')'
1116
1117 # class with __repr__, but no __format__ or __str__
1118 class F:
1119 def __init__(self, x):
1120 self.x = x
1121 def __repr__(self):
1122 return 'F(' + self.x + ')'
1123
1124 # class with __format__ that forwards to string, for some format_spec's
1125 class G:
1126 def __init__(self, x):
1127 self.x = x
1128 def __str__(self):
1129 return "string is " + self.x
1130 def __format__(self, format_spec):
1131 if format_spec == 'd':
1132 return 'G(' + self.x + ')'
1133 return object.__format__(self, format_spec)
1134
1135 class I(datetime.date):
1136 def __format__(self, format_spec):
1137 return self.strftime(format_spec)
1138
1139 class J(int):
1140 def __format__(self, format_spec):
1141 return int.__format__(self * 2, format_spec)
1142
1143 class M:
1144 def __init__(self, x):
1145 self.x = x
1146 def __repr__(self):
1147 return 'M(' + self.x + ')'
1148 __str__ = None
1149
1150 class N:
1151 def __init__(self, x):
1152 self.x = x
1153 def __repr__(self):
1154 return 'N(' + self.x + ')'
1155 __format__ = None
1156
1157 self.assertEqual(''.format(), '')
1158 self.assertEqual('abc'.format(), 'abc')
1159 self.assertEqual('{0}'.format('abc'), 'abc')
1160 self.assertEqual('{0:}'.format('abc'), 'abc')
1161 # self.assertEqual('{ 0 }'.format('abc'), 'abc')
1162 self.assertEqual('X{0}'.format('abc'), 'Xabc')
1163 self.assertEqual('{0}X'.format('abc'), 'abcX')
1164 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
1165 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
1166 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
1167 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
1168 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
1169 self.assertEqual('{0}'.format(-15), '-15')
1170 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
1171 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
1172 self.assertEqual('{{'.format(), '{')
1173 self.assertEqual('}}'.format(), '}')
1174 self.assertEqual('{{}}'.format(), '{}')
1175 self.assertEqual('{{x}}'.format(), '{x}')
1176 self.assertEqual('{{{0}}}'.format(123), '{123}')
1177 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
1178 self.assertEqual('}}{{'.format(), '}{')
1179 self.assertEqual('}}x{{'.format(), '}x{')
1180
1181 # weird field names
1182 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
1183 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
1184 self.assertEqual("{0[ ]}".format({' ':3}), '3')
1185
1186 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
1187 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
1188 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
1189 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
1190 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
1191 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
1192 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
1193
1194 # strings
1195 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
1196 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
1197 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
1198 self.assertEqual('{0:.0s}'.format('abcdef'), '')
1199 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
1200 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
1201 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
1202 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
1203 self.assertEqual('{0:x<0s}'.format('result'), 'result')
1204 self.assertEqual('{0:x<5s}'.format('result'), 'result')
1205 self.assertEqual('{0:x<6s}'.format('result'), 'result')
1206 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
1207 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
1208 self.assertEqual('{0: <7s}'.format('result'), 'result ')
1209 self.assertEqual('{0:<7s}'.format('result'), 'result ')
1210 self.assertEqual('{0:>7s}'.format('result'), ' result')
1211 self.assertEqual('{0:>8s}'.format('result'), ' result')
1212 self.assertEqual('{0:^8s}'.format('result'), ' result ')
1213 self.assertEqual('{0:^9s}'.format('result'), ' result ')
1214 self.assertEqual('{0:^10s}'.format('result'), ' result ')
1215 self.assertEqual('{0:8s}'.format('result'), 'result ')
1216 self.assertEqual('{0:0s}'.format('result'), 'result')
1217 self.assertEqual('{0:08s}'.format('result'), 'result00')
1218 self.assertEqual('{0:<08s}'.format('result'), 'result00')
1219 self.assertEqual('{0:>08s}'.format('result'), '00result')
1220 self.assertEqual('{0:^08s}'.format('result'), '0result0')
1221 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
1222 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
1223 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
1224
1225 # issue 12546: use \x00 as a fill character
1226 self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
1227 self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
1228 self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
1229 self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
1230
1231 self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
1232 self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
1233 self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
1234 self.assertEqual('{0:<6}'.format(3), '3 ')
1235
1236 self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
1237 self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
1238 self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
1239 self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
1240
1241 self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
1242 self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
1243 self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
1244 self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
1245
1246 # format specifiers for user defined type
1247 self.assertEqual('{0:abc}'.format(C()), 'abc')
1248
1249 # !r, !s and !a coercions
1250 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
1251 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
1252 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
1253 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
1254 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
1255 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
1256 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
1257 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
1258 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
1259 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
1260 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
1261 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
1262 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
1263 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
1264 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
1265 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
1266
1267 # test fallback to object.__format__
1268 self.assertEqual('{0}'.format({}), '{}')
1269 self.assertEqual('{0}'.format([]), '[]')
1270 self.assertEqual('{0}'.format([1]), '[1]')
1271
1272 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
1273 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
1274
1275 self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
1276 self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
1277 self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
1278
1279 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
1280 month=8,
1281 day=27)),
1282 "date: 2007-08-27")
1283
1284 # test deriving from a builtin type and overriding __format__
1285 self.assertEqual("{0}".format(J(10)), "20")
1286
1287
1288 # string format specifiers
1289 self.assertEqual('{0:}'.format('a'), 'a')
1290
1291 # computed format specifiers
1292 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
1293 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
1294 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
1295 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
1296 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
1297
1298 # test various errors
1299 self.assertRaises(ValueError, '{'.format)
1300 self.assertRaises(ValueError, '}'.format)
1301 self.assertRaises(ValueError, 'a{'.format)
1302 self.assertRaises(ValueError, 'a}'.format)
1303 self.assertRaises(ValueError, '{a'.format)
1304 self.assertRaises(ValueError, '}a'.format)
1305 self.assertRaises(IndexError, '{0}'.format)
1306 self.assertRaises(IndexError, '{1}'.format, 'abc')
1307 self.assertRaises(KeyError, '{x}'.format)
1308 self.assertRaises(ValueError, "}{".format)
1309 self.assertRaises(ValueError, "abc{0:{}".format)
1310 self.assertRaises(ValueError, "{0".format)
1311 self.assertRaises(IndexError, "{0.}".format)
1312 self.assertRaises(ValueError, "{0.}".format, 0)
1313 self.assertRaises(ValueError, "{0[}".format)
1314 self.assertRaises(ValueError, "{0[}".format, [])
1315 self.assertRaises(KeyError, "{0]}".format)
1316 self.assertRaises(ValueError, "{0.[]}".format, 0)
1317 self.assertRaises(ValueError, "{0..foo}".format, 0)
1318 self.assertRaises(ValueError, "{0[0}".format, 0)
1319 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
1320 self.assertRaises(KeyError, "{c]}".format)
1321 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
1322 self.assertRaises(ValueError, "{0}}".format, 0)
1323 self.assertRaises(KeyError, "{foo}".format, bar=3)
1324 self.assertRaises(ValueError, "{0!x}".format, 3)
1325 self.assertRaises(ValueError, "{0!}".format, 0)
1326 self.assertRaises(ValueError, "{0!rs}".format, 0)
1327 self.assertRaises(ValueError, "{!}".format)
1328 self.assertRaises(IndexError, "{:}".format)
1329 self.assertRaises(IndexError, "{:s}".format)
1330 self.assertRaises(IndexError, "{}".format)
1331 big = "23098475029384702983476098230754973209482573"
1332 self.assertRaises(ValueError, ("{" + big + "}").format)
1333 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
1334
1335 # test number formatter errors:
1336 self.assertRaises(ValueError, '{0:x}'.format, 1j)
1337 self.assertRaises(ValueError, '{0:x}'.format, 1.0)
1338 self.assertRaises(ValueError, '{0:X}'.format, 1j)
1339 self.assertRaises(ValueError, '{0:X}'.format, 1.0)
1340 self.assertRaises(ValueError, '{0:o}'.format, 1j)
1341 self.assertRaises(ValueError, '{0:o}'.format, 1.0)
1342 self.assertRaises(ValueError, '{0:u}'.format, 1j)
1343 self.assertRaises(ValueError, '{0:u}'.format, 1.0)
1344 self.assertRaises(ValueError, '{0:i}'.format, 1j)
1345 self.assertRaises(ValueError, '{0:i}'.format, 1.0)
1346 self.assertRaises(ValueError, '{0:d}'.format, 1j)
1347 self.assertRaises(ValueError, '{0:d}'.format, 1.0)
1348
1349 # issue 6089
1350 self.assertRaises(ValueError, "{0[0]x}".format, [None])
1351 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
1352
1353 # can't have a replacement on the field name portion
1354 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
1355
1356 # exceed maximum recursion depth
1357 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
1358 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
1359 0, 1, 2, 3, 4, 5, 6, 7)
1360
1361 # string format spec errors
1362 sign_msg = "Sign not allowed in string format specifier"
1363 self.assertRaisesRegex(ValueError, sign_msg, "{0:-s}".format, '')
1364 self.assertRaisesRegex(ValueError, sign_msg, format, "", "-")
1365 space_msg = "Space not allowed in string format specifier"
1366 self.assertRaisesRegex(ValueError, space_msg, "{: }".format, '')
1367 self.assertRaises(ValueError, "{0:=s}".format, '')
1368
1369 # Alternate formatting is not supported
1370 self.assertRaises(ValueError, format, '', '#')
1371 self.assertRaises(ValueError, format, '', '#20')
1372
1373 # Non-ASCII
1374 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
1375 'ABC\u0410\u0411\u0412')
1376 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
1377 'ABC')
1378 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
1379 '')
1380
1381 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
1382 self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
1383 self.assertEqual("{[{]}".format({"{" : "a"}), "a")
1384 self.assertEqual("{[}]}".format({"}" : "a"}), "a")
1385 self.assertEqual("{[[]}".format({"[" : "a"}), "a")
1386 self.assertEqual("{[!]}".format({"!" : "a"}), "a")
1387 self.assertRaises(ValueError, "{a{}b}".format, 42)
1388 self.assertRaises(ValueError, "{a{b}".format, 42)
1389 self.assertRaises(ValueError, "{[}".format, 42)
1390
1391 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
1392
1393 # Blocking fallback
1394 m = M('data')
1395 self.assertEqual("{!r}".format(m), 'M(data)')
1396 self.assertRaises(TypeError, "{!s}".format, m)
1397 self.assertRaises(TypeError, "{}".format, m)
1398 n = N('data')
1399 self.assertEqual("{!r}".format(n), 'N(data)')
1400 self.assertEqual("{!s}".format(n), 'N(data)')
1401 self.assertRaises(TypeError, "{}".format, n)
1402
1403 def test_format_map(self):
1404 self.assertEqual(''.format_map({}), '')
1405 self.assertEqual('a'.format_map({}), 'a')
1406 self.assertEqual('ab'.format_map({}), 'ab')
1407 self.assertEqual('a{{'.format_map({}), 'a{')
1408 self.assertEqual('a}}'.format_map({}), 'a}')
1409 self.assertEqual('{{b'.format_map({}), '{b')
1410 self.assertEqual('}}b'.format_map({}), '}b')
1411 self.assertEqual('a{{b'.format_map({}), 'a{b')
1412
1413 # using mappings
1414 class Mapping(dict):
1415 def __missing__(self, key):
1416 return key
1417 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
1418 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
1419
1420 class InternalMapping:
1421 def __init__(self):
1422 self.mapping = {'a': 'hello'}
1423 def __getitem__(self, key):
1424 return self.mapping[key]
1425 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
1426
1427
1428 class C:
1429 def __init__(self, x=100):
1430 self._x = x
1431 def __format__(self, spec):
1432 return spec
1433 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
1434
1435 # test various errors
1436 self.assertRaises(TypeError, ''.format_map)
1437 self.assertRaises(TypeError, 'a'.format_map)
1438
1439 self.assertRaises(ValueError, '{'.format_map, {})
1440 self.assertRaises(ValueError, '}'.format_map, {})
1441 self.assertRaises(ValueError, 'a{'.format_map, {})
1442 self.assertRaises(ValueError, 'a}'.format_map, {})
1443 self.assertRaises(ValueError, '{a'.format_map, {})
1444 self.assertRaises(ValueError, '}a'.format_map, {})
1445
1446 # issue #12579: can't supply positional params to format_map
1447 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1448 self.assertRaises(ValueError, '{}'.format_map, 'a')
1449 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1450
1451 class BadMapping:
1452 def __getitem__(self, key):
1453 return 1/0
1454 self.assertRaises(KeyError, '{a}'.format_map, {})
1455 self.assertRaises(TypeError, '{a}'.format_map, [])
1456 self.assertRaises(ZeroDivisionError, '{a}'.format_map, BadMapping())
1457
1458 def test_format_huge_precision(self):
1459 format_string = ".{}f".format(sys.maxsize + 1)
1460 with self.assertRaises(ValueError):
1461 result = format(2.34, format_string)
1462
1463 def test_format_huge_width(self):
1464 format_string = "{}f".format(sys.maxsize + 1)
1465 with self.assertRaises(ValueError):
1466 result = format(2.34, format_string)
1467
1468 def test_format_huge_item_number(self):
1469 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1470 with self.assertRaises(ValueError):
1471 result = format_string.format(2.34)
1472
1473 def test_format_auto_numbering(self):
1474 class C:
1475 def __init__(self, x=100):
1476 self._x = x
1477 def __format__(self, spec):
1478 return spec
1479
1480 self.assertEqual('{}'.format(10), '10')
1481 self.assertEqual('{:5}'.format('s'), 's ')
1482 self.assertEqual('{!r}'.format('s'), "'s'")
1483 self.assertEqual('{._x}'.format(C(10)), '10')
1484 self.assertEqual('{[1]}'.format([1, 2]), '2')
1485 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1486 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1487
1488 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1489 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1490
1491 # can't mix and match numbering and auto-numbering
1492 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1493 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1494 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1495 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1496
1497 # can mix and match auto-numbering and named
1498 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1499 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1500 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1501 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1502
1503 def test_formatting(self):
1504 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
1505 # Testing Unicode formatting strings...
1506 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1507 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1508 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1509 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1510 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1511 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57')
1512 if not sys.platform.startswith('java'):
1513 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
1514 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1515 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
1516 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1517 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
1518
1519 self.assertEqual('%c' % 0x1234, '\u1234')
1520 self.assertEqual('%c' % 0x21483, '\U00021483')
1521 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1522 self.assertEqual('%c' % '\U00021483', '\U00021483')
1523 self.assertRaises(TypeError, "%c".__mod__, "aa")
1524 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
1525 self.assertRaises(TypeError, "%i".__mod__, "aa")
1526
1527 # formatting jobs delegated from the string implementation:
1528 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1529 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1530 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1531 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1532 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1533 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1534 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1535 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1536 self.assertEqual('...%s...' % "abc", '...abc...')
1537 self.assertEqual('%*s' % (5,'abc',), ' abc')
1538 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1539 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1540 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1541 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1542 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1543 self.assertEqual('%c' % 'a', 'a')
1544 class Wrapper:
1545 def __str__(self):
1546 return '\u1234'
1547 self.assertEqual('%s' % Wrapper(), '\u1234')
1548
1549 # issue 3382
1550 NAN = float('nan')
1551 INF = float('inf')
1552 self.assertEqual('%f' % NAN, 'nan')
1553 self.assertEqual('%F' % NAN, 'NAN')
1554 self.assertEqual('%f' % INF, 'inf')
1555 self.assertEqual('%F' % INF, 'INF')
1556
1557 # PEP 393
1558 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1559 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1560
1561 #issue 19995
1562 class PseudoInt:
1563 def __init__(self, value):
1564 self.value = int(value)
1565 def __int__(self):
1566 return self.value
1567 def __index__(self):
1568 return self.value
1569 class PseudoFloat:
1570 def __init__(self, value):
1571 self.value = float(value)
1572 def __int__(self):
1573 return int(self.value)
1574 pi = PseudoFloat(3.1415)
1575 letter_m = PseudoInt(109)
1576 self.assertEqual('%x' % 42, '2a')
1577 self.assertEqual('%X' % 15, 'F')
1578 self.assertEqual('%o' % 9, '11')
1579 self.assertEqual('%c' % 109, 'm')
1580 self.assertEqual('%x' % letter_m, '6d')
1581 self.assertEqual('%X' % letter_m, '6D')
1582 self.assertEqual('%o' % letter_m, '155')
1583 self.assertEqual('%c' % letter_m, 'm')
1584 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14)
1585 self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11)
1586 self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79)
1587 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi)
1588 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not complex', operator.mod, '%x', 3j)
1589 self.assertRaisesRegex(TypeError, '%X format: an integer is required, not complex', operator.mod, '%X', 2j)
1590 self.assertRaisesRegex(TypeError, '%o format: an integer is required, not complex', operator.mod, '%o', 1j)
1591 self.assertRaisesRegex(TypeError, '%u format: a real number is required, not complex', operator.mod, '%u', 3j)
1592 self.assertRaisesRegex(TypeError, '%i format: a real number is required, not complex', operator.mod, '%i', 2j)
1593 self.assertRaisesRegex(TypeError, '%d format: a real number is required, not complex', operator.mod, '%d', 1j)
1594 self.assertRaisesRegex(TypeError, '%c requires int or char', operator.mod, '%c', pi)
1595
1596 class RaisingNumber:
1597 def __int__(self):
1598 raise RuntimeError('int') # should not be `TypeError`
1599 def __index__(self):
1600 raise RuntimeError('index') # should not be `TypeError`
1601
1602 rn = RaisingNumber()
1603 self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%d', rn)
1604 self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%i', rn)
1605 self.assertRaisesRegex(RuntimeError, 'int', operator.mod, '%u', rn)
1606 self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%x', rn)
1607 self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%X', rn)
1608 self.assertRaisesRegex(RuntimeError, 'index', operator.mod, '%o', rn)
1609
1610 def test_formatting_with_enum(self):
1611 # issue18780
1612 import enum
1613 class Float(float, enum.Enum):
1614 # a mixed-in type will use the name for %s etc.
1615 PI = 3.1415926
1616 class Int(enum.IntEnum):
1617 # IntEnum uses the value and not the name for %s etc.
1618 IDES = 15
1619 class Str(enum.StrEnum):
1620 # StrEnum uses the value and not the name for %s etc.
1621 ABC = 'abc'
1622 # Testing Unicode formatting strings...
1623 self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
1624 'abc, abc')
1625 self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
1626 (Str.ABC, Str.ABC,
1627 Int.IDES, Int.IDES, Int.IDES,
1628 Float.PI, Float.PI),
1629 'abc, abc, 15, 15, 15, 3.141593, 3.14')
1630
1631 # formatting jobs delegated from the string implementation:
1632 self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
1633 '...abc...')
1634 self.assertEqual('...%(foo)r...' % {'foo':Int.IDES},
1635 '...<Int.IDES: 15>...')
1636 self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
1637 '...15...')
1638 self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
1639 '...15...')
1640 self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
1641 '...15...')
1642 self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
1643 '...15...')
1644 self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
1645 '...3.141593...')
1646
1647 def test_formatting_huge_precision(self):
1648 format_string = "%.{}f".format(sys.maxsize + 1)
1649 with self.assertRaises(ValueError):
1650 result = format_string % 2.34
1651
1652 def test_issue28598_strsubclass_rhs(self):
1653 # A subclass of str with an __rmod__ method should be able to hook
1654 # into the % operator
1655 class SubclassedStr(str):
1656 def __rmod__(self, other):
1657 return 'Success, self.__rmod__({!r}) was called'.format(other)
1658 self.assertEqual('lhs %% %r' % SubclassedStr('rhs'),
1659 "Success, self.__rmod__('lhs %% %r') was called")
1660
1661 @support.cpython_only
1662 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
1663 def test_formatting_huge_precision_c_limits(self):
1664 format_string = "%.{}f".format(_testcapi.INT_MAX + 1)
1665 with self.assertRaises(ValueError):
1666 result = format_string % 2.34
1667
1668 def test_formatting_huge_width(self):
1669 format_string = "%{}f".format(sys.maxsize + 1)
1670 with self.assertRaises(ValueError):
1671 result = format_string % 2.34
1672
1673 def test_startswith_endswith_errors(self):
1674 for meth in ('foo'.startswith, 'foo'.endswith):
1675 with self.assertRaises(TypeError) as cm:
1676 meth(['f'])
1677 exc = str(cm.exception)
1678 self.assertIn('str', exc)
1679 self.assertIn('tuple', exc)
1680
1681 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
1682 def test_format_float(self):
1683 # should not format with a comma, but always with C locale
1684 self.assertEqual('1.0', '%.1f' % 1.0)
1685
1686 def test_constructor(self):
1687 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1688
1689 self.assertEqual(
1690 str('unicode remains unicode'),
1691 'unicode remains unicode'
1692 )
1693
1694 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
1695 subclass = StrSubclass(text)
1696 self.assertEqual(str(subclass), text)
1697 self.assertEqual(len(subclass), len(text))
1698 if text == 'ascii':
1699 self.assertEqual(subclass.encode('ascii'), b'ascii')
1700 self.assertEqual(subclass.encode('utf-8'), b'ascii')
1701
1702 self.assertEqual(
1703 str('strings are converted to unicode'),
1704 'strings are converted to unicode'
1705 )
1706
1707 class StringCompat:
1708 def __init__(self, x):
1709 self.x = x
1710 def __str__(self):
1711 return self.x
1712
1713 self.assertEqual(
1714 str(StringCompat('__str__ compatible objects are recognized')),
1715 '__str__ compatible objects are recognized'
1716 )
1717
1718 # unicode(obj) is compatible to str():
1719
1720 o = StringCompat('unicode(obj) is compatible to str()')
1721 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
1722 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
1723
1724 for obj in (123, 123.45, 123):
1725 self.assertEqual(str(obj), str(str(obj)))
1726
1727 # unicode(obj, encoding, error) tests (this maps to
1728 # PyUnicode_FromEncodedObject() at C level)
1729
1730 if not sys.platform.startswith('java'):
1731 self.assertRaises(
1732 TypeError,
1733 str,
1734 'decoding unicode is not supported',
1735 'utf-8',
1736 'strict'
1737 )
1738
1739 self.assertEqual(
1740 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
1741 'strings are decoded to unicode'
1742 )
1743
1744 if not sys.platform.startswith('java'):
1745 self.assertEqual(
1746 str(
1747 memoryview(b'character buffers are decoded to unicode'),
1748 'utf-8',
1749 'strict'
1750 ),
1751 'character buffers are decoded to unicode'
1752 )
1753
1754 self.assertRaises(TypeError, str, 42, 42, 42)
1755
1756 def test_constructor_keyword_args(self):
1757 """Pass various keyword argument combinations to the constructor."""
1758 # The object argument can be passed as a keyword.
1759 self.assertEqual(str(object='foo'), 'foo')
1760 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1761 # The errors argument without encoding triggers "decode" mode.
1762 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1763 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1764
1765 def test_constructor_defaults(self):
1766 """Check the constructor argument defaults."""
1767 # The object argument defaults to '' or b''.
1768 self.assertEqual(str(), '')
1769 self.assertEqual(str(errors='strict'), '')
1770 utf8_cent = '¢'.encode('utf-8')
1771 # The encoding argument defaults to utf-8.
1772 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1773 # The errors argument defaults to strict.
1774 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1775
1776 def test_codecs_utf7(self):
1777 utfTests = [
1778 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1779 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1780 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1781 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1782 ('+', b'+-'),
1783 ('+-', b'+--'),
1784 ('+?', b'+-?'),
1785 (r'\?', b'+AFw?'),
1786 ('+?', b'+-?'),
1787 (r'\\?', b'+AFwAXA?'),
1788 (r'\\\?', b'+AFwAXABc?'),
1789 (r'++--', b'+-+---'),
1790 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1791 ('/', b'/'),
1792 ]
1793
1794 for (x, y) in utfTests:
1795 self.assertEqual(x.encode('utf-7'), y)
1796
1797 # Unpaired surrogates are passed through
1798 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1799 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1800 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1801 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1802 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1803 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1804 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1805 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
1806
1807 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1808 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
1809
1810 # Issue #2242: crash on some Windows/MSVC versions
1811 self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
1812
1813 # Direct encoded characters
1814 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1815 # Optional direct characters
1816 set_o = '!"#$%&*;<=>@[]^_`{|}'
1817 for c in set_d:
1818 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1819 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1820 for c in set_o:
1821 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1822
1823 with self.assertRaisesRegex(UnicodeDecodeError,
1824 'ill-formed sequence'):
1825 b'+@'.decode('utf-7')
1826
1827 def test_codecs_utf8(self):
1828 self.assertEqual(''.encode('utf-8'), b'')
1829 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
1830 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1831 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
1832 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1833 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
1834 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1835 b'\xf0\x90\x80\x82'*10)
1836 self.assertEqual(
1837 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1838 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1839 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1840 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1841 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1842 ' Nunstuck git und'.encode('utf-8'),
1843 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1844 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1845 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1846 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1847 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1848 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1849 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1850 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1851 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1852 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
1853 )
1854
1855 # UTF-8 specific decoding tests
1856 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1857 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1858 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
1859
1860 # Other possible utf-8 test cases:
1861 # * strict decoding testing for all of the
1862 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
1863
1864 def test_utf8_decode_valid_sequences(self):
1865 sequences = [
1866 # single byte
1867 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1868 # 2 bytes
1869 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1870 # 3 bytes
1871 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1872 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1873 # 4 bytes
1874 (b'\xF0\x90\x80\x80', '\U00010000'),
1875 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1876 ]
1877 for seq, res in sequences:
1878 self.assertEqual(seq.decode('utf-8'), res)
1879
1880
1881 def test_utf8_decode_invalid_sequences(self):
1882 # continuation bytes in a sequence of 2, 3, or 4 bytes
1883 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
1884 # start bytes of a 2-byte sequence equivalent to code points < 0x7F
1885 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
1886 # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
1887 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1888 invalid_start_bytes = (
1889 continuation_bytes + invalid_2B_seq_start_bytes +
1890 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1891 )
1892
1893 for byte in invalid_start_bytes:
1894 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1895
1896 for sb in invalid_2B_seq_start_bytes:
1897 for cb in continuation_bytes:
1898 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1899
1900 for sb in invalid_4B_seq_start_bytes:
1901 for cb1 in continuation_bytes[:3]:
1902 for cb3 in continuation_bytes[:3]:
1903 self.assertRaises(UnicodeDecodeError,
1904 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1905
1906 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1907 self.assertRaises(UnicodeDecodeError,
1908 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1909 self.assertRaises(UnicodeDecodeError,
1910 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1911 # surrogates
1912 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1913 self.assertRaises(UnicodeDecodeError,
1914 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1915 self.assertRaises(UnicodeDecodeError,
1916 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1917 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1918 self.assertRaises(UnicodeDecodeError,
1919 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1920 self.assertRaises(UnicodeDecodeError,
1921 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1922 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1923 self.assertRaises(UnicodeDecodeError,
1924 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1925 self.assertRaises(UnicodeDecodeError,
1926 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1927
1928 def test_issue8271(self):
1929 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1930 # only the start byte and the continuation byte(s) are now considered
1931 # invalid, instead of the number of bytes specified by the start byte.
1932 # See https://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
1933 # table 3-8, Row 2) for more information about the algorithm used.
1934 FFFD = '\ufffd'
1935 sequences = [
1936 # invalid start bytes
1937 (b'\x80', FFFD), # continuation byte
1938 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1939 (b'\xc0', FFFD),
1940 (b'\xc0\xc0', FFFD*2),
1941 (b'\xc1', FFFD),
1942 (b'\xc1\xc0', FFFD*2),
1943 (b'\xc0\xc1', FFFD*2),
1944 # with start byte of a 2-byte sequence
1945 (b'\xc2', FFFD), # only the start byte
1946 (b'\xc2\xc2', FFFD*2), # 2 start bytes
1947 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
1948 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1949 # with start byte of a 3-byte sequence
1950 (b'\xe1', FFFD), # only the start byte
1951 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1952 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1953 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1954 (b'\xe1\x80', FFFD), # only 1 continuation byte
1955 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1956 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1957 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1958 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1959 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1960 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1961 # with start byte of a 4-byte sequence
1962 (b'\xf1', FFFD), # only the start byte
1963 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1964 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1965 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1966 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1967 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1968 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1969 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1970 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1971 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1972 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1973 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1974 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1975 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1976 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1977 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1978 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1979 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1980 # with invalid start byte of a 4-byte sequence (rfc2279)
1981 (b'\xf5', FFFD), # only the start byte
1982 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1983 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1984 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1985 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1986 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1987 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1988 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1989 # with invalid start byte of a 5-byte sequence (rfc2279)
1990 (b'\xf8', FFFD), # only the start byte
1991 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1992 (b'\xf8\x80', FFFD*2), # only one continuation byte
1993 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1994 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1995 # with invalid start byte of a 6-byte sequence (rfc2279)
1996 (b'\xfc', FFFD), # only the start byte
1997 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1998 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1999 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
2000 # invalid start byte
2001 (b'\xfe', FFFD),
2002 (b'\xfe\x80\x80', FFFD*3),
2003 # other sequences
2004 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
2005 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
2006 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
2007 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
2008 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
2009 ]
2010 for n, (seq, res) in enumerate(sequences):
2011 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
2012 self.assertEqual(seq.decode('utf-8', 'replace'), res)
2013 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
2014 self.assertEqual(seq.decode('utf-8', 'ignore'),
2015 res.replace('\uFFFD', ''))
2016
2017 def assertCorrectUTF8Decoding(self, seq, res, err):
2018 """
2019 Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when
2020 'strict' is used, returns res when 'replace' is used, and that doesn't
2021 return anything when 'ignore' is used.
2022 """
2023 with self.assertRaises(UnicodeDecodeError) as cm:
2024 seq.decode('utf-8')
2025 exc = cm.exception
2026
2027 self.assertIn(err, str(exc))
2028 self.assertEqual(seq.decode('utf-8', 'replace'), res)
2029 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
2030 'aaaa' + res + 'bbbb')
2031 res = res.replace('\ufffd', '')
2032 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
2033 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
2034 'aaaa' + res + 'bbbb')
2035
2036 def test_invalid_start_byte(self):
2037 """
2038 Test that an 'invalid start byte' error is raised when the first byte
2039 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
2040 4-bytes sequence. The invalid start byte is replaced with a single
2041 U+FFFD when errors='replace'.
2042 E.g. <80> is a continuation byte and can appear only after a start byte.
2043 """
2044 FFFD = '\ufffd'
2045 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
2046 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
2047 'invalid start byte')
2048
2049 def test_unexpected_end_of_data(self):
2050 """
2051 Test that an 'unexpected end of data' error is raised when the string
2052 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
2053 enough continuation bytes. The incomplete sequence is replaced with a
2054 single U+FFFD when errors='replace'.
2055 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
2056 sequence, but it's followed by only 2 valid continuation bytes and the
2057 last continuation bytes is missing.
2058 Note: the continuation bytes must be all valid, if one of them is
2059 invalid another error will be raised.
2060 """
2061 sequences = [
2062 'C2', 'DF',
2063 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
2064 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
2065 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
2066 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
2067 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
2068 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
2069 ]
2070 FFFD = '\ufffd'
2071 for seq in sequences:
2072 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), '\ufffd',
2073 'unexpected end of data')
2074
2075 def test_invalid_cb_for_2bytes_seq(self):
2076 """
2077 Test that an 'invalid continuation byte' error is raised when the
2078 continuation byte of a 2-bytes sequence is invalid. The start byte
2079 is replaced by a single U+FFFD and the second byte is handled
2080 separately when errors='replace'.
2081 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
2082 sequence, but 41 is not a valid continuation byte because it's the
2083 ASCII letter 'A'.
2084 """
2085 FFFD = '\ufffd'
2086 FFFDx2 = FFFD * 2
2087 sequences = [
2088 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
2089 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
2090 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
2091 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
2092 ]
2093 for seq, res in sequences:
2094 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
2095 'invalid continuation byte')
2096
2097 def test_invalid_cb_for_3bytes_seq(self):
2098 """
2099 Test that an 'invalid continuation byte' error is raised when the
2100 continuation byte(s) of a 3-bytes sequence are invalid. When
2101 errors='replace', if the first continuation byte is valid, the first
2102 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
2103 third byte is handled separately, otherwise only the start byte is
2104 replaced with a U+FFFD and the other continuation bytes are handled
2105 separately.
2106 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
2107 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
2108 because it's the ASCII letter 'A'.
2109 Note: when the start byte is E0 or ED, the valid ranges for the first
2110 continuation byte are limited to A0..BF and 80..9F respectively.
2111 Python 2 used to consider all the bytes in range 80..BF valid when the
2112 start byte was ED. This is fixed in Python 3.
2113 """
2114 FFFD = '\ufffd'
2115 FFFDx2 = FFFD * 2
2116 sequences = [
2117 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
2118 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
2119 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
2120 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
2121 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
2122 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
2123 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
2124 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
2125 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
2126 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
2127 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
2128 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
2129 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
2130 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
2131 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
2132 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
2133 ('ED 7F', FFFD+'\x7f'),
2134 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
2135 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
2136 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
2137 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
2138 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
2139 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
2140 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
2141 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
2142 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
2143 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
2144 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
2145 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
2146 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
2147 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
2148 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
2149 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
2150 ]
2151 for seq, res in sequences:
2152 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
2153 'invalid continuation byte')
2154
2155 def test_invalid_cb_for_4bytes_seq(self):
2156 """
2157 Test that an 'invalid continuation byte' error is raised when the
2158 continuation byte(s) of a 4-bytes sequence are invalid. When
2159 errors='replace',the start byte and all the following valid
2160 continuation bytes are replaced with a single U+FFFD, and all the bytes
2161 starting from the first invalid continuation bytes (included) are
2162 handled separately.
2163 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
2164 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
2165 because it's the ASCII letter 'A'.
2166 Note: when the start byte is E0 or ED, the valid ranges for the first
2167 continuation byte are limited to A0..BF and 80..9F respectively.
2168 However, when the start byte is ED, Python 2 considers all the bytes
2169 in range 80..BF valid. This is fixed in Python 3.
2170 """
2171 FFFD = '\ufffd'
2172 FFFDx2 = FFFD * 2
2173 sequences = [
2174 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
2175 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
2176 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
2177 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
2178 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
2179 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
2180 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
2181 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
2182 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
2183 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
2184 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
2185 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
2186 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
2187 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
2188 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
2189 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
2190 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
2191 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
2192 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
2193 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
2194 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
2195 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
2196 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
2197 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
2198 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
2199 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
2200 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
2201 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
2202 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
2203 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
2204 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
2205 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
2206 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
2207 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
2208 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
2209 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
2210 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
2211 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
2212 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
2213 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
2214 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
2215 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
2216 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
2217 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
2218 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
2219 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
2220 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
2221 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
2222 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
2223 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
2224 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
2225 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
2226 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
2227 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
2228 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
2229 ]
2230 for seq, res in sequences:
2231 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
2232 'invalid continuation byte')
2233
2234 def test_codecs_idna(self):
2235 # Test whether trailing dot is preserved
2236 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
2237
2238 def test_codecs_errors(self):
2239 # Error handling (encoding)
2240 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
2241 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
2242 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
2243 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
2244 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
2245 'Andr\202 x'.encode('ascii', errors='replace'))
2246 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
2247 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
2248
2249 # Error handling (decoding)
2250 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
2251 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
2252 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
2253 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
2254 self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
2255
2256 # Error handling (unknown character names)
2257 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
2258
2259 # Error handling (truncated escape sequence)
2260 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
2261
2262 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
2263 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
2264 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
2265 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
2266
2267 # Error handling (wrong arguments)
2268 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
2269
2270 # Error handling (lone surrogate in
2271 # _PyUnicode_TransformDecimalAndSpaceToASCII())
2272 self.assertRaises(ValueError, int, "\ud800")
2273 self.assertRaises(ValueError, int, "\udf00")
2274 self.assertRaises(ValueError, float, "\ud800")
2275 self.assertRaises(ValueError, float, "\udf00")
2276 self.assertRaises(ValueError, complex, "\ud800")
2277 self.assertRaises(ValueError, complex, "\udf00")
2278
2279 def test_codecs(self):
2280 # Encoding
2281 self.assertEqual('hello'.encode('ascii'), b'hello')
2282 self.assertEqual('hello'.encode('utf-7'), b'hello')
2283 self.assertEqual('hello'.encode('utf-8'), b'hello')
2284 self.assertEqual('hello'.encode('utf-8'), b'hello')
2285 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
2286 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
2287 self.assertEqual('hello'.encode('latin-1'), b'hello')
2288
2289 # Default encoding is utf-8
2290 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
2291
2292 # Roundtrip safety for BMP (just the first 1024 chars)
2293 for c in range(1024):
2294 u = chr(c)
2295 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
2296 'utf-16-be', 'raw_unicode_escape',
2297 'unicode_escape'):
2298 self.assertEqual(str(u.encode(encoding),encoding), u)
2299
2300 # Roundtrip safety for BMP (just the first 256 chars)
2301 for c in range(256):
2302 u = chr(c)
2303 for encoding in ('latin-1',):
2304 self.assertEqual(str(u.encode(encoding),encoding), u)
2305
2306 # Roundtrip safety for BMP (just the first 128 chars)
2307 for c in range(128):
2308 u = chr(c)
2309 for encoding in ('ascii',):
2310 self.assertEqual(str(u.encode(encoding),encoding), u)
2311
2312 # Roundtrip safety for non-BMP (just a few chars)
2313 with warnings.catch_warnings():
2314 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
2315 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
2316 'raw_unicode_escape', 'unicode_escape'):
2317 self.assertEqual(str(u.encode(encoding),encoding), u)
2318
2319 # UTF-8 must be roundtrip safe for all code points
2320 # (except surrogates, which are forbidden).
2321 u = ''.join(map(chr, list(range(0, 0xd800)) +
2322 list(range(0xe000, 0x110000))))
2323 for encoding in ('utf-8',):
2324 self.assertEqual(str(u.encode(encoding),encoding), u)
2325
2326 def test_codecs_charmap(self):
2327 # 0-127
2328 s = bytes(range(128))
2329 for encoding in (
2330 'cp037', 'cp1026', 'cp273',
2331 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2332 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
2333 'cp863', 'cp865', 'cp866', 'cp1125',
2334 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2335 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
2336 'iso8859_7', 'iso8859_9',
2337 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1',
2338 'mac_cyrillic', 'mac_latin2',
2339
2340 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2341 'cp1256', 'cp1257', 'cp1258',
2342 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
2343
2344 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
2345 'cp1006', 'iso8859_8',
2346
2347 ### These have undefined mappings:
2348 #'cp424',
2349
2350 ### These fail the round-trip:
2351 #'cp875'
2352
2353 ):
2354 self.assertEqual(str(s, encoding).encode(encoding), s)
2355
2356 # 128-255
2357 s = bytes(range(128, 256))
2358 for encoding in (
2359 'cp037', 'cp1026', 'cp273',
2360 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2361 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
2362 'cp863', 'cp865', 'cp866', 'cp1125',
2363 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2364 'iso8859_2', 'iso8859_4', 'iso8859_5',
2365 'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1',
2366 'mac_cyrillic', 'mac_latin2',
2367
2368 ### These have undefined mappings:
2369 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2370 #'cp1256', 'cp1257', 'cp1258',
2371 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
2372 #'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048',
2373 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
2374
2375 ### These fail the round-trip:
2376 #'cp1006', 'cp875', 'iso8859_8',
2377
2378 ):
2379 self.assertEqual(str(s, encoding).encode(encoding), s)
2380
2381 def test_concatenation(self):
2382 self.assertEqual(("abc" "def"), "abcdef")
2383 self.assertEqual(("abc" "def"), "abcdef")
2384 self.assertEqual(("abc" "def"), "abcdef")
2385 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
2386 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
2387
2388 def test_ucs4(self):
2389 x = '\U00100000'
2390 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
2391 self.assertEqual(x, y)
2392
2393 y = br'\U00100000'
2394 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2395 self.assertEqual(x, y)
2396 y = br'\U00010000'
2397 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2398 self.assertEqual(x, y)
2399
2400 try:
2401 br'\U11111111'.decode("raw-unicode-escape")
2402 except UnicodeDecodeError as e:
2403 self.assertEqual(e.start, 0)
2404 self.assertEqual(e.end, 10)
2405 else:
2406 self.fail("Should have raised UnicodeDecodeError")
2407
2408 def test_conversion(self):
2409 # Make sure __str__() works properly
2410 class StrWithStr(str):
2411 def __new__(cls, value):
2412 self = str.__new__(cls, "")
2413 self.value = value
2414 return self
2415 def __str__(self):
2416 return self.value
2417
2418 self.assertTypedEqual(str(WithStr('abc')), 'abc')
2419 self.assertTypedEqual(str(WithStr(StrSubclass('abc'))), StrSubclass('abc'))
2420 self.assertTypedEqual(StrSubclass(WithStr('abc')), StrSubclass('abc'))
2421 self.assertTypedEqual(StrSubclass(WithStr(StrSubclass('abc'))),
2422 StrSubclass('abc'))
2423 self.assertTypedEqual(StrSubclass(WithStr(OtherStrSubclass('abc'))),
2424 StrSubclass('abc'))
2425
2426 self.assertTypedEqual(str(StrWithStr('abc')), 'abc')
2427 self.assertTypedEqual(str(StrWithStr(StrSubclass('abc'))), StrSubclass('abc'))
2428 self.assertTypedEqual(StrSubclass(StrWithStr('abc')), StrSubclass('abc'))
2429 self.assertTypedEqual(StrSubclass(StrWithStr(StrSubclass('abc'))),
2430 StrSubclass('abc'))
2431 self.assertTypedEqual(StrSubclass(StrWithStr(OtherStrSubclass('abc'))),
2432 StrSubclass('abc'))
2433
2434 self.assertTypedEqual(str(WithRepr('<abc>')), '<abc>')
2435 self.assertTypedEqual(str(WithRepr(StrSubclass('<abc>'))), StrSubclass('<abc>'))
2436 self.assertTypedEqual(StrSubclass(WithRepr('<abc>')), StrSubclass('<abc>'))
2437 self.assertTypedEqual(StrSubclass(WithRepr(StrSubclass('<abc>'))),
2438 StrSubclass('<abc>'))
2439 self.assertTypedEqual(StrSubclass(WithRepr(OtherStrSubclass('<abc>'))),
2440 StrSubclass('<abc>'))
2441
2442 def test_unicode_repr(self):
2443 class s1:
2444 def __repr__(self):
2445 return '\\n'
2446
2447 self.assertEqual(repr(s1()), '\\n')
2448
2449 def test_printable_repr(self):
2450 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
2451 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
2452
2453 # This test only affects 32-bit platforms because expandtabs can only take
2454 # an int as the max value, not a 64-bit C long. If expandtabs is changed
2455 # to take a 64-bit long, this test should apply to all platforms.
2456 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
2457 'only applies to 32-bit platforms')
2458 def test_expandtabs_overflows_gracefully(self):
2459 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
2460
2461 @support.cpython_only
2462 def test_expandtabs_optimization(self):
2463 s = 'abc'
2464 self.assertIs(s.expandtabs(), s)
2465
2466 @support.cpython_only
2467 def test_raiseMemError(self):
2468 asciifields = "nnbP"
2469 compactfields = asciifields + "nPn"
2470 ascii_struct_size = support.calcobjsize(asciifields)
2471 compact_struct_size = support.calcobjsize(compactfields)
2472
2473 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
2474 code = ord(char)
2475 if code < 0x80:
2476 char_size = 1 # sizeof(Py_UCS1)
2477 struct_size = ascii_struct_size
2478 elif code < 0x100:
2479 char_size = 1 # sizeof(Py_UCS1)
2480 struct_size = compact_struct_size
2481 elif code < 0x10000:
2482 char_size = 2 # sizeof(Py_UCS2)
2483 struct_size = compact_struct_size
2484 else:
2485 char_size = 4 # sizeof(Py_UCS4)
2486 struct_size = compact_struct_size
2487 # Note: sys.maxsize is half of the actual max allocation because of
2488 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2489 # be allocatable, given enough memory.
2490 maxlen = ((sys.maxsize - struct_size) // char_size)
2491 alloc = lambda: char * maxlen
2492 with self.subTest(
2493 char=char,
2494 struct_size=struct_size,
2495 char_size=char_size
2496 ):
2497 # self-check
2498 self.assertEqual(
2499 sys.getsizeof(char * 42),
2500 struct_size + (char_size * (42 + 1))
2501 )
2502 self.assertRaises(MemoryError, alloc)
2503 self.assertRaises(MemoryError, alloc)
2504
2505 def test_format_subclass(self):
2506 class S(str):
2507 def __str__(self):
2508 return '__str__ overridden'
2509 s = S('xxx')
2510 self.assertEqual("%s" % s, '__str__ overridden')
2511 self.assertEqual("{}".format(s), '__str__ overridden')
2512
2513 def test_subclass_add(self):
2514 class S(str):
2515 def __add__(self, o):
2516 return "3"
2517 self.assertEqual(S("4") + S("5"), "3")
2518 class S(str):
2519 def __iadd__(self, o):
2520 return "3"
2521 s = S("1")
2522 s += "4"
2523 self.assertEqual(s, "3")
2524
2525 def test_getnewargs(self):
2526 text = 'abc'
2527 args = text.__getnewargs__()
2528 # PyPy: the objects are the same
2529 # self.assertIsNot(args[0], text)
2530 self.assertEqual(args[0], text)
2531 self.assertEqual(len(args), 1)
2532
2533 @support.cpython_only
2534 @support.requires_legacy_unicode_capi
2535 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
2536 def test_resize(self):
2537 for length in range(1, 100, 7):
2538 # generate a fresh string (refcount=1)
2539 text = 'a' * length + 'b'
2540
2541 # fill wstr internal field
2542 with self.assertWarns(DeprecationWarning):
2543 abc = _testcapi.getargs_u(text)
2544 self.assertEqual(abc, text)
2545
2546 # resize text: wstr field must be cleared and then recomputed
2547 text += 'c'
2548 with self.assertWarns(DeprecationWarning):
2549 abcdef = _testcapi.getargs_u(text)
2550 self.assertNotEqual(abc, abcdef)
2551 self.assertEqual(abcdef, text)
2552
2553 def test_compare(self):
2554 # Issue #17615
2555 N = 10
2556 ascii = 'a' * N
2557 ascii2 = 'z' * N
2558 latin = '\x80' * N
2559 latin2 = '\xff' * N
2560 bmp = '\u0100' * N
2561 bmp2 = '\uffff' * N
2562 astral = '\U00100000' * N
2563 astral2 = '\U0010ffff' * N
2564 strings = (
2565 ascii, ascii2,
2566 latin, latin2,
2567 bmp, bmp2,
2568 astral, astral2)
2569 for text1, text2 in itertools.combinations(strings, 2):
2570 equal = (text1 is text2)
2571 self.assertEqual(text1 == text2, equal)
2572 self.assertEqual(text1 != text2, not equal)
2573
2574 if equal:
2575 self.assertTrue(text1 <= text2)
2576 self.assertTrue(text1 >= text2)
2577
2578 # text1 is text2: duplicate strings to skip the "str1 == str2"
2579 # optimization in unicode_compare_eq() and really compare
2580 # character per character
2581 copy1 = duplicate_string(text1)
2582 copy2 = duplicate_string(text2)
2583 self.assertIsNot(copy1, copy2)
2584
2585 self.assertTrue(copy1 == copy2)
2586 self.assertFalse(copy1 != copy2)
2587
2588 self.assertTrue(copy1 <= copy2)
2589 self.assertTrue(copy2 >= copy2)
2590
2591 self.assertTrue(ascii < ascii2)
2592 self.assertTrue(ascii < latin)
2593 self.assertTrue(ascii < bmp)
2594 self.assertTrue(ascii < astral)
2595 self.assertFalse(ascii >= ascii2)
2596 self.assertFalse(ascii >= latin)
2597 self.assertFalse(ascii >= bmp)
2598 self.assertFalse(ascii >= astral)
2599
2600 self.assertFalse(latin < ascii)
2601 self.assertTrue(latin < latin2)
2602 self.assertTrue(latin < bmp)
2603 self.assertTrue(latin < astral)
2604 self.assertTrue(latin >= ascii)
2605 self.assertFalse(latin >= latin2)
2606 self.assertFalse(latin >= bmp)
2607 self.assertFalse(latin >= astral)
2608
2609 self.assertFalse(bmp < ascii)
2610 self.assertFalse(bmp < latin)
2611 self.assertTrue(bmp < bmp2)
2612 self.assertTrue(bmp < astral)
2613 self.assertTrue(bmp >= ascii)
2614 self.assertTrue(bmp >= latin)
2615 self.assertFalse(bmp >= bmp2)
2616 self.assertFalse(bmp >= astral)
2617
2618 self.assertFalse(astral < ascii)
2619 self.assertFalse(astral < latin)
2620 self.assertFalse(astral < bmp2)
2621 self.assertTrue(astral < astral2)
2622 self.assertTrue(astral >= ascii)
2623 self.assertTrue(astral >= latin)
2624 self.assertTrue(astral >= bmp2)
2625 self.assertFalse(astral >= astral2)
2626
2627 def test_free_after_iterating(self):
2628 support.check_free_after_iterating(self, iter, str)
2629 support.check_free_after_iterating(self, reversed, str)
2630
2631 def test_check_encoding_errors(self):
2632 # bpo-37388: str(bytes) and str.decode() must check encoding and errors
2633 # arguments in dev mode
2634 encodings = ('ascii', 'utf8', 'latin1')
2635 invalid = 'Boom, Shaka Laka, Boom!'
2636 code = textwrap.dedent(f'''
2637 import sys
2638 encodings = {encodings!r}
2639
2640 for data in (b'', b'short string'):
2641 try:
2642 str(data, encoding={invalid!r})
2643 except LookupError:
2644 pass
2645 else:
2646 sys.exit(21)
2647
2648 try:
2649 str(data, errors={invalid!r})
2650 except LookupError:
2651 pass
2652 else:
2653 sys.exit(22)
2654
2655 for encoding in encodings:
2656 try:
2657 str(data, encoding, errors={invalid!r})
2658 except LookupError:
2659 pass
2660 else:
2661 sys.exit(22)
2662
2663 for data in ('', 'short string'):
2664 try:
2665 data.encode(encoding={invalid!r})
2666 except LookupError:
2667 pass
2668 else:
2669 sys.exit(23)
2670
2671 try:
2672 data.encode(errors={invalid!r})
2673 except LookupError:
2674 pass
2675 else:
2676 sys.exit(24)
2677
2678 for encoding in encodings:
2679 try:
2680 data.encode(encoding, errors={invalid!r})
2681 except LookupError:
2682 pass
2683 else:
2684 sys.exit(24)
2685
2686 sys.exit(10)
2687 ''')
2688 proc = assert_python_failure('-X', 'dev', '-c', code)
2689 self.assertEqual(proc.rc, 10, proc)
2690
2691
2692 class StringModuleTest(unittest.TestCase):
2693 def test_formatter_parser(self):
2694 def parse(format):
2695 return list(_string.formatter_parser(format))
2696
2697 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2698 self.assertEqual(formatter, [
2699 ('prefix ', '2', '', 's'),
2700 ('xxx', '0', '^+10.3f', None),
2701 ('', 'obj.attr', '', 's'),
2702 (' ', 'z[0]', '10', 's'),
2703 ])
2704
2705 formatter = parse("prefix {} suffix")
2706 self.assertEqual(formatter, [
2707 ('prefix ', '', '', None),
2708 (' suffix', None, None, None),
2709 ])
2710
2711 formatter = parse("str")
2712 self.assertEqual(formatter, [
2713 ('str', None, None, None),
2714 ])
2715
2716 formatter = parse("")
2717 self.assertEqual(formatter, [])
2718
2719 formatter = parse("{0}")
2720 self.assertEqual(formatter, [
2721 ('', '0', '', None),
2722 ])
2723
2724 self.assertRaises(TypeError, _string.formatter_parser, 1)
2725
2726 def test_formatter_field_name_split(self):
2727 def split(name):
2728 items = list(_string.formatter_field_name_split(name))
2729 items[1] = list(items[1])
2730 return items
2731 self.assertEqual(split("obj"), ["obj", []])
2732 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
2733 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
2734 self.assertEqual(split("obj.arg[key1][key2]"), [
2735 "obj",
2736 [(True, 'arg'),
2737 (False, 'key1'),
2738 (False, 'key2'),
2739 ]])
2740 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
2741
2742 def test_str_subclass_attr(self):
2743
2744 name = StrSubclass("name")
2745 name2 = StrSubclass("name2")
2746 class Bag:
2747 pass
2748
2749 o = Bag()
2750 with self.assertRaises(AttributeError):
2751 delattr(o, name)
2752 setattr(o, name, 1)
2753 self.assertEqual(o.name, 1)
2754 o.name = 2
2755 self.assertEqual(list(o.__dict__), [name])
2756
2757 with self.assertRaises(AttributeError):
2758 delattr(o, name2)
2759 with self.assertRaises(AttributeError):
2760 del o.name2
2761 setattr(o, name2, 3)
2762 self.assertEqual(o.name2, 3)
2763 o.name2 = 4
2764 self.assertEqual(list(o.__dict__), [name, name2])
2765
2766
2767 if __name__ == "__main__":
2768 unittest.main()