blob: 59697935fe5cd841c42a2f27178bdaf41d5a1392 [file] [log] [blame]
Guido van Rossuma831cac2000-03-10 23:23:21 +00001""" Test script for the Unicode implementation.
2
Guido van Rossuma831cac2000-03-10 23:23:21 +00003Written by Marc-Andre Lemburg (mal@lemburg.com).
4
5(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
6
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03007"""
Victor Stinner040e16e2011-11-15 22:44:05 +01008import _string
Guido van Rossum98297ee2007-11-06 21:34:58 +00009import codecs
Victor Stinner9fc59812013-04-08 22:34:43 +020010import itertools
Ethan Furman9ab74802014-03-21 06:38:46 -070011import operator
Guido van Rossum98297ee2007-11-06 21:34:58 +000012import struct
13import sys
Victor Stinner22eb6892019-06-26 00:51:05 +020014import textwrap
Greg Price6bccbe72019-08-14 04:05:19 -070015import unicodedata
Guido van Rossum98297ee2007-11-06 21:34:58 +000016import unittest
17import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000018from test import support, string_tests
Victor Stinner22eb6892019-06-26 00:51:05 +020019from test.support.script_helper import assert_python_failure
Guido van Rossuma831cac2000-03-10 23:23:21 +000020
Neal Norwitz430f68b2005-11-24 22:00:56 +000021# Error handling (bad decoder return)
22def search_function(encoding):
23 def decode1(input, errors="strict"):
24 return 42 # not a tuple
25 def encode1(input, errors="strict"):
26 return 42 # not a tuple
27 def encode2(input, errors="strict"):
28 return (42, 42) # no unicode
29 def decode2(input, errors="strict"):
30 return (42, 42) # no unicode
31 if encoding=="test.unicode1":
32 return (encode1, decode1, None, None)
33 elif encoding=="test.unicode2":
34 return (encode2, decode2, None, None)
35 else:
36 return None
37codecs.register(search_function)
38
Victor Stinner9fc59812013-04-08 22:34:43 +020039def duplicate_string(text):
40 """
41 Try to get a fresh clone of the specified text:
42 new object with a reference count of 1.
43
44 This is a best-effort: latin1 single letters and the empty
45 string ('') are singletons and cannot be cloned.
46 """
47 return text.encode().decode()
48
Serhiy Storchaka15095802015-11-25 15:47:01 +020049class StrSubclass(str):
50 pass
51
Brett Cannon226b2302010-03-20 22:22:22 +000052class UnicodeTest(string_tests.CommonTest,
53 string_tests.MixinStrUnicodeUserStringTest,
Ezio Melotti0dceb562013-01-10 07:43:26 +020054 string_tests.MixinStrUnicodeTest,
55 unittest.TestCase):
Brett Cannon226b2302010-03-20 22:22:22 +000056
Guido van Rossumef87d6e2007-05-02 19:09:54 +000057 type2test = str
Walter Dörwald0fd583c2003-02-21 12:53:50 +000058
59 def checkequalnofix(self, result, object, methodname, *args):
60 method = getattr(object, methodname)
61 realresult = method(*args)
62 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000063 self.assertTrue(type(realresult) is type(result))
Walter Dörwald0fd583c2003-02-21 12:53:50 +000064
65 # if the original is returned make sure that
66 # this doesn't happen with subclasses
67 if realresult is object:
Guido van Rossumef87d6e2007-05-02 19:09:54 +000068 class usub(str):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000069 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000070 return 'usub(%r)' % str.__repr__(self)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000071 object = usub(object)
72 method = getattr(object, methodname)
73 realresult = method(*args)
74 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000075 self.assertTrue(object is not realresult)
Guido van Rossume4874ae2001-09-21 15:36:41 +000076
Jeremy Hylton504de6b2003-10-06 05:08:26 +000077 def test_literals(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000078 self.assertEqual('\xff', '\u00ff')
79 self.assertEqual('\uffff', '\U0000ffff')
Guido van Rossum36e0a922007-07-20 04:05:57 +000080 self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
81 self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
82 self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
Benjamin Petersoncd76c272008-04-05 15:09:30 +000083 # raw strings should not have unicode escapes
Florent Xiclunaa87b3832010-09-13 02:28:18 +000084 self.assertNotEqual(r"\u0020", " ")
Jeremy Hylton504de6b2003-10-06 05:08:26 +000085
Georg Brandl559e5d72008-06-11 18:37:52 +000086 def test_ascii(self):
87 if not sys.platform.startswith('java'):
88 # Test basic sanity of repr()
89 self.assertEqual(ascii('abc'), "'abc'")
90 self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
91 self.assertEqual(ascii('ab\\'), "'ab\\\\'")
92 self.assertEqual(ascii('\\c'), "'\\\\c'")
93 self.assertEqual(ascii('\\'), "'\\\\'")
94 self.assertEqual(ascii('\n'), "'\\n'")
95 self.assertEqual(ascii('\r'), "'\\r'")
96 self.assertEqual(ascii('\t'), "'\\t'")
97 self.assertEqual(ascii('\b'), "'\\x08'")
98 self.assertEqual(ascii("'\""), """'\\'"'""")
99 self.assertEqual(ascii("'\""), """'\\'"'""")
100 self.assertEqual(ascii("'"), '''"'"''')
101 self.assertEqual(ascii('"'), """'"'""")
102 latin1repr = (
103 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
104 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
105 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
106 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
107 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
108 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
109 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
110 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
111 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
112 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
113 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
114 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
115 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
116 "\\xfe\\xff'")
117 testrepr = ascii(''.join(map(chr, range(256))))
118 self.assertEqual(testrepr, latin1repr)
119 # Test ascii works on wide unicode escapes without overflow.
120 self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
121 ascii("\U00010000" * 39 + "\uffff" * 4096))
122
123 class WrongRepr:
124 def __repr__(self):
125 return b'byte-repr'
126 self.assertRaises(TypeError, ascii, WrongRepr())
127
Walter Dörwald28256f22003-01-19 16:59:20 +0000128 def test_repr(self):
129 if not sys.platform.startswith('java'):
130 # Test basic sanity of repr()
Walter Dörwald67e83882007-05-05 12:26:27 +0000131 self.assertEqual(repr('abc'), "'abc'")
132 self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
133 self.assertEqual(repr('ab\\'), "'ab\\\\'")
134 self.assertEqual(repr('\\c'), "'\\\\c'")
135 self.assertEqual(repr('\\'), "'\\\\'")
136 self.assertEqual(repr('\n'), "'\\n'")
137 self.assertEqual(repr('\r'), "'\\r'")
138 self.assertEqual(repr('\t'), "'\\t'")
139 self.assertEqual(repr('\b'), "'\\x08'")
140 self.assertEqual(repr("'\""), """'\\'"'""")
141 self.assertEqual(repr("'\""), """'\\'"'""")
142 self.assertEqual(repr("'"), '''"'"''')
143 self.assertEqual(repr('"'), """'"'""")
Walter Dörwald28256f22003-01-19 16:59:20 +0000144 latin1repr = (
Walter Dörwald67e83882007-05-05 12:26:27 +0000145 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
Walter Dörwald28256f22003-01-19 16:59:20 +0000146 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
147 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
148 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
149 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
150 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
Georg Brandl559e5d72008-06-11 18:37:52 +0000151 "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
152 "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
153 "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
154 "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
155 "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
156 "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
157 "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
158 "\xfe\xff'")
Guido van Rossum805365e2007-05-07 22:24:25 +0000159 testrepr = repr(''.join(map(chr, range(256))))
Walter Dörwald28256f22003-01-19 16:59:20 +0000160 self.assertEqual(testrepr, latin1repr)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000161 # Test repr works on wide unicode escapes without overflow.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000162 self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
163 repr("\U00010000" * 39 + "\uffff" * 4096))
Walter Dörwald28256f22003-01-19 16:59:20 +0000164
Georg Brandl559e5d72008-06-11 18:37:52 +0000165 class WrongRepr:
166 def __repr__(self):
167 return b'byte-repr'
168 self.assertRaises(TypeError, repr, WrongRepr())
169
Guido van Rossum49d6b072006-08-17 21:11:47 +0000170 def test_iterators(self):
171 # Make sure unicode objects have an __iter__ method
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000172 it = "\u1111\u2222\u3333".__iter__()
173 self.assertEqual(next(it), "\u1111")
174 self.assertEqual(next(it), "\u2222")
175 self.assertEqual(next(it), "\u3333")
Georg Brandla18af4e2007-04-21 15:47:16 +0000176 self.assertRaises(StopIteration, next, it)
Guido van Rossum49d6b072006-08-17 21:11:47 +0000177
Walter Dörwald28256f22003-01-19 16:59:20 +0000178 def test_count(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000179 string_tests.CommonTest.test_count(self)
180 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000181 self.checkequalnofix(3, 'aaa', 'count', 'a')
182 self.checkequalnofix(0, 'aaa', 'count', 'b')
183 self.checkequalnofix(3, 'aaa', 'count', 'a')
184 self.checkequalnofix(0, 'aaa', 'count', 'b')
185 self.checkequalnofix(0, 'aaa', 'count', 'b')
186 self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
187 self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
188 self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
189 self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200190 # test mixed kinds
191 self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
192 self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
193 self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
194 self.checkequal(0, 'a' * 10, 'count', '\u0102')
195 self.checkequal(0, 'a' * 10, 'count', '\U00100304')
196 self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
197 self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
198 self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
199 self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
200 self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
201 self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
202 self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000203
Walter Dörwald28256f22003-01-19 16:59:20 +0000204 def test_find(self):
Antoine Pitrouc0bbe7d2011-10-08 22:41:35 +0200205 string_tests.CommonTest.test_find(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200206 # test implementation details of the memchr fast path
207 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
208 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
209 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
210 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
211 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
212 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
213 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
214 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000215 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
216 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
217 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000218
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000219 self.assertRaises(TypeError, 'hello'.find)
220 self.assertRaises(TypeError, 'hello'.find, 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200221 # test mixed kinds
222 self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
223 self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
224 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
225 self.checkequal(-1, 'a' * 100, 'find', '\u0102')
226 self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
227 self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
228 self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
229 self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
230 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
231 self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
232 self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
233 self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000234
Walter Dörwald28256f22003-01-19 16:59:20 +0000235 def test_rfind(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000236 string_tests.CommonTest.test_rfind(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200237 # test implementation details of the memrchr fast path
238 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
239 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
240 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
241 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
242 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
243 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
244 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000245 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000246 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
247 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
248 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200249 # test mixed kinds
250 self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
251 self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
252 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
253 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
254 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
255 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
256 self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
257 self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
258 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
259 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
260 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
261 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
Guido van Rossum8b264542000-12-19 02:22:31 +0000262
Walter Dörwald28256f22003-01-19 16:59:20 +0000263 def test_index(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000264 string_tests.CommonTest.test_index(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000265 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
266 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
267 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
268 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
269 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
270 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
271 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
272 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200273 # test mixed kinds
274 self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
275 self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
276 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
277 self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
278 self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
279 self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
280 self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
281 self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
282 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
283 self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
284 self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
285 self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000286
Walter Dörwald28256f22003-01-19 16:59:20 +0000287 def test_rindex(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000288 string_tests.CommonTest.test_rindex(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000289 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
290 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
291 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
292 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000293
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000294 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
295 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
296 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
297 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
298 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200299 # test mixed kinds
300 self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
301 self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
302 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
303 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
304 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
305 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
306 self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
307 self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
308 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
309 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
310 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
311 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000312
Georg Brandlceee0772007-11-27 23:48:05 +0000313 def test_maketrans_translate(self):
314 # these work with plain translate()
315 self.checkequalnofix('bbbc', 'abababc', 'translate',
316 {ord('a'): None})
317 self.checkequalnofix('iiic', 'abababc', 'translate',
318 {ord('a'): None, ord('b'): ord('i')})
319 self.checkequalnofix('iiix', 'abababc', 'translate',
320 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
321 self.checkequalnofix('c', 'abababc', 'translate',
322 {ord('a'): None, ord('b'): ''})
323 self.checkequalnofix('xyyx', 'xzx', 'translate',
324 {ord('z'): 'yy'})
Victor Stinner5a29f252014-04-05 00:17:51 +0200325
Georg Brandlceee0772007-11-27 23:48:05 +0000326 # this needs maketrans()
327 self.checkequalnofix('abababc', 'abababc', 'translate',
328 {'b': '<i>'})
329 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
330 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
331 # test alternative way of calling maketrans()
332 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
333 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
334
Victor Stinner5a29f252014-04-05 00:17:51 +0200335 # various tests switching from ASCII to latin1 or the opposite;
336 # same length, remove a letter, or replace with a longer string.
337 self.assertEqual("[a]".translate(str.maketrans('a', 'X')),
338 "[X]")
339 self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})),
340 "[X]")
341 self.assertEqual("[a]".translate(str.maketrans({'a': None})),
342 "[]")
343 self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})),
344 "[XXX]")
345 self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})),
346 "[\xe9]")
Victor Stinner33798672016-03-01 21:59:58 +0100347 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})),
348 "x123")
349 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})),
350 "x\xe9")
351
352 # test non-ASCII (don't take the fast-path)
Victor Stinner5a29f252014-04-05 00:17:51 +0200353 self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})),
354 "[<\xe9>]")
355 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})),
356 "[a]")
357 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})),
358 "[]")
Victor Stinner33798672016-03-01 21:59:58 +0100359 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})),
360 "[123]")
361 self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})),
362 "[<\u20ac>\xe9]")
Victor Stinner5a29f252014-04-05 00:17:51 +0200363
Victor Stinner4ff33af2014-04-05 11:56:37 +0200364 # invalid Unicode characters
365 invalid_char = 0x10ffff+1
366 for before in "a\xe9\u20ac\U0010ffff":
367 mapping = str.maketrans({before: invalid_char})
368 text = "[%s]" % before
369 self.assertRaises(ValueError, text.translate, mapping)
370
371 # errors
Georg Brandlceee0772007-11-27 23:48:05 +0000372 self.assertRaises(TypeError, self.type2test.maketrans)
373 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
374 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
375 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
376 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
377 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
378 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
Guido van Rossuma831cac2000-03-10 23:23:21 +0000379
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000380 self.assertRaises(TypeError, 'hello'.translate)
Walter Dörwald67e83882007-05-05 12:26:27 +0000381 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000382
Walter Dörwald28256f22003-01-19 16:59:20 +0000383 def test_split(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000384 string_tests.CommonTest.test_split(self)
Andrew M. Kuchlingeddd68d2002-03-29 16:21:44 +0000385
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200386 # test mixed kinds
387 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
388 left *= 9
389 right *= 9
390 for delim in ('c', '\u0102', '\U00010302'):
391 self.checkequal([left + right],
392 left + right, 'split', delim)
393 self.checkequal([left, right],
394 left + delim + right, 'split', delim)
395 self.checkequal([left + right],
396 left + right, 'split', delim * 2)
397 self.checkequal([left, right],
398 left + delim * 2 + right, 'split', delim *2)
399
400 def test_rsplit(self):
401 string_tests.CommonTest.test_rsplit(self)
402 # test mixed kinds
403 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
404 left *= 9
405 right *= 9
406 for delim in ('c', '\u0102', '\U00010302'):
407 self.checkequal([left + right],
408 left + right, 'rsplit', delim)
409 self.checkequal([left, right],
410 left + delim + right, 'rsplit', delim)
411 self.checkequal([left + right],
412 left + right, 'rsplit', delim * 2)
413 self.checkequal([left, right],
414 left + delim * 2 + right, 'rsplit', delim *2)
415
416 def test_partition(self):
417 string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
418 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300419 self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200420 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
421 left *= 9
422 right *= 9
423 for delim in ('c', '\u0102', '\U00010302'):
424 self.checkequal((left + right, '', ''),
425 left + right, 'partition', delim)
426 self.checkequal((left, delim, right),
427 left + delim + right, 'partition', delim)
428 self.checkequal((left + right, '', ''),
429 left + right, 'partition', delim * 2)
430 self.checkequal((left, delim * 2, right),
431 left + delim * 2 + right, 'partition', delim * 2)
432
433 def test_rpartition(self):
434 string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
435 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300436 self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200437 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
438 left *= 9
439 right *= 9
440 for delim in ('c', '\u0102', '\U00010302'):
441 self.checkequal(('', '', left + right),
442 left + right, 'rpartition', delim)
443 self.checkequal((left, delim, right),
444 left + delim + right, 'rpartition', delim)
445 self.checkequal(('', '', left + right),
446 left + right, 'rpartition', delim * 2)
447 self.checkequal((left, delim * 2, right),
448 left + delim * 2 + right, 'rpartition', delim * 2)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000449
Walter Dörwald28256f22003-01-19 16:59:20 +0000450 def test_join(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000451 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +0000452
Guido van Rossumf1044292007-09-27 18:01:22 +0000453 class MyWrapper:
454 def __init__(self, sval): self.sval = sval
455 def __str__(self): return self.sval
456
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000457 # mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000458 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
459 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
460 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
461 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
462 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
463 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
464 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000465 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
466 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
467 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
468 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
Marc-André Lemburge5034372000-08-08 08:04:29 +0000469
Martin Panterb71c0952017-01-12 11:54:59 +0000470 @unittest.skipIf(sys.maxsize > 2**32,
471 'needs too much memory on a 64-bit platform')
472 def test_join_overflow(self):
473 size = int(sys.maxsize**0.5) + 1
474 seq = ('A' * size,) * size
475 self.assertRaises(OverflowError, ''.join, seq)
476
Walter Dörwald28256f22003-01-19 16:59:20 +0000477 def test_replace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000478 string_tests.CommonTest.test_replace(self)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000479
Walter Dörwald28256f22003-01-19 16:59:20 +0000480 # method call forwarded from str implementation because of unicode argument
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000481 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
482 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200483 # test mixed kinds
484 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
485 left *= 9
486 right *= 9
487 for delim in ('c', '\u0102', '\U00010302'):
488 for repl in ('d', '\u0103', '\U00010303'):
489 self.checkequal(left + right,
490 left + right, 'replace', delim, repl)
491 self.checkequal(left + repl + right,
492 left + delim + right,
493 'replace', delim, repl)
494 self.checkequal(left + right,
495 left + right, 'replace', delim * 2, repl)
496 self.checkequal(left + repl + right,
497 left + delim * 2 + right,
498 'replace', delim * 2, repl)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000499
Victor Stinner59de0ee2011-10-07 10:01:28 +0200500 @support.cpython_only
501 def test_replace_id(self):
Victor Stinner1d972ad2011-10-07 13:31:46 +0200502 pattern = 'abc'
503 text = 'abc def'
504 self.assertIs(text.replace(pattern, pattern), text)
Victor Stinner59de0ee2011-10-07 10:01:28 +0200505
Guido van Rossum98297ee2007-11-06 21:34:58 +0000506 def test_bytes_comparison(self):
Brett Cannon226b2302010-03-20 22:22:22 +0000507 with support.check_warnings():
508 warnings.simplefilter('ignore', BytesWarning)
509 self.assertEqual('abc' == b'abc', False)
510 self.assertEqual('abc' != b'abc', True)
511 self.assertEqual('abc' == bytearray(b'abc'), False)
512 self.assertEqual('abc' != bytearray(b'abc'), True)
Brett Cannon40430012007-10-22 20:24:51 +0000513
Walter Dörwald28256f22003-01-19 16:59:20 +0000514 def test_comparison(self):
515 # Comparisons:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000516 self.assertEqual('abc', 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000517 self.assertTrue('abcd' > 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000518 self.assertTrue('abc' < 'abcd')
Walter Dörwald28256f22003-01-19 16:59:20 +0000519
520 if 0:
521 # Move these tests to a Unicode collation module test...
522 # Testing UTF-16 code point order comparisons...
523
524 # No surrogates, no fixup required.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000525 self.assertTrue('\u0061' < '\u20ac')
Walter Dörwald28256f22003-01-19 16:59:20 +0000526 # Non surrogate below surrogate value, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000527 self.assertTrue('\u0061' < '\ud800\udc02')
Walter Dörwald28256f22003-01-19 16:59:20 +0000528
529 # Non surrogate above surrogate value, fixup required
530 def test_lecmp(s, s2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000531 self.assertTrue(s < s2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000532
533 def test_fixup(s):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000534 s2 = '\ud800\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000535 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000536 s2 = '\ud900\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000537 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000538 s2 = '\uda00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000539 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000540 s2 = '\udb00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000541 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000542 s2 = '\ud800\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000543 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000544 s2 = '\ud900\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000545 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000546 s2 = '\uda00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000547 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000548 s2 = '\udb00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000549 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000550 s2 = '\ud800\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000551 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000552 s2 = '\ud900\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000553 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000554 s2 = '\uda00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000555 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000556 s2 = '\udb00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000557 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000558 s2 = '\ud800\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000559 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000560 s2 = '\ud900\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000561 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000562 s2 = '\uda00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000563 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000564 s2 = '\udb00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000565 test_lecmp(s, s2)
566
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000567 test_fixup('\ue000')
568 test_fixup('\uff61')
Walter Dörwald28256f22003-01-19 16:59:20 +0000569
570 # Surrogates on both sides, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000571 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
Walter Dörwald28256f22003-01-19 16:59:20 +0000572
Walter Dörwald28256f22003-01-19 16:59:20 +0000573 def test_islower(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000574 super().test_islower()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000575 self.checkequalnofix(False, '\u1FFc', 'islower')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500576 self.assertFalse('\u2167'.islower())
577 self.assertTrue('\u2177'.islower())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300578 # non-BMP, uppercase
579 self.assertFalse('\U00010401'.islower())
580 self.assertFalse('\U00010427'.islower())
581 # non-BMP, lowercase
582 self.assertTrue('\U00010429'.islower())
583 self.assertTrue('\U0001044E'.islower())
584 # non-BMP, non-cased
585 self.assertFalse('\U0001F40D'.islower())
586 self.assertFalse('\U0001F46F'.islower())
Walter Dörwald28256f22003-01-19 16:59:20 +0000587
588 def test_isupper(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000589 super().test_isupper()
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000590 if not sys.platform.startswith('java'):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000591 self.checkequalnofix(False, '\u1FFc', 'isupper')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500592 self.assertTrue('\u2167'.isupper())
593 self.assertFalse('\u2177'.isupper())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300594 # non-BMP, uppercase
595 self.assertTrue('\U00010401'.isupper())
596 self.assertTrue('\U00010427'.isupper())
597 # non-BMP, lowercase
598 self.assertFalse('\U00010429'.isupper())
599 self.assertFalse('\U0001044E'.isupper())
600 # non-BMP, non-cased
601 self.assertFalse('\U0001F40D'.isupper())
602 self.assertFalse('\U0001F46F'.isupper())
Walter Dörwald28256f22003-01-19 16:59:20 +0000603
604 def test_istitle(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000605 super().test_istitle()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000606 self.checkequalnofix(True, '\u1FFc', 'istitle')
607 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
Walter Dörwald28256f22003-01-19 16:59:20 +0000608
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300609 # non-BMP, uppercase + lowercase
610 self.assertTrue('\U00010401\U00010429'.istitle())
611 self.assertTrue('\U00010427\U0001044E'.istitle())
612 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
613 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
614 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
615
Walter Dörwald28256f22003-01-19 16:59:20 +0000616 def test_isspace(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000617 super().test_isspace()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000618 self.checkequalnofix(True, '\u2000', 'isspace')
619 self.checkequalnofix(True, '\u200a', 'isspace')
620 self.checkequalnofix(False, '\u2014', 'isspace')
Greg Price6bccbe72019-08-14 04:05:19 -0700621 # There are no non-BMP whitespace chars as of Unicode 12.
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300622 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
623 '\U0001F40D', '\U0001F46F']:
624 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
625
Greg Price6bccbe72019-08-14 04:05:19 -0700626 @support.requires_resource('cpu')
627 def test_isspace_invariant(self):
628 for codepoint in range(sys.maxunicode + 1):
629 char = chr(codepoint)
630 bidirectional = unicodedata.bidirectional(char)
631 category = unicodedata.category(char)
632 self.assertEqual(char.isspace(),
633 (bidirectional in ('WS', 'B', 'S')
634 or category == 'Zs'))
635
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300636 def test_isalnum(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000637 super().test_isalnum()
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300638 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
639 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
640 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
Walter Dörwald28256f22003-01-19 16:59:20 +0000641
642 def test_isalpha(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000643 super().test_isalpha()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000644 self.checkequalnofix(True, '\u1FFc', 'isalpha')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300645 # non-BMP, cased
646 self.assertTrue('\U00010401'.isalpha())
647 self.assertTrue('\U00010427'.isalpha())
648 self.assertTrue('\U00010429'.isalpha())
649 self.assertTrue('\U0001044E'.isalpha())
650 # non-BMP, non-cased
651 self.assertFalse('\U0001F40D'.isalpha())
652 self.assertFalse('\U0001F46F'.isalpha())
Walter Dörwald28256f22003-01-19 16:59:20 +0000653
INADA Naokia49ac992018-01-27 14:06:21 +0900654 def test_isascii(self):
655 super().test_isascii()
656 self.assertFalse("\u20ac".isascii())
657 self.assertFalse("\U0010ffff".isascii())
658
Walter Dörwald28256f22003-01-19 16:59:20 +0000659 def test_isdecimal(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000660 self.checkequalnofix(False, '', 'isdecimal')
661 self.checkequalnofix(False, 'a', 'isdecimal')
662 self.checkequalnofix(True, '0', 'isdecimal')
663 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
664 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
665 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
666 self.checkequalnofix(True, '0123456789', 'isdecimal')
667 self.checkequalnofix(False, '0123456789a', 'isdecimal')
Walter Dörwald28256f22003-01-19 16:59:20 +0000668
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000669 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000670
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300671 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
672 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
673 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
674 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
675 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
676
Walter Dörwald28256f22003-01-19 16:59:20 +0000677 def test_isdigit(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000678 super().test_isdigit()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000679 self.checkequalnofix(True, '\u2460', 'isdigit')
680 self.checkequalnofix(False, '\xbc', 'isdigit')
681 self.checkequalnofix(True, '\u0660', 'isdigit')
Walter Dörwald28256f22003-01-19 16:59:20 +0000682
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300683 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
684 '\U0001F40D', '\U0001F46F', '\U00011065']:
685 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
686 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
687 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
688
Walter Dörwald28256f22003-01-19 16:59:20 +0000689 def test_isnumeric(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000690 self.checkequalnofix(False, '', 'isnumeric')
691 self.checkequalnofix(False, 'a', 'isnumeric')
692 self.checkequalnofix(True, '0', 'isnumeric')
693 self.checkequalnofix(True, '\u2460', 'isnumeric')
694 self.checkequalnofix(True, '\xbc', 'isnumeric')
695 self.checkequalnofix(True, '\u0660', 'isnumeric')
696 self.checkequalnofix(True, '0123456789', 'isnumeric')
697 self.checkequalnofix(False, '0123456789a', 'isnumeric')
Walter Dörwald28256f22003-01-19 16:59:20 +0000698
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000699 self.assertRaises(TypeError, "abc".isnumeric, 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000700
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300701 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
702 '\U0001F40D', '\U0001F46F']:
703 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
704 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
705 '\U000104A0', '\U0001F107']:
706 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
707
Martin v. Löwis47383402007-08-15 07:32:56 +0000708 def test_isidentifier(self):
709 self.assertTrue("a".isidentifier())
710 self.assertTrue("Z".isidentifier())
711 self.assertTrue("_".isidentifier())
712 self.assertTrue("b0".isidentifier())
713 self.assertTrue("bc".isidentifier())
714 self.assertTrue("b_".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000715 self.assertTrue("µ".isidentifier())
Benjamin Petersonf413b802011-08-12 22:17:18 -0500716 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000717
718 self.assertFalse(" ".isidentifier())
719 self.assertFalse("[".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000720 self.assertFalse("©".isidentifier())
Georg Brandld52429f2008-07-04 15:55:02 +0000721 self.assertFalse("0".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000722
Serhiy Storchaka5650e762020-05-12 16:18:00 +0300723 @support.cpython_only
724 def test_isidentifier_legacy(self):
725 import _testcapi
726 u = '𝖀𝖓𝖎𝖈𝖔𝖉𝖊'
727 self.assertTrue(u.isidentifier())
Inada Naoki038dd0f2020-06-30 15:26:56 +0900728 with support.check_warnings():
729 warnings.simplefilter('ignore', DeprecationWarning)
730 self.assertTrue(_testcapi.unicode_legacy_string(u).isidentifier())
Serhiy Storchaka5650e762020-05-12 16:18:00 +0300731
Georg Brandl559e5d72008-06-11 18:37:52 +0000732 def test_isprintable(self):
733 self.assertTrue("".isprintable())
Benjamin Peterson09832742009-03-26 17:15:46 +0000734 self.assertTrue(" ".isprintable())
Georg Brandl559e5d72008-06-11 18:37:52 +0000735 self.assertTrue("abcdefg".isprintable())
736 self.assertFalse("abcdefg\n".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000737 # some defined Unicode character
738 self.assertTrue("\u0374".isprintable())
739 # undefined character
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000740 self.assertFalse("\u0378".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000741 # single surrogate character
Georg Brandl559e5d72008-06-11 18:37:52 +0000742 self.assertFalse("\ud800".isprintable())
743
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300744 self.assertTrue('\U0001F46F'.isprintable())
745 self.assertFalse('\U000E0020'.isprintable())
746
747 def test_surrogates(self):
748 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
749 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
750 self.assertTrue(s.islower())
751 self.assertFalse(s.isupper())
752 self.assertFalse(s.istitle())
753 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
754 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
755 self.assertFalse(s.islower())
756 self.assertTrue(s.isupper())
757 self.assertTrue(s.istitle())
758
759 for meth_name in ('islower', 'isupper', 'istitle'):
760 meth = getattr(str, meth_name)
761 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
762 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
763
764 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
765 'isdecimal', 'isnumeric',
766 'isidentifier', 'isprintable'):
767 meth = getattr(str, meth_name)
768 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
769 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
770 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
771 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
772
773
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300774 def test_lower(self):
775 string_tests.CommonTest.test_lower(self)
776 self.assertEqual('\U00010427'.lower(), '\U0001044F')
777 self.assertEqual('\U00010427\U00010427'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300778 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300779 self.assertEqual('\U00010427\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300780 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300781 self.assertEqual('X\U00010427x\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300782 'x\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500783 self.assertEqual('fi'.lower(), 'fi')
784 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
785 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
786 self.assertEqual('\u03a3'.lower(), '\u03c3')
787 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
788 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
789 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
790 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
791 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
792 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
793 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
794 self.assertEqual('\u2177'.lower(), '\u2177')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300795
Benjamin Petersond5890c82012-01-14 13:23:30 -0500796 def test_casefold(self):
797 self.assertEqual('hello'.casefold(), 'hello')
798 self.assertEqual('hELlo'.casefold(), 'hello')
799 self.assertEqual('ß'.casefold(), 'ss')
800 self.assertEqual('fi'.casefold(), 'fi')
801 self.assertEqual('\u03a3'.casefold(), '\u03c3')
802 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
Benjamin Peterson4eda9372012-08-05 15:05:34 -0700803 self.assertEqual('\u00b5'.casefold(), '\u03bc')
Benjamin Petersond5890c82012-01-14 13:23:30 -0500804
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300805 def test_upper(self):
806 string_tests.CommonTest.test_upper(self)
807 self.assertEqual('\U0001044F'.upper(), '\U00010427')
808 self.assertEqual('\U0001044F\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300809 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300810 self.assertEqual('\U00010427\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300811 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300812 self.assertEqual('X\U00010427x\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300813 'X\U00010427X\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500814 self.assertEqual('fi'.upper(), 'FI')
815 self.assertEqual('\u0130'.upper(), '\u0130')
816 self.assertEqual('\u03a3'.upper(), '\u03a3')
817 self.assertEqual('ß'.upper(), 'SS')
818 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
819 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
820 self.assertEqual('\u2177'.upper(), '\u2167')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300821
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300822 def test_capitalize(self):
823 string_tests.CommonTest.test_capitalize(self)
824 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
825 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300826 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300827 self.assertEqual('\U00010427\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300828 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300829 self.assertEqual('\U0001044F\U00010427'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300830 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300831 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300832 'X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500833 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
834 exp = '\u0399\u0308\u0300\u0069\u0307'
835 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
Kingsley Mb015fc82019-04-12 16:35:39 +0100836 self.assertEqual('finnish'.capitalize(), 'Finnish')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500837 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300838
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300839 def test_title(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000840 super().test_title()
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300841 self.assertEqual('\U0001044F'.title(), '\U00010427')
842 self.assertEqual('\U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300843 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300844 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300845 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300846 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300847 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300848 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300849 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300850 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300851 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500852 self.assertEqual('fiNNISH'.title(), 'Finnish')
853 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
854 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300855
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300856 def test_swapcase(self):
857 string_tests.CommonTest.test_swapcase(self)
858 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
859 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
860 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300861 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300862 self.assertEqual('\U00010427\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300863 '\U0001044F\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300864 self.assertEqual('\U0001044F\U00010427'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300865 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300866 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300867 'x\U0001044FX\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500868 self.assertEqual('fi'.swapcase(), 'FI')
869 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
870 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
871 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
872 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
873 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
874 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
875 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
876 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
877 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
878 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
879 self.assertEqual('ß'.swapcase(), 'SS')
880 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300881
Ezio Melottif84e01d2013-07-08 17:48:29 +0200882 def test_center(self):
883 string_tests.CommonTest.test_center(self)
884 self.assertEqual('x'.center(2, '\U0010FFFF'),
885 'x\U0010FFFF')
886 self.assertEqual('x'.center(3, '\U0010FFFF'),
887 '\U0010FFFFx\U0010FFFF')
888 self.assertEqual('x'.center(4, '\U0010FFFF'),
889 '\U0010FFFFx\U0010FFFF\U0010FFFF')
890
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400891 @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
Benjamin Peterson4d856892014-10-15 13:39:46 -0400892 @support.cpython_only
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400893 def test_case_operation_overflow(self):
894 # Issue #22643
Serhiy Storchaka411dfd82015-11-07 16:54:48 +0200895 size = 2**32//12 + 1
896 try:
897 s = "ü" * size
898 except MemoryError:
899 self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
900 try:
901 self.assertRaises(OverflowError, s.upper)
902 finally:
903 del s
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400904
Walter Dörwald28256f22003-01-19 16:59:20 +0000905 def test_contains(self):
906 # Testing Unicode contains method
Benjamin Peterson577473f2010-01-19 00:09:57 +0000907 self.assertIn('a', 'abdb')
908 self.assertIn('a', 'bdab')
909 self.assertIn('a', 'bdaba')
910 self.assertIn('a', 'bdba')
911 self.assertNotIn('a', 'bdb')
912 self.assertIn('a', 'bdba')
913 self.assertIn('a', ('a',1,None))
914 self.assertIn('a', (1,None,'a'))
915 self.assertIn('a', ('a',1,None))
916 self.assertIn('a', (1,None,'a'))
917 self.assertNotIn('a', ('x',1,'y'))
918 self.assertNotIn('a', ('x',1,None))
919 self.assertNotIn('abcd', 'abcxxxx')
920 self.assertIn('ab', 'abcd')
921 self.assertIn('ab', 'abc')
922 self.assertIn('ab', (1,None,'ab'))
923 self.assertIn('', 'abc')
924 self.assertIn('', '')
925 self.assertIn('', 'abc')
926 self.assertNotIn('\0', 'abc')
927 self.assertIn('\0', '\0abc')
928 self.assertIn('\0', 'abc\0')
929 self.assertIn('a', '\0abc')
930 self.assertIn('asdf', 'asdf')
931 self.assertNotIn('asdf', 'asd')
932 self.assertNotIn('asdf', '')
Walter Dörwald28256f22003-01-19 16:59:20 +0000933
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000934 self.assertRaises(TypeError, "abc".__contains__)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200935 # test mixed kinds
936 for fill in ('a', '\u0100', '\U00010300'):
937 fill *= 9
938 for delim in ('c', '\u0102', '\U00010302'):
939 self.assertNotIn(delim, fill)
940 self.assertIn(delim, fill + delim)
941 self.assertNotIn(delim * 2, fill)
942 self.assertIn(delim * 2, fill + delim * 2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000943
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +0300944 def test_issue18183(self):
945 '\U00010000\U00100000'.lower()
946 '\U00010000\U00100000'.casefold()
947 '\U00010000\U00100000'.upper()
948 '\U00010000\U00100000'.capitalize()
949 '\U00010000\U00100000'.title()
950 '\U00010000\U00100000'.swapcase()
951 '\U00100000'.center(3, '\U00010000')
952 '\U00100000'.ljust(3, '\U00010000')
953 '\U00100000'.rjust(3, '\U00010000')
954
Eric Smith8c663262007-08-25 02:26:07 +0000955 def test_format(self):
956 self.assertEqual(''.format(), '')
957 self.assertEqual('a'.format(), 'a')
958 self.assertEqual('ab'.format(), 'ab')
959 self.assertEqual('a{{'.format(), 'a{')
960 self.assertEqual('a}}'.format(), 'a}')
961 self.assertEqual('{{b'.format(), '{b')
962 self.assertEqual('}}b'.format(), '}b')
963 self.assertEqual('a{{b'.format(), 'a{b')
964
965 # examples from the PEP:
966 import datetime
967 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
968 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
969 "My name is Fred")
970 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
971 "My name is Fred :-{}")
972
973 d = datetime.date(2007, 8, 18)
974 self.assertEqual("The year is {0.year}".format(d),
975 "The year is 2007")
976
Eric Smith8c663262007-08-25 02:26:07 +0000977 # classes we'll use for testing
978 class C:
979 def __init__(self, x=100):
980 self._x = x
981 def __format__(self, spec):
982 return spec
983
984 class D:
985 def __init__(self, x):
986 self.x = x
987 def __format__(self, spec):
988 return str(self.x)
989
990 # class with __str__, but no __format__
991 class E:
992 def __init__(self, x):
993 self.x = x
994 def __str__(self):
995 return 'E(' + self.x + ')'
996
997 # class with __repr__, but no __format__ or __str__
998 class F:
999 def __init__(self, x):
1000 self.x = x
1001 def __repr__(self):
1002 return 'F(' + self.x + ')'
1003
1004 # class with __format__ that forwards to string, for some format_spec's
1005 class G:
1006 def __init__(self, x):
1007 self.x = x
1008 def __str__(self):
1009 return "string is " + self.x
1010 def __format__(self, format_spec):
1011 if format_spec == 'd':
1012 return 'G(' + self.x + ')'
1013 return object.__format__(self, format_spec)
1014
Eric Smith739e2ad2007-08-27 19:07:22 +00001015 class I(datetime.date):
1016 def __format__(self, format_spec):
1017 return self.strftime(format_spec)
1018
Eric Smith185e30c2007-08-30 22:23:08 +00001019 class J(int):
1020 def __format__(self, format_spec):
1021 return int.__format__(self * 2, format_spec)
1022
Guido van Rossum97c1adf2016-08-18 09:22:23 -07001023 class M:
1024 def __init__(self, x):
1025 self.x = x
1026 def __repr__(self):
1027 return 'M(' + self.x + ')'
1028 __str__ = None
1029
1030 class N:
1031 def __init__(self, x):
1032 self.x = x
1033 def __repr__(self):
1034 return 'N(' + self.x + ')'
1035 __format__ = None
Eric Smith8c663262007-08-25 02:26:07 +00001036
1037 self.assertEqual(''.format(), '')
1038 self.assertEqual('abc'.format(), 'abc')
1039 self.assertEqual('{0}'.format('abc'), 'abc')
1040 self.assertEqual('{0:}'.format('abc'), 'abc')
1041# self.assertEqual('{ 0 }'.format('abc'), 'abc')
1042 self.assertEqual('X{0}'.format('abc'), 'Xabc')
1043 self.assertEqual('{0}X'.format('abc'), 'abcX')
1044 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
1045 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
1046 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
1047 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
1048 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
1049 self.assertEqual('{0}'.format(-15), '-15')
1050 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
1051 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
1052 self.assertEqual('{{'.format(), '{')
1053 self.assertEqual('}}'.format(), '}')
1054 self.assertEqual('{{}}'.format(), '{}')
1055 self.assertEqual('{{x}}'.format(), '{x}')
1056 self.assertEqual('{{{0}}}'.format(123), '{123}')
1057 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
1058 self.assertEqual('}}{{'.format(), '}{')
1059 self.assertEqual('}}x{{'.format(), '}x{')
1060
Eric Smith7ade6482007-08-26 22:27:13 +00001061 # weird field names
1062 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
1063 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
Eric Smith4cb4e4e2007-09-03 08:40:29 +00001064 self.assertEqual("{0[ ]}".format({' ':3}), '3')
Eric Smith7ade6482007-08-26 22:27:13 +00001065
Eric Smith8c663262007-08-25 02:26:07 +00001066 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
1067 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
1068 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
1069 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
1070 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
1071 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
1072 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
1073
Eric Smith8c663262007-08-25 02:26:07 +00001074 # strings
1075 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
1076 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
1077 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
1078 self.assertEqual('{0:.0s}'.format('abcdef'), '')
1079 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
1080 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
1081 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
1082 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
1083 self.assertEqual('{0:x<0s}'.format('result'), 'result')
1084 self.assertEqual('{0:x<5s}'.format('result'), 'result')
1085 self.assertEqual('{0:x<6s}'.format('result'), 'result')
1086 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
1087 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
1088 self.assertEqual('{0: <7s}'.format('result'), 'result ')
1089 self.assertEqual('{0:<7s}'.format('result'), 'result ')
1090 self.assertEqual('{0:>7s}'.format('result'), ' result')
1091 self.assertEqual('{0:>8s}'.format('result'), ' result')
1092 self.assertEqual('{0:^8s}'.format('result'), ' result ')
1093 self.assertEqual('{0:^9s}'.format('result'), ' result ')
1094 self.assertEqual('{0:^10s}'.format('result'), ' result ')
1095 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
1096 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
1097 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
1098
Eric V. Smith2ea97122014-04-14 11:55:10 -04001099 # issue 12546: use \x00 as a fill character
1100 self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
1101 self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
1102 self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
1103 self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
1104
1105 self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
1106 self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
1107 self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
1108 self.assertEqual('{0:<6}'.format(3), '3 ')
1109
1110 self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
1111 self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
1112 self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
1113 self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
1114
1115 self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
1116 self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
1117 self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
1118 self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
1119
Eric Smith8c663262007-08-25 02:26:07 +00001120 # format specifiers for user defined type
1121 self.assertEqual('{0:abc}'.format(C()), 'abc')
1122
Georg Brandld52429f2008-07-04 15:55:02 +00001123 # !r, !s and !a coercions
Eric Smith8c663262007-08-25 02:26:07 +00001124 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
1125 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
1126 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
1127 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
1128 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
1129 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
1130 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001131 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001132 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
1133 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
Georg Brandl559e5d72008-06-11 18:37:52 +00001134 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001135 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001136 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
Georg Brandl559e5d72008-06-11 18:37:52 +00001137 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
1138 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
Georg Brandld52429f2008-07-04 15:55:02 +00001139 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
Eric Smith8c663262007-08-25 02:26:07 +00001140
Eric Smith8c663262007-08-25 02:26:07 +00001141 # test fallback to object.__format__
1142 self.assertEqual('{0}'.format({}), '{}')
1143 self.assertEqual('{0}'.format([]), '[]')
1144 self.assertEqual('{0}'.format([1]), '[1]')
Eric Smithe4d63172010-09-13 20:48:43 +00001145
Eric Smith8c663262007-08-25 02:26:07 +00001146 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
Eric Smith8c663262007-08-25 02:26:07 +00001147 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
1148
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02001149 self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
1150 self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
1151 self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
Eric Smithe4d63172010-09-13 20:48:43 +00001152
Eric Smith739e2ad2007-08-27 19:07:22 +00001153 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
1154 month=8,
1155 day=27)),
1156 "date: 2007-08-27")
1157
Eric Smith185e30c2007-08-30 22:23:08 +00001158 # test deriving from a builtin type and overriding __format__
1159 self.assertEqual("{0}".format(J(10)), "20")
1160
1161
Eric Smith8c663262007-08-25 02:26:07 +00001162 # string format specifiers
1163 self.assertEqual('{0:}'.format('a'), 'a')
1164
1165 # computed format specifiers
1166 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
1167 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
1168 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
1169 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
1170 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
1171
1172 # test various errors
1173 self.assertRaises(ValueError, '{'.format)
1174 self.assertRaises(ValueError, '}'.format)
1175 self.assertRaises(ValueError, 'a{'.format)
1176 self.assertRaises(ValueError, 'a}'.format)
1177 self.assertRaises(ValueError, '{a'.format)
1178 self.assertRaises(ValueError, '}a'.format)
Eric Smith11529192007-09-04 23:04:22 +00001179 self.assertRaises(IndexError, '{0}'.format)
1180 self.assertRaises(IndexError, '{1}'.format, 'abc')
1181 self.assertRaises(KeyError, '{x}'.format)
Eric Smith8c663262007-08-25 02:26:07 +00001182 self.assertRaises(ValueError, "}{".format)
Eric Smith8c663262007-08-25 02:26:07 +00001183 self.assertRaises(ValueError, "abc{0:{}".format)
1184 self.assertRaises(ValueError, "{0".format)
Eric Smith11529192007-09-04 23:04:22 +00001185 self.assertRaises(IndexError, "{0.}".format)
1186 self.assertRaises(ValueError, "{0.}".format, 0)
Benjamin Peterson4d944742013-05-17 18:22:31 -05001187 self.assertRaises(ValueError, "{0[}".format)
Eric Smith4cb4e4e2007-09-03 08:40:29 +00001188 self.assertRaises(ValueError, "{0[}".format, [])
Eric Smith11529192007-09-04 23:04:22 +00001189 self.assertRaises(KeyError, "{0]}".format)
1190 self.assertRaises(ValueError, "{0.[]}".format, 0)
Eric Smith7ade6482007-08-26 22:27:13 +00001191 self.assertRaises(ValueError, "{0..foo}".format, 0)
Eric Smith11529192007-09-04 23:04:22 +00001192 self.assertRaises(ValueError, "{0[0}".format, 0)
1193 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
1194 self.assertRaises(KeyError, "{c]}".format)
1195 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
1196 self.assertRaises(ValueError, "{0}}".format, 0)
1197 self.assertRaises(KeyError, "{foo}".format, bar=3)
Eric Smith8c663262007-08-25 02:26:07 +00001198 self.assertRaises(ValueError, "{0!x}".format, 3)
Eric Smith11529192007-09-04 23:04:22 +00001199 self.assertRaises(ValueError, "{0!}".format, 0)
1200 self.assertRaises(ValueError, "{0!rs}".format, 0)
Eric Smith8c663262007-08-25 02:26:07 +00001201 self.assertRaises(ValueError, "{!}".format)
Eric Smith8ec90442009-03-14 12:29:34 +00001202 self.assertRaises(IndexError, "{:}".format)
1203 self.assertRaises(IndexError, "{:s}".format)
1204 self.assertRaises(IndexError, "{}".format)
Benjamin Peterson59a1b2f2010-06-07 22:31:26 +00001205 big = "23098475029384702983476098230754973209482573"
1206 self.assertRaises(ValueError, ("{" + big + "}").format)
1207 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
Eric Smith8c663262007-08-25 02:26:07 +00001208
Eric Smith41669ca2009-05-23 14:23:22 +00001209 # issue 6089
1210 self.assertRaises(ValueError, "{0[0]x}".format, [None])
1211 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
1212
Eric Smith8c663262007-08-25 02:26:07 +00001213 # can't have a replacement on the field name portion
1214 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
1215
1216 # exceed maximum recursion depth
1217 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
1218 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
1219 0, 1, 2, 3, 4, 5, 6, 7)
1220
1221 # string format spec errors
1222 self.assertRaises(ValueError, "{0:-s}".format, '')
1223 self.assertRaises(ValueError, format, "", "-")
1224 self.assertRaises(ValueError, "{0:=s}".format, '')
1225
Eric Smithb1ebcc62008-07-15 13:02:41 +00001226 # Alternate formatting is not supported
1227 self.assertRaises(ValueError, format, '', '#')
1228 self.assertRaises(ValueError, format, '', '#20')
1229
Victor Stinnerece58de2012-04-23 23:36:38 +02001230 # Non-ASCII
1231 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
1232 'ABC\u0410\u0411\u0412')
1233 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
1234 'ABC')
1235 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
1236 '')
1237
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001238 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
Benjamin Peterson4d944742013-05-17 18:22:31 -05001239 self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
1240 self.assertEqual("{[{]}".format({"{" : "a"}), "a")
1241 self.assertEqual("{[}]}".format({"}" : "a"}), "a")
1242 self.assertEqual("{[[]}".format({"[" : "a"}), "a")
1243 self.assertEqual("{[!]}".format({"!" : "a"}), "a")
1244 self.assertRaises(ValueError, "{a{}b}".format, 42)
1245 self.assertRaises(ValueError, "{a{b}".format, 42)
1246 self.assertRaises(ValueError, "{[}".format, 42)
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001247
Benjamin Peterson0ee22bf2013-11-26 19:22:36 -06001248 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001249
Guido van Rossum97c1adf2016-08-18 09:22:23 -07001250 # Blocking fallback
1251 m = M('data')
1252 self.assertEqual("{!r}".format(m), 'M(data)')
1253 self.assertRaises(TypeError, "{!s}".format, m)
1254 self.assertRaises(TypeError, "{}".format, m)
1255 n = N('data')
1256 self.assertEqual("{!r}".format(n), 'N(data)')
1257 self.assertEqual("{!s}".format(n), 'N(data)')
1258 self.assertRaises(TypeError, "{}".format, n)
1259
Eric Smith27bbca62010-11-04 17:06:58 +00001260 def test_format_map(self):
1261 self.assertEqual(''.format_map({}), '')
1262 self.assertEqual('a'.format_map({}), 'a')
1263 self.assertEqual('ab'.format_map({}), 'ab')
1264 self.assertEqual('a{{'.format_map({}), 'a{')
1265 self.assertEqual('a}}'.format_map({}), 'a}')
1266 self.assertEqual('{{b'.format_map({}), '{b')
1267 self.assertEqual('}}b'.format_map({}), '}b')
1268 self.assertEqual('a{{b'.format_map({}), 'a{b')
1269
1270 # using mappings
1271 class Mapping(dict):
1272 def __missing__(self, key):
1273 return key
1274 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
1275 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
1276
1277 class InternalMapping:
1278 def __init__(self):
1279 self.mapping = {'a': 'hello'}
1280 def __getitem__(self, key):
1281 return self.mapping[key]
1282 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
1283
1284
Eric Smith27bbca62010-11-04 17:06:58 +00001285 class C:
1286 def __init__(self, x=100):
1287 self._x = x
1288 def __format__(self, spec):
1289 return spec
Eric Smith27bbca62010-11-04 17:06:58 +00001290 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
1291
1292 # test various errors
Eric V. Smithedbb6ca2012-03-12 15:16:22 -07001293 self.assertRaises(TypeError, ''.format_map)
1294 self.assertRaises(TypeError, 'a'.format_map)
1295
1296 self.assertRaises(ValueError, '{'.format_map, {})
1297 self.assertRaises(ValueError, '}'.format_map, {})
1298 self.assertRaises(ValueError, 'a{'.format_map, {})
1299 self.assertRaises(ValueError, 'a}'.format_map, {})
1300 self.assertRaises(ValueError, '{a'.format_map, {})
1301 self.assertRaises(ValueError, '}a'.format_map, {})
Eric Smith27bbca62010-11-04 17:06:58 +00001302
Eric V. Smith12ebefc2011-07-18 14:03:41 -04001303 # issue #12579: can't supply positional params to format_map
1304 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1305 self.assertRaises(ValueError, '{}'.format_map, 'a')
1306 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1307
Serhiy Storchaka50754162017-08-03 11:45:23 +03001308 class BadMapping:
1309 def __getitem__(self, key):
1310 return 1/0
1311 self.assertRaises(KeyError, '{a}'.format_map, {})
1312 self.assertRaises(TypeError, '{a}'.format_map, [])
1313 self.assertRaises(ZeroDivisionError, '{a}'.format_map, BadMapping())
1314
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001315 def test_format_huge_precision(self):
1316 format_string = ".{}f".format(sys.maxsize + 1)
1317 with self.assertRaises(ValueError):
1318 result = format(2.34, format_string)
1319
1320 def test_format_huge_width(self):
1321 format_string = "{}f".format(sys.maxsize + 1)
1322 with self.assertRaises(ValueError):
1323 result = format(2.34, format_string)
1324
1325 def test_format_huge_item_number(self):
1326 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1327 with self.assertRaises(ValueError):
1328 result = format_string.format(2.34)
1329
Eric Smith8ec90442009-03-14 12:29:34 +00001330 def test_format_auto_numbering(self):
1331 class C:
1332 def __init__(self, x=100):
1333 self._x = x
1334 def __format__(self, spec):
1335 return spec
1336
1337 self.assertEqual('{}'.format(10), '10')
1338 self.assertEqual('{:5}'.format('s'), 's ')
1339 self.assertEqual('{!r}'.format('s'), "'s'")
1340 self.assertEqual('{._x}'.format(C(10)), '10')
1341 self.assertEqual('{[1]}'.format([1, 2]), '2')
1342 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1343 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1344
1345 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1346 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1347
1348 # can't mix and match numbering and auto-numbering
1349 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1350 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1351 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1352 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1353
1354 # can mix and match auto-numbering and named
1355 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1356 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1357 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1358 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1359
Walter Dörwald28256f22003-01-19 16:59:20 +00001360 def test_formatting(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001361 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
Walter Dörwald28256f22003-01-19 16:59:20 +00001362 # Testing Unicode formatting strings...
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001363 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1364 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1365 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1366 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1367 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1368 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 1003.57), 'abc, abc, -1, -2.000000, 1003.57')
Walter Dörwald28256f22003-01-19 16:59:20 +00001369 if not sys.platform.startswith('java'):
Walter Dörwald67e83882007-05-05 12:26:27 +00001370 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
Georg Brandl559e5d72008-06-11 18:37:52 +00001371 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1372 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001373 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1374 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
Walter Dörwald56fbcb52003-03-31 18:18:41 +00001375
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001376 self.assertEqual('%c' % 0x1234, '\u1234')
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00001377 self.assertEqual('%c' % 0x21483, '\U00021483')
1378 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1379 self.assertEqual('%c' % '\U00021483', '\U00021483')
1380 self.assertRaises(TypeError, "%c".__mod__, "aa")
Stefan Krah99212f62010-07-19 17:58:26 +00001381 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07001382 self.assertRaises(TypeError, "%i".__mod__, "aa")
Walter Dörwald28256f22003-01-19 16:59:20 +00001383
1384 # formatting jobs delegated from the string implementation:
Walter Dörwald28256f22003-01-19 16:59:20 +00001385 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001386 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1387 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1388 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1389 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1390 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1391 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1392 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1393 self.assertEqual('...%s...' % "abc", '...abc...')
1394 self.assertEqual('%*s' % (5,'abc',), ' abc')
1395 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1396 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1397 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1398 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1399 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1400 self.assertEqual('%c' % 'a', 'a')
Neil Schemenauercf52c072005-08-12 17:34:58 +00001401 class Wrapper:
1402 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001403 return '\u1234'
1404 self.assertEqual('%s' % Wrapper(), '\u1234')
Walter Dörwald28256f22003-01-19 16:59:20 +00001405
Eric Smith741191f2009-05-06 13:08:15 +00001406 # issue 3382
1407 NAN = float('nan')
1408 INF = float('inf')
1409 self.assertEqual('%f' % NAN, 'nan')
1410 self.assertEqual('%F' % NAN, 'NAN')
1411 self.assertEqual('%f' % INF, 'inf')
1412 self.assertEqual('%F' % INF, 'INF')
1413
Victor Stinnerf59c28c2012-05-09 03:24:14 +02001414 # PEP 393
1415 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1416 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1417
Ethan Furmandf3ed242014-01-05 06:50:30 -08001418 #issue 19995
Ethan Furman9ab74802014-03-21 06:38:46 -07001419 class PseudoInt:
Ethan Furmandf3ed242014-01-05 06:50:30 -08001420 def __init__(self, value):
1421 self.value = int(value)
1422 def __int__(self):
1423 return self.value
1424 def __index__(self):
1425 return self.value
Ethan Furman9ab74802014-03-21 06:38:46 -07001426 class PseudoFloat:
Ethan Furmandf3ed242014-01-05 06:50:30 -08001427 def __init__(self, value):
1428 self.value = float(value)
1429 def __int__(self):
1430 return int(self.value)
Ethan Furman9ab74802014-03-21 06:38:46 -07001431 pi = PseudoFloat(3.1415)
1432 letter_m = PseudoInt(109)
Antoine Pitroueb168042014-01-10 00:02:38 +01001433 self.assertEqual('%x' % 42, '2a')
1434 self.assertEqual('%X' % 15, 'F')
1435 self.assertEqual('%o' % 9, '11')
1436 self.assertEqual('%c' % 109, 'm')
1437 self.assertEqual('%x' % letter_m, '6d')
1438 self.assertEqual('%X' % letter_m, '6D')
1439 self.assertEqual('%o' % letter_m, '155')
1440 self.assertEqual('%c' % letter_m, 'm')
Ethan Furman9ab74802014-03-21 06:38:46 -07001441 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14),
1442 self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11),
1443 self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79),
1444 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi),
1445 self.assertRaises(TypeError, operator.mod, '%c', pi),
Ethan Furmandf3ed242014-01-05 06:50:30 -08001446
Ethan Furmanfb137212013-08-31 10:18:55 -07001447 def test_formatting_with_enum(self):
1448 # issue18780
1449 import enum
1450 class Float(float, enum.Enum):
1451 PI = 3.1415926
1452 class Int(enum.IntEnum):
1453 IDES = 15
1454 class Str(str, enum.Enum):
1455 ABC = 'abc'
1456 # Testing Unicode formatting strings...
Ethan Furman13bdfa72013-08-31 12:48:51 -07001457 self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
1458 'Str.ABC, Str.ABC')
1459 self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
1460 (Str.ABC, Str.ABC,
1461 Int.IDES, Int.IDES, Int.IDES,
1462 Float.PI, Float.PI),
1463 'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14')
Ethan Furmanfb137212013-08-31 10:18:55 -07001464
1465 # formatting jobs delegated from the string implementation:
Ethan Furman13bdfa72013-08-31 12:48:51 -07001466 self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
1467 '...Str.ABC...')
1468 self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
1469 '...Int.IDES...')
1470 self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
1471 '...15...')
1472 self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
1473 '...15...')
1474 self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
1475 '...15...')
1476 self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
1477 '...3.141593...')
Ethan Furmanfb137212013-08-31 10:18:55 -07001478
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001479 def test_formatting_huge_precision(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001480 format_string = "%.{}f".format(sys.maxsize + 1)
1481 with self.assertRaises(ValueError):
1482 result = format_string % 2.34
1483
Martijn Pietersd7e64332017-02-23 13:38:04 +00001484 def test_issue28598_strsubclass_rhs(self):
1485 # A subclass of str with an __rmod__ method should be able to hook
1486 # into the % operator
1487 class SubclassedStr(str):
1488 def __rmod__(self, other):
1489 return 'Success, self.__rmod__({!r}) was called'.format(other)
1490 self.assertEqual('lhs %% %r' % SubclassedStr('rhs'),
1491 "Success, self.__rmod__('lhs %% %r') was called")
1492
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001493 @support.cpython_only
1494 def test_formatting_huge_precision_c_limits(self):
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001495 from _testcapi import INT_MAX
1496 format_string = "%.{}f".format(INT_MAX + 1)
1497 with self.assertRaises(ValueError):
1498 result = format_string % 2.34
1499
1500 def test_formatting_huge_width(self):
1501 format_string = "%{}f".format(sys.maxsize + 1)
1502 with self.assertRaises(ValueError):
1503 result = format_string % 2.34
1504
Ezio Melottiba42fd52011-04-26 06:09:45 +03001505 def test_startswith_endswith_errors(self):
1506 for meth in ('foo'.startswith, 'foo'.endswith):
Ezio Melottif2b3f782011-04-26 06:40:59 +03001507 with self.assertRaises(TypeError) as cm:
Ezio Melottiba42fd52011-04-26 06:09:45 +03001508 meth(['f'])
Ezio Melottif2b3f782011-04-26 06:40:59 +03001509 exc = str(cm.exception)
Ezio Melottiba42fd52011-04-26 06:09:45 +03001510 self.assertIn('str', exc)
1511 self.assertIn('tuple', exc)
1512
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001513 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
Georg Brandlda6b1072006-01-20 17:48:54 +00001514 def test_format_float(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001515 # should not format with a comma, but always with C locale
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001516 self.assertEqual('1.0', '%.1f' % 1.0)
Georg Brandlda6b1072006-01-20 17:48:54 +00001517
Walter Dörwald28256f22003-01-19 16:59:20 +00001518 def test_constructor(self):
1519 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1520
1521 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001522 str('unicode remains unicode'),
1523 'unicode remains unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001524 )
1525
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001526 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
Serhiy Storchaka15095802015-11-25 15:47:01 +02001527 subclass = StrSubclass(text)
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001528 self.assertEqual(str(subclass), text)
1529 self.assertEqual(len(subclass), len(text))
1530 if text == 'ascii':
1531 self.assertEqual(subclass.encode('ascii'), b'ascii')
1532 self.assertEqual(subclass.encode('utf-8'), b'ascii')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001533
Walter Dörwald28256f22003-01-19 16:59:20 +00001534 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001535 str('strings are converted to unicode'),
1536 'strings are converted to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001537 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001538
Walter Dörwald28256f22003-01-19 16:59:20 +00001539 class StringCompat:
1540 def __init__(self, x):
1541 self.x = x
1542 def __str__(self):
1543 return self.x
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001544
Walter Dörwald28256f22003-01-19 16:59:20 +00001545 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001546 str(StringCompat('__str__ compatible objects are recognized')),
1547 '__str__ compatible objects are recognized'
Walter Dörwald28256f22003-01-19 16:59:20 +00001548 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001549
Walter Dörwald28256f22003-01-19 16:59:20 +00001550 # unicode(obj) is compatible to str():
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001551
Walter Dörwald28256f22003-01-19 16:59:20 +00001552 o = StringCompat('unicode(obj) is compatible to str()')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001553 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Walter Dörwald28256f22003-01-19 16:59:20 +00001554 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001555
Guido van Rossume2a383d2007-01-15 16:59:06 +00001556 for obj in (123, 123.45, 123):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001557 self.assertEqual(str(obj), str(str(obj)))
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001558
Walter Dörwald28256f22003-01-19 16:59:20 +00001559 # unicode(obj, encoding, error) tests (this maps to
1560 # PyUnicode_FromEncodedObject() at C level)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001561
Walter Dörwald28256f22003-01-19 16:59:20 +00001562 if not sys.platform.startswith('java'):
1563 self.assertRaises(
1564 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001565 str,
1566 'decoding unicode is not supported',
Walter Dörwald28256f22003-01-19 16:59:20 +00001567 'utf-8',
1568 'strict'
1569 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001570
Walter Dörwald28256f22003-01-19 16:59:20 +00001571 self.assertEqual(
Walter Dörwald67e83882007-05-05 12:26:27 +00001572 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001573 'strings are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001574 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001575
Walter Dörwald28256f22003-01-19 16:59:20 +00001576 if not sys.platform.startswith('java'):
1577 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001578 str(
Guido van Rossumbae07c92007-10-08 02:46:15 +00001579 memoryview(b'character buffers are decoded to unicode'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001580 'utf-8',
1581 'strict'
1582 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001583 'character buffers are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001584 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001585
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001586 self.assertRaises(TypeError, str, 42, 42, 42)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001587
Chris Jerdonek5fae0e52012-11-20 17:45:51 -08001588 def test_constructor_keyword_args(self):
1589 """Pass various keyword argument combinations to the constructor."""
1590 # The object argument can be passed as a keyword.
1591 self.assertEqual(str(object='foo'), 'foo')
1592 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1593 # The errors argument without encoding triggers "decode" mode.
1594 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1595 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1596
1597 def test_constructor_defaults(self):
1598 """Check the constructor argument defaults."""
1599 # The object argument defaults to '' or b''.
1600 self.assertEqual(str(), '')
1601 self.assertEqual(str(errors='strict'), '')
1602 utf8_cent = '¢'.encode('utf-8')
1603 # The encoding argument defaults to utf-8.
1604 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1605 # The errors argument defaults to strict.
1606 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1607
Walter Dörwald28256f22003-01-19 16:59:20 +00001608 def test_codecs_utf7(self):
1609 utfTests = [
Walter Dörwald67e83882007-05-05 12:26:27 +00001610 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1611 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1612 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1613 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1614 ('+', b'+-'),
1615 ('+-', b'+--'),
1616 ('+?', b'+-?'),
R David Murray44b548d2016-09-08 13:59:53 -04001617 (r'\?', b'+AFw?'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001618 ('+?', b'+-?'),
1619 (r'\\?', b'+AFwAXA?'),
1620 (r'\\\?', b'+AFwAXABc?'),
Antoine Pitrou244651a2009-05-04 18:56:13 +00001621 (r'++--', b'+-+---'),
1622 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1623 ('/', b'/'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001624 ]
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001625
Walter Dörwald28256f22003-01-19 16:59:20 +00001626 for (x, y) in utfTests:
1627 self.assertEqual(x.encode('utf-7'), y)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001628
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001629 # Unpaired surrogates are passed through
1630 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1631 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1632 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1633 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1634 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1635 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1636 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1637 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001638
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001639 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1640 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001641
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001642 # Issue #2242: crash on some Windows/MSVC versions
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03001643 self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
Antoine Pitrou244651a2009-05-04 18:56:13 +00001644
1645 # Direct encoded characters
1646 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1647 # Optional direct characters
1648 set_o = '!"#$%&*;<=>@[]^_`{|}'
1649 for c in set_d:
1650 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1651 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1652 for c in set_o:
1653 self.assertEqual(c.encode('ascii').decode('utf7'), c)
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001654
Zackery Spytze349bf22018-08-18 22:43:38 -06001655 with self.assertRaisesRegex(UnicodeDecodeError,
1656 'ill-formed sequence'):
1657 b'+@'.decode('utf-7')
1658
Walter Dörwald28256f22003-01-19 16:59:20 +00001659 def test_codecs_utf8(self):
Walter Dörwald67e83882007-05-05 12:26:27 +00001660 self.assertEqual(''.encode('utf-8'), b'')
1661 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001662 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1663 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001664 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1665 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001666 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1667 b'\xf0\x90\x80\x82'*10)
Walter Dörwald28256f22003-01-19 16:59:20 +00001668 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001669 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1670 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1671 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1672 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1673 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1674 ' Nunstuck git und'.encode('utf-8'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001675 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1676 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1677 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1678 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1679 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1680 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1681 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1682 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1683 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1684 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
Walter Dörwald28256f22003-01-19 16:59:20 +00001685 )
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001686
Walter Dörwald28256f22003-01-19 16:59:20 +00001687 # UTF-8 specific decoding tests
Walter Dörwald67e83882007-05-05 12:26:27 +00001688 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1689 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1690 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001691
Walter Dörwald28256f22003-01-19 16:59:20 +00001692 # Other possible utf-8 test cases:
1693 # * strict decoding testing for all of the
1694 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001695
Ezio Melotti57221d02010-07-01 07:32:02 +00001696 def test_utf8_decode_valid_sequences(self):
1697 sequences = [
1698 # single byte
1699 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1700 # 2 bytes
1701 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1702 # 3 bytes
1703 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1704 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1705 # 4 bytes
1706 (b'\xF0\x90\x80\x80', '\U00010000'),
1707 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1708 ]
1709 for seq, res in sequences:
1710 self.assertEqual(seq.decode('utf-8'), res)
1711
1712
1713 def test_utf8_decode_invalid_sequences(self):
1714 # continuation bytes in a sequence of 2, 3, or 4 bytes
1715 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001716 # start bytes of a 2-byte sequence equivalent to code points < 0x7F
Ezio Melotti57221d02010-07-01 07:32:02 +00001717 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001718 # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
Ezio Melotti57221d02010-07-01 07:32:02 +00001719 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1720 invalid_start_bytes = (
1721 continuation_bytes + invalid_2B_seq_start_bytes +
1722 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1723 )
1724
1725 for byte in invalid_start_bytes:
1726 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1727
1728 for sb in invalid_2B_seq_start_bytes:
1729 for cb in continuation_bytes:
1730 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1731
1732 for sb in invalid_4B_seq_start_bytes:
1733 for cb1 in continuation_bytes[:3]:
1734 for cb3 in continuation_bytes[:3]:
1735 self.assertRaises(UnicodeDecodeError,
1736 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1737
1738 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1739 self.assertRaises(UnicodeDecodeError,
1740 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1741 self.assertRaises(UnicodeDecodeError,
1742 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1743 # surrogates
1744 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1745 self.assertRaises(UnicodeDecodeError,
1746 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1747 self.assertRaises(UnicodeDecodeError,
1748 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1749 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1750 self.assertRaises(UnicodeDecodeError,
1751 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1752 self.assertRaises(UnicodeDecodeError,
1753 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1754 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1755 self.assertRaises(UnicodeDecodeError,
1756 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1757 self.assertRaises(UnicodeDecodeError,
1758 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1759
1760 def test_issue8271(self):
1761 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1762 # only the start byte and the continuation byte(s) are now considered
1763 # invalid, instead of the number of bytes specified by the start byte.
Benjamin Peterson51796e52020-03-10 21:10:59 -07001764 # See https://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
Ezio Melotti57221d02010-07-01 07:32:02 +00001765 # table 3-8, Row 2) for more information about the algorithm used.
1766 FFFD = '\ufffd'
1767 sequences = [
1768 # invalid start bytes
1769 (b'\x80', FFFD), # continuation byte
1770 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1771 (b'\xc0', FFFD),
1772 (b'\xc0\xc0', FFFD*2),
1773 (b'\xc1', FFFD),
1774 (b'\xc1\xc0', FFFD*2),
1775 (b'\xc0\xc1', FFFD*2),
1776 # with start byte of a 2-byte sequence
1777 (b'\xc2', FFFD), # only the start byte
1778 (b'\xc2\xc2', FFFD*2), # 2 start bytes
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001779 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
Ezio Melotti57221d02010-07-01 07:32:02 +00001780 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1781 # with start byte of a 3-byte sequence
1782 (b'\xe1', FFFD), # only the start byte
1783 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1784 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1785 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1786 (b'\xe1\x80', FFFD), # only 1 continuation byte
1787 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1788 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1789 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1790 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1791 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1792 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1793 # with start byte of a 4-byte sequence
1794 (b'\xf1', FFFD), # only the start byte
1795 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1796 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1797 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1798 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1799 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1800 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1801 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1802 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1803 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1804 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1805 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1806 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1807 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1808 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1809 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1810 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1811 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1812 # with invalid start byte of a 4-byte sequence (rfc2279)
1813 (b'\xf5', FFFD), # only the start byte
1814 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1815 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1816 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1817 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1818 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1819 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1820 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1821 # with invalid start byte of a 5-byte sequence (rfc2279)
1822 (b'\xf8', FFFD), # only the start byte
1823 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1824 (b'\xf8\x80', FFFD*2), # only one continuation byte
1825 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1826 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1827 # with invalid start byte of a 6-byte sequence (rfc2279)
1828 (b'\xfc', FFFD), # only the start byte
1829 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1830 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1831 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
1832 # invalid start byte
1833 (b'\xfe', FFFD),
1834 (b'\xfe\x80\x80', FFFD*3),
1835 # other sequences
1836 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
1837 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
1838 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
1839 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
1840 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
1841 ]
1842 for n, (seq, res) in enumerate(sequences):
1843 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
1844 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1845 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
1846 self.assertEqual(seq.decode('utf-8', 'ignore'),
1847 res.replace('\uFFFD', ''))
1848
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001849 def assertCorrectUTF8Decoding(self, seq, res, err):
1850 """
Martin Panter6245cb32016-04-15 02:14:19 +00001851 Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001852 'strict' is used, returns res when 'replace' is used, and that doesn't
1853 return anything when 'ignore' is used.
1854 """
1855 with self.assertRaises(UnicodeDecodeError) as cm:
1856 seq.decode('utf-8')
1857 exc = cm.exception
1858
1859 self.assertIn(err, str(exc))
1860 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1861 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
1862 'aaaa' + res + 'bbbb')
1863 res = res.replace('\ufffd', '')
1864 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
1865 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
1866 'aaaa' + res + 'bbbb')
1867
1868 def test_invalid_start_byte(self):
1869 """
1870 Test that an 'invalid start byte' error is raised when the first byte
1871 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
1872 4-bytes sequence. The invalid start byte is replaced with a single
1873 U+FFFD when errors='replace'.
1874 E.g. <80> is a continuation byte and can appear only after a start byte.
1875 """
1876 FFFD = '\ufffd'
1877 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
1878 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
1879 'invalid start byte')
1880
1881 def test_unexpected_end_of_data(self):
1882 """
1883 Test that an 'unexpected end of data' error is raised when the string
1884 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
1885 enough continuation bytes. The incomplete sequence is replaced with a
1886 single U+FFFD when errors='replace'.
1887 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
1888 sequence, but it's followed by only 2 valid continuation bytes and the
1889 last continuation bytes is missing.
1890 Note: the continuation bytes must be all valid, if one of them is
1891 invalid another error will be raised.
1892 """
1893 sequences = [
1894 'C2', 'DF',
1895 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
1896 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
1897 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
1898 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
1899 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
1900 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
1901 ]
1902 FFFD = '\ufffd'
1903 for seq in sequences:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +02001904 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), '\ufffd',
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001905 'unexpected end of data')
1906
1907 def test_invalid_cb_for_2bytes_seq(self):
1908 """
1909 Test that an 'invalid continuation byte' error is raised when the
1910 continuation byte of a 2-bytes sequence is invalid. The start byte
1911 is replaced by a single U+FFFD and the second byte is handled
1912 separately when errors='replace'.
1913 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
1914 sequence, but 41 is not a valid continuation byte because it's the
1915 ASCII letter 'A'.
1916 """
1917 FFFD = '\ufffd'
1918 FFFDx2 = FFFD * 2
1919 sequences = [
1920 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
1921 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
1922 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
1923 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
1924 ]
1925 for seq, res in sequences:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +02001926 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001927 'invalid continuation byte')
1928
1929 def test_invalid_cb_for_3bytes_seq(self):
1930 """
1931 Test that an 'invalid continuation byte' error is raised when the
1932 continuation byte(s) of a 3-bytes sequence are invalid. When
1933 errors='replace', if the first continuation byte is valid, the first
1934 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
1935 third byte is handled separately, otherwise only the start byte is
1936 replaced with a U+FFFD and the other continuation bytes are handled
1937 separately.
1938 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1939 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1940 because it's the ASCII letter 'A'.
1941 Note: when the start byte is E0 or ED, the valid ranges for the first
1942 continuation byte are limited to A0..BF and 80..9F respectively.
1943 Python 2 used to consider all the bytes in range 80..BF valid when the
1944 start byte was ED. This is fixed in Python 3.
1945 """
1946 FFFD = '\ufffd'
1947 FFFDx2 = FFFD * 2
1948 sequences = [
1949 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
1950 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
1951 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
1952 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
1953 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
1954 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
1955 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
1956 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
1957 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
1958 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
1959 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
1960 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
1961 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
1962 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
1963 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
1964 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
1965 ('ED 7F', FFFD+'\x7f'),
1966 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
1967 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
1968 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
1969 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
1970 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
1971 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
1972 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
1973 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
1974 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
1975 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
1976 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
1977 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
1978 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
1979 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
1980 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
1981 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
1982 ]
1983 for seq, res in sequences:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +02001984 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001985 'invalid continuation byte')
1986
1987 def test_invalid_cb_for_4bytes_seq(self):
1988 """
1989 Test that an 'invalid continuation byte' error is raised when the
1990 continuation byte(s) of a 4-bytes sequence are invalid. When
1991 errors='replace',the start byte and all the following valid
1992 continuation bytes are replaced with a single U+FFFD, and all the bytes
1993 starting from the first invalid continuation bytes (included) are
1994 handled separately.
1995 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1996 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1997 because it's the ASCII letter 'A'.
1998 Note: when the start byte is E0 or ED, the valid ranges for the first
1999 continuation byte are limited to A0..BF and 80..9F respectively.
2000 However, when the start byte is ED, Python 2 considers all the bytes
2001 in range 80..BF valid. This is fixed in Python 3.
2002 """
2003 FFFD = '\ufffd'
2004 FFFDx2 = FFFD * 2
2005 sequences = [
2006 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
2007 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
2008 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
2009 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
2010 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
2011 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
2012 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
2013 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
2014 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
2015 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
2016 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
2017 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
2018 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
2019 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
2020 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
2021 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
2022 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
2023 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
2024 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
2025 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
2026 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
2027 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
2028 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
2029 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
2030 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
2031 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
2032 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
2033 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
2034 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
2035 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
2036 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
2037 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
2038 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
2039 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
2040 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
2041 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
2042 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
2043 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
2044 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
2045 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
2046 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
2047 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
2048 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
2049 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
2050 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
2051 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
2052 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
2053 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
2054 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
2055 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
2056 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
2057 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
2058 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
2059 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
2060 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
2061 ]
2062 for seq, res in sequences:
Serhiy Storchaka8cbd3df2016-12-21 12:59:28 +02002063 self.assertCorrectUTF8Decoding(bytes.fromhex(seq), res,
Ezio Melottif7ed5d12012-11-04 23:21:38 +02002064 'invalid continuation byte')
2065
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00002066 def test_codecs_idna(self):
2067 # Test whether trailing dot is preserved
Walter Dörwald1324c6f2007-05-11 19:57:05 +00002068 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00002069
Walter Dörwald28256f22003-01-19 16:59:20 +00002070 def test_codecs_errors(self):
2071 # Error handling (encoding)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002072 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
2073 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
Walter Dörwald67e83882007-05-05 12:26:27 +00002074 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
2075 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
Benjamin Peterson308d6372009-09-18 21:42:35 +00002076 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
2077 'Andr\202 x'.encode('ascii', errors='replace'))
2078 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
2079 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002080
Walter Dörwald28256f22003-01-19 16:59:20 +00002081 # Error handling (decoding)
Walter Dörwald67e83882007-05-05 12:26:27 +00002082 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
2083 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
2084 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
2085 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03002086 self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002087
Walter Dörwald28256f22003-01-19 16:59:20 +00002088 # Error handling (unknown character names)
Guido van Rossum39478e82007-08-27 17:23:59 +00002089 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002090
Walter Dörwald28256f22003-01-19 16:59:20 +00002091 # Error handling (truncated escape sequence)
Guido van Rossum9c627722007-08-27 18:31:48 +00002092 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00002093
Guido van Rossum9c627722007-08-27 18:31:48 +00002094 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
2095 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002096 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
2097 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00002098
Walter Dörwald28256f22003-01-19 16:59:20 +00002099 # Error handling (wrong arguments)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002100 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002101
Serhiy Storchaka9b6c60c2017-11-13 21:23:48 +02002102 # Error handling (lone surrogate in
2103 # _PyUnicode_TransformDecimalAndSpaceToASCII())
2104 self.assertRaises(ValueError, int, "\ud800")
2105 self.assertRaises(ValueError, int, "\udf00")
2106 self.assertRaises(ValueError, float, "\ud800")
2107 self.assertRaises(ValueError, float, "\udf00")
2108 self.assertRaises(ValueError, complex, "\ud800")
2109 self.assertRaises(ValueError, complex, "\udf00")
Guido van Rossum97064862000-04-10 13:52:48 +00002110
Walter Dörwald28256f22003-01-19 16:59:20 +00002111 def test_codecs(self):
2112 # Encoding
Walter Dörwald67e83882007-05-05 12:26:27 +00002113 self.assertEqual('hello'.encode('ascii'), b'hello')
2114 self.assertEqual('hello'.encode('utf-7'), b'hello')
2115 self.assertEqual('hello'.encode('utf-8'), b'hello')
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002116 self.assertEqual('hello'.encode('utf-8'), b'hello')
Walter Dörwald67e83882007-05-05 12:26:27 +00002117 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
2118 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
2119 self.assertEqual('hello'.encode('latin-1'), b'hello')
Guido van Rossum97064862000-04-10 13:52:48 +00002120
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002121 # Default encoding is utf-8
2122 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
2123
Walter Dörwald28256f22003-01-19 16:59:20 +00002124 # Roundtrip safety for BMP (just the first 1024 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002125 for c in range(1024):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002126 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002127 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
2128 'utf-16-be', 'raw_unicode_escape',
Inada Naoki6a16b182019-03-18 15:44:11 +09002129 'unicode_escape'):
2130 self.assertEqual(str(u.encode(encoding),encoding), u)
Martin v. Löwis047c05e2002-03-21 08:55:28 +00002131
Walter Dörwald28256f22003-01-19 16:59:20 +00002132 # Roundtrip safety for BMP (just the first 256 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002133 for c in range(256):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002134 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002135 for encoding in ('latin-1',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002136 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002137
Walter Dörwald28256f22003-01-19 16:59:20 +00002138 # Roundtrip safety for BMP (just the first 128 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002139 for c in range(128):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002140 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002141 for encoding in ('ascii',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002142 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002143
Walter Dörwald28256f22003-01-19 16:59:20 +00002144 # Roundtrip safety for non-BMP (just a few chars)
Victor Stinner040e16e2011-11-15 22:44:05 +01002145 with warnings.catch_warnings():
Victor Stinner040e16e2011-11-15 22:44:05 +01002146 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
2147 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
Inada Naoki6a16b182019-03-18 15:44:11 +09002148 'raw_unicode_escape', 'unicode_escape'):
Victor Stinner040e16e2011-11-15 22:44:05 +01002149 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002150
Antoine Pitrou51f66482011-11-11 13:35:44 +01002151 # UTF-8 must be roundtrip safe for all code points
2152 # (except surrogates, which are forbidden).
2153 u = ''.join(map(chr, list(range(0, 0xd800)) +
Ezio Melotti40dc9192011-11-11 17:00:46 +02002154 list(range(0xe000, 0x110000))))
Walter Dörwald28256f22003-01-19 16:59:20 +00002155 for encoding in ('utf-8',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002156 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002157
Walter Dörwald28256f22003-01-19 16:59:20 +00002158 def test_codecs_charmap(self):
2159 # 0-127
Guido van Rossum805365e2007-05-07 22:24:25 +00002160 s = bytes(range(128))
Walter Dörwald28256f22003-01-19 16:59:20 +00002161 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002162 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002163 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2164 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002165 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002166 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2167 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002168 'iso8859_7', 'iso8859_9',
2169 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1',
Walter Dörwald28256f22003-01-19 16:59:20 +00002170 'mac_cyrillic', 'mac_latin2',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002171
Walter Dörwald28256f22003-01-19 16:59:20 +00002172 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2173 'cp1256', 'cp1257', 'cp1258',
2174 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002175
Walter Dörwald28256f22003-01-19 16:59:20 +00002176 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
2177 'cp1006', 'iso8859_8',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002178
Walter Dörwald28256f22003-01-19 16:59:20 +00002179 ### These have undefined mappings:
2180 #'cp424',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002181
Walter Dörwald28256f22003-01-19 16:59:20 +00002182 ### These fail the round-trip:
2183 #'cp875'
Guido van Rossum9e896b32000-04-05 20:11:21 +00002184
Walter Dörwald28256f22003-01-19 16:59:20 +00002185 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002186 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002187
Walter Dörwald28256f22003-01-19 16:59:20 +00002188 # 128-255
Guido van Rossum805365e2007-05-07 22:24:25 +00002189 s = bytes(range(128, 256))
Walter Dörwald28256f22003-01-19 16:59:20 +00002190 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002191 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002192 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2193 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002194 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002195 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2196 'iso8859_2', 'iso8859_4', 'iso8859_5',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002197 'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1',
Walter Dörwald28256f22003-01-19 16:59:20 +00002198 'mac_cyrillic', 'mac_latin2',
Fred Drake004d5e62000-10-23 17:22:08 +00002199
Walter Dörwald28256f22003-01-19 16:59:20 +00002200 ### These have undefined mappings:
2201 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2202 #'cp1256', 'cp1257', 'cp1258',
2203 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002204 #'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048',
Walter Dörwald28256f22003-01-19 16:59:20 +00002205 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
Fred Drake004d5e62000-10-23 17:22:08 +00002206
Walter Dörwald28256f22003-01-19 16:59:20 +00002207 ### These fail the round-trip:
2208 #'cp1006', 'cp875', 'iso8859_8',
Tim Peters2f228e72001-05-13 00:19:31 +00002209
Walter Dörwald28256f22003-01-19 16:59:20 +00002210 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002211 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002212
Walter Dörwald28256f22003-01-19 16:59:20 +00002213 def test_concatenation(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002214 self.assertEqual(("abc" "def"), "abcdef")
2215 self.assertEqual(("abc" "def"), "abcdef")
2216 self.assertEqual(("abc" "def"), "abcdef")
2217 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
2218 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
Fred Drake004d5e62000-10-23 17:22:08 +00002219
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002220 def test_ucs4(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002221 x = '\U00100000'
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002222 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
2223 self.assertEqual(x, y)
2224
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002225 y = br'\U00100000'
2226 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2227 self.assertEqual(x, y)
2228 y = br'\U00010000'
2229 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2230 self.assertEqual(x, y)
Christian Heimesfe337bf2008-03-23 21:54:12 +00002231
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002232 try:
2233 br'\U11111111'.decode("raw-unicode-escape")
2234 except UnicodeDecodeError as e:
2235 self.assertEqual(e.start, 0)
2236 self.assertEqual(e.end, 10)
2237 else:
2238 self.fail("Should have raised UnicodeDecodeError")
Christian Heimesfe337bf2008-03-23 21:54:12 +00002239
Brett Cannonc3647ac2005-04-26 03:45:26 +00002240 def test_conversion(self):
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002241 # Make sure __str__() works properly
2242 class ObjectToStr:
Brett Cannonc3647ac2005-04-26 03:45:26 +00002243 def __str__(self):
2244 return "foo"
2245
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002246 class StrSubclassToStr(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00002247 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002248 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00002249
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002250 class StrSubclassToStrSubclass(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002251 def __new__(cls, content=""):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002252 return str.__new__(cls, 2*content)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002253 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002254 return self
2255
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002256 self.assertEqual(str(ObjectToStr()), "foo")
2257 self.assertEqual(str(StrSubclassToStr("bar")), "foo")
2258 s = str(StrSubclassToStrSubclass("foo"))
2259 self.assertEqual(s, "foofoo")
2260 self.assertIs(type(s), StrSubclassToStrSubclass)
Serhiy Storchaka15095802015-11-25 15:47:01 +02002261 s = StrSubclass(StrSubclassToStrSubclass("foo"))
2262 self.assertEqual(s, "foofoo")
2263 self.assertIs(type(s), StrSubclass)
Brett Cannonc3647ac2005-04-26 03:45:26 +00002264
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002265 def test_unicode_repr(self):
2266 class s1:
2267 def __repr__(self):
2268 return '\\n'
2269
2270 class s2:
2271 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002272 return '\\n'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002273
2274 self.assertEqual(repr(s1()), '\\n')
2275 self.assertEqual(repr(s2()), '\\n')
2276
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002277 def test_printable_repr(self):
2278 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
Martin v. Löwisbaecd722010-10-11 22:42:28 +00002279 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002280
Zachary Ware9fe6d862013-12-08 00:20:35 -06002281 # This test only affects 32-bit platforms because expandtabs can only take
2282 # an int as the max value, not a 64-bit C long. If expandtabs is changed
2283 # to take a 64-bit long, this test should apply to all platforms.
2284 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
2285 'only applies to 32-bit platforms')
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002286 def test_expandtabs_overflows_gracefully(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +00002287 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002288
Victor Stinner1d972ad2011-10-07 13:31:46 +02002289 @support.cpython_only
Antoine Pitroue19aa382011-10-04 16:04:01 +02002290 def test_expandtabs_optimization(self):
2291 s = 'abc'
2292 self.assertIs(s.expandtabs(), s)
2293
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002294 def test_raiseMemError(self):
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002295 if struct.calcsize('P') == 8:
2296 # 64 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002297 ascii_struct_size = 48
2298 compact_struct_size = 72
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002299 else:
2300 # 32 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002301 ascii_struct_size = 24
2302 compact_struct_size = 36
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002303
2304 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
2305 code = ord(char)
2306 if code < 0x100:
2307 char_size = 1 # sizeof(Py_UCS1)
2308 struct_size = ascii_struct_size
2309 elif code < 0x10000:
2310 char_size = 2 # sizeof(Py_UCS2)
2311 struct_size = compact_struct_size
2312 else:
2313 char_size = 4 # sizeof(Py_UCS4)
2314 struct_size = compact_struct_size
2315 # Note: sys.maxsize is half of the actual max allocation because of
Martin v. Löwis287eca62011-09-28 10:03:28 +02002316 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2317 # be allocatable, given enough memory.
2318 maxlen = ((sys.maxsize - struct_size) // char_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002319 alloc = lambda: char * maxlen
2320 self.assertRaises(MemoryError, alloc)
2321 self.assertRaises(MemoryError, alloc)
Antoine Pitrou3db3e872008-08-17 17:06:51 +00002322
Victor Stinner808fc0a2010-03-22 12:50:40 +00002323 def test_format_subclass(self):
2324 class S(str):
2325 def __str__(self):
2326 return '__str__ overridden'
2327 s = S('xxx')
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002328 self.assertEqual("%s" % s, '__str__ overridden')
2329 self.assertEqual("{}".format(s), '__str__ overridden')
Victor Stinner808fc0a2010-03-22 12:50:40 +00002330
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002331 def test_subclass_add(self):
2332 class S(str):
2333 def __add__(self, o):
2334 return "3"
2335 self.assertEqual(S("4") + S("5"), "3")
2336 class S(str):
2337 def __iadd__(self, o):
2338 return "3"
2339 s = S("1")
2340 s += "4"
2341 self.assertEqual(s, "3")
2342
2343 def test_getnewargs(self):
2344 text = 'abc'
2345 args = text.__getnewargs__()
2346 self.assertIsNot(args[0], text)
2347 self.assertEqual(args[0], text)
2348 self.assertEqual(len(args), 1)
2349
Inada Naoki6a16b182019-03-18 15:44:11 +09002350 @support.cpython_only
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002351 def test_resize(self):
Inada Naoki6a16b182019-03-18 15:44:11 +09002352 from _testcapi import getargs_u
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002353 for length in range(1, 100, 7):
2354 # generate a fresh string (refcount=1)
2355 text = 'a' * length + 'b'
2356
Inada Naoki6a16b182019-03-18 15:44:11 +09002357 # fill wstr internal field
2358 abc = getargs_u(text)
2359 self.assertEqual(abc, text)
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002360
Inada Naoki6a16b182019-03-18 15:44:11 +09002361 # resize text: wstr field must be cleared and then recomputed
2362 text += 'c'
2363 abcdef = getargs_u(text)
2364 self.assertNotEqual(abc, abcdef)
2365 self.assertEqual(abcdef, text)
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002366
2367 def test_compare(self):
2368 # Issue #17615
2369 N = 10
2370 ascii = 'a' * N
2371 ascii2 = 'z' * N
2372 latin = '\x80' * N
2373 latin2 = '\xff' * N
2374 bmp = '\u0100' * N
2375 bmp2 = '\uffff' * N
2376 astral = '\U00100000' * N
2377 astral2 = '\U0010ffff' * N
2378 strings = (
2379 ascii, ascii2,
2380 latin, latin2,
2381 bmp, bmp2,
2382 astral, astral2)
2383 for text1, text2 in itertools.combinations(strings, 2):
2384 equal = (text1 is text2)
2385 self.assertEqual(text1 == text2, equal)
2386 self.assertEqual(text1 != text2, not equal)
2387
2388 if equal:
2389 self.assertTrue(text1 <= text2)
2390 self.assertTrue(text1 >= text2)
2391
2392 # text1 is text2: duplicate strings to skip the "str1 == str2"
2393 # optimization in unicode_compare_eq() and really compare
2394 # character per character
2395 copy1 = duplicate_string(text1)
2396 copy2 = duplicate_string(text2)
2397 self.assertIsNot(copy1, copy2)
2398
2399 self.assertTrue(copy1 == copy2)
2400 self.assertFalse(copy1 != copy2)
2401
2402 self.assertTrue(copy1 <= copy2)
2403 self.assertTrue(copy2 >= copy2)
2404
2405 self.assertTrue(ascii < ascii2)
2406 self.assertTrue(ascii < latin)
2407 self.assertTrue(ascii < bmp)
2408 self.assertTrue(ascii < astral)
2409 self.assertFalse(ascii >= ascii2)
2410 self.assertFalse(ascii >= latin)
2411 self.assertFalse(ascii >= bmp)
2412 self.assertFalse(ascii >= astral)
2413
2414 self.assertFalse(latin < ascii)
2415 self.assertTrue(latin < latin2)
2416 self.assertTrue(latin < bmp)
2417 self.assertTrue(latin < astral)
2418 self.assertTrue(latin >= ascii)
2419 self.assertFalse(latin >= latin2)
2420 self.assertFalse(latin >= bmp)
2421 self.assertFalse(latin >= astral)
2422
2423 self.assertFalse(bmp < ascii)
2424 self.assertFalse(bmp < latin)
2425 self.assertTrue(bmp < bmp2)
2426 self.assertTrue(bmp < astral)
2427 self.assertTrue(bmp >= ascii)
2428 self.assertTrue(bmp >= latin)
2429 self.assertFalse(bmp >= bmp2)
2430 self.assertFalse(bmp >= astral)
2431
2432 self.assertFalse(astral < ascii)
2433 self.assertFalse(astral < latin)
2434 self.assertFalse(astral < bmp2)
2435 self.assertTrue(astral < astral2)
2436 self.assertTrue(astral >= ascii)
2437 self.assertTrue(astral >= latin)
2438 self.assertTrue(astral >= bmp2)
2439 self.assertFalse(astral >= astral2)
2440
2441 def test_free_after_iterating(self):
2442 support.check_free_after_iterating(self, iter, str)
2443 support.check_free_after_iterating(self, reversed, str)
2444
Victor Stinner22eb6892019-06-26 00:51:05 +02002445 def test_check_encoding_errors(self):
2446 # bpo-37388: str(bytes) and str.decode() must check encoding and errors
2447 # arguments in dev mode
2448 encodings = ('ascii', 'utf8', 'latin1')
2449 invalid = 'Boom, Shaka Laka, Boom!'
2450 code = textwrap.dedent(f'''
2451 import sys
2452 encodings = {encodings!r}
2453
2454 for data in (b'', b'short string'):
2455 try:
2456 str(data, encoding={invalid!r})
2457 except LookupError:
2458 pass
2459 else:
2460 sys.exit(21)
2461
2462 try:
2463 str(data, errors={invalid!r})
2464 except LookupError:
2465 pass
2466 else:
2467 sys.exit(22)
2468
2469 for encoding in encodings:
2470 try:
2471 str(data, encoding, errors={invalid!r})
2472 except LookupError:
2473 pass
2474 else:
2475 sys.exit(22)
2476
2477 for data in ('', 'short string'):
2478 try:
2479 data.encode(encoding={invalid!r})
2480 except LookupError:
2481 pass
2482 else:
2483 sys.exit(23)
2484
2485 try:
2486 data.encode(errors={invalid!r})
2487 except LookupError:
2488 pass
2489 else:
2490 sys.exit(24)
2491
2492 for encoding in encodings:
2493 try:
2494 data.encode(encoding, errors={invalid!r})
2495 except LookupError:
2496 pass
2497 else:
2498 sys.exit(24)
2499
2500 sys.exit(10)
2501 ''')
2502 proc = assert_python_failure('-X', 'dev', '-c', code)
2503 self.assertEqual(proc.rc, 10, proc)
2504
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002505
2506class CAPITest(unittest.TestCase):
2507
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002508 # Test PyUnicode_FromFormat()
Victor Stinner1205f272010-09-11 00:54:47 +00002509 def test_from_format(self):
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002510 support.import_module('ctypes')
Victor Stinner15a11362012-10-06 23:48:20 +02002511 from ctypes import (
2512 pythonapi, py_object, sizeof,
Victor Stinner6d970f42011-03-02 00:04:25 +00002513 c_int, c_long, c_longlong, c_ssize_t,
Victor Stinner15a11362012-10-06 23:48:20 +02002514 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002515 name = "PyUnicode_FromFormat"
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002516 _PyUnicode_FromFormat = getattr(pythonapi, name)
2517 _PyUnicode_FromFormat.restype = py_object
2518
2519 def PyUnicode_FromFormat(format, *args):
2520 cargs = tuple(
2521 py_object(arg) if isinstance(arg, str) else arg
2522 for arg in args)
2523 return _PyUnicode_FromFormat(format, *cargs)
Victor Stinner1205f272010-09-11 00:54:47 +00002524
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002525 def check_format(expected, format, *args):
2526 text = PyUnicode_FromFormat(format, *args)
2527 self.assertEqual(expected, text)
2528
Victor Stinner1205f272010-09-11 00:54:47 +00002529 # ascii format, non-ascii argument
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002530 check_format('ascii\x7f=unicode\xe9',
2531 b'ascii\x7f=%U', 'unicode\xe9')
Victor Stinner1205f272010-09-11 00:54:47 +00002532
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002533 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
2534 # raises an error
Ezio Melottied3a7d22010-12-01 02:32:32 +00002535 self.assertRaisesRegex(ValueError,
R David Murray44b548d2016-09-08 13:59:53 -04002536 r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
Victor Stinner4c7db312010-09-12 07:51:18 +00002537 'string, got a non-ASCII byte: 0xe9$',
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002538 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002539
Victor Stinner96865452011-03-01 23:44:09 +00002540 # test "%c"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002541 check_format('\uabcd',
2542 b'%c', c_int(0xabcd))
2543 check_format('\U0010ffff',
2544 b'%c', c_int(0x10ffff))
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002545 with self.assertRaises(OverflowError):
2546 PyUnicode_FromFormat(b'%c', c_int(0x110000))
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +03002547 # Issue #18183
Serhiy Storchakaf15ffe02013-06-12 09:28:20 +03002548 check_format('\U00010000\U00100000',
2549 b'%c%c', c_int(0x10000), c_int(0x100000))
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002550
Victor Stinner96865452011-03-01 23:44:09 +00002551 # test "%"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002552 check_format('%',
2553 b'%')
2554 check_format('%',
2555 b'%%')
2556 check_format('%s',
2557 b'%%s')
2558 check_format('[%]',
2559 b'[%%]')
2560 check_format('%abc',
2561 b'%%%s', b'abc')
2562
2563 # truncated string
2564 check_format('abc',
2565 b'%.3s', b'abcdef')
2566 check_format('abc[\ufffd',
2567 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
2568 check_format("'\\u20acABC'",
2569 b'%A', '\u20acABC')
2570 check_format("'\\u20",
2571 b'%.5A', '\u20acABCDEF')
2572 check_format("'\u20acABC'",
2573 b'%R', '\u20acABC')
2574 check_format("'\u20acA",
2575 b'%.3R', '\u20acABCDEF')
2576 check_format('\u20acAB',
2577 b'%.3S', '\u20acABCDEF')
2578 check_format('\u20acAB',
2579 b'%.3U', '\u20acABCDEF')
2580 check_format('\u20acAB',
2581 b'%.3V', '\u20acABCDEF', None)
2582 check_format('abc[\ufffd',
2583 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
2584
2585 # following tests comes from #7330
2586 # test width modifier and precision modifier with %S
2587 check_format("repr= abc",
2588 b'repr=%5S', 'abc')
2589 check_format("repr=ab",
2590 b'repr=%.2S', 'abc')
2591 check_format("repr= ab",
2592 b'repr=%5.2S', 'abc')
2593
2594 # test width modifier and precision modifier with %R
2595 check_format("repr= 'abc'",
2596 b'repr=%8R', 'abc')
2597 check_format("repr='ab",
2598 b'repr=%.3R', 'abc')
2599 check_format("repr= 'ab",
2600 b'repr=%5.3R', 'abc')
2601
2602 # test width modifier and precision modifier with %A
2603 check_format("repr= 'abc'",
2604 b'repr=%8A', 'abc')
2605 check_format("repr='ab",
2606 b'repr=%.3A', 'abc')
2607 check_format("repr= 'ab",
2608 b'repr=%5.3A', 'abc')
2609
2610 # test width modifier and precision modifier with %s
2611 check_format("repr= abc",
2612 b'repr=%5s', b'abc')
2613 check_format("repr=ab",
2614 b'repr=%.2s', b'abc')
2615 check_format("repr= ab",
2616 b'repr=%5.2s', b'abc')
2617
2618 # test width modifier and precision modifier with %U
2619 check_format("repr= abc",
2620 b'repr=%5U', 'abc')
2621 check_format("repr=ab",
2622 b'repr=%.2U', 'abc')
2623 check_format("repr= ab",
2624 b'repr=%5.2U', 'abc')
2625
2626 # test width modifier and precision modifier with %V
2627 check_format("repr= abc",
2628 b'repr=%5V', 'abc', b'123')
2629 check_format("repr=ab",
2630 b'repr=%.2V', 'abc', b'123')
2631 check_format("repr= ab",
2632 b'repr=%5.2V', 'abc', b'123')
2633 check_format("repr= 123",
2634 b'repr=%5V', None, b'123')
2635 check_format("repr=12",
2636 b'repr=%.2V', None, b'123')
2637 check_format("repr= 12",
2638 b'repr=%5.2V', None, b'123')
Victor Stinner96865452011-03-01 23:44:09 +00002639
Victor Stinner6d970f42011-03-02 00:04:25 +00002640 # test integer formats (%i, %d, %u)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 check_format('010',
2642 b'%03i', c_int(10))
2643 check_format('0010',
2644 b'%0.4i', c_int(10))
2645 check_format('-123',
2646 b'%i', c_int(-123))
2647 check_format('-123',
2648 b'%li', c_long(-123))
2649 check_format('-123',
2650 b'%lli', c_longlong(-123))
2651 check_format('-123',
2652 b'%zi', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002653
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002654 check_format('-123',
2655 b'%d', c_int(-123))
2656 check_format('-123',
2657 b'%ld', c_long(-123))
2658 check_format('-123',
2659 b'%lld', c_longlong(-123))
2660 check_format('-123',
2661 b'%zd', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002662
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002663 check_format('123',
2664 b'%u', c_uint(123))
2665 check_format('123',
2666 b'%lu', c_ulong(123))
2667 check_format('123',
2668 b'%llu', c_ulonglong(123))
2669 check_format('123',
2670 b'%zu', c_size_t(123))
Victor Stinner6d970f42011-03-02 00:04:25 +00002671
Victor Stinner15a11362012-10-06 23:48:20 +02002672 # test long output
2673 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
2674 max_longlong = -min_longlong - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002675 check_format(str(min_longlong),
2676 b'%lld', c_longlong(min_longlong))
2677 check_format(str(max_longlong),
2678 b'%lld', c_longlong(max_longlong))
Victor Stinner15a11362012-10-06 23:48:20 +02002679 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002680 check_format(str(max_ulonglong),
2681 b'%llu', c_ulonglong(max_ulonglong))
Victor Stinner15a11362012-10-06 23:48:20 +02002682 PyUnicode_FromFormat(b'%p', c_void_p(-1))
2683
Victor Stinnere215d962012-10-06 23:03:36 +02002684 # test padding (width and/or precision)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002685 check_format('123'.rjust(10, '0'),
2686 b'%010i', c_int(123))
2687 check_format('123'.rjust(100),
2688 b'%100i', c_int(123))
2689 check_format('123'.rjust(100, '0'),
2690 b'%.100i', c_int(123))
2691 check_format('123'.rjust(80, '0').rjust(100),
2692 b'%100.80i', c_int(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002693
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002694 check_format('123'.rjust(10, '0'),
2695 b'%010u', c_uint(123))
2696 check_format('123'.rjust(100),
2697 b'%100u', c_uint(123))
2698 check_format('123'.rjust(100, '0'),
2699 b'%.100u', c_uint(123))
2700 check_format('123'.rjust(80, '0').rjust(100),
2701 b'%100.80u', c_uint(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002702
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002703 check_format('123'.rjust(10, '0'),
2704 b'%010x', c_int(0x123))
2705 check_format('123'.rjust(100),
2706 b'%100x', c_int(0x123))
2707 check_format('123'.rjust(100, '0'),
2708 b'%.100x', c_int(0x123))
2709 check_format('123'.rjust(80, '0').rjust(100),
2710 b'%100.80x', c_int(0x123))
Victor Stinnere215d962012-10-06 23:03:36 +02002711
Victor Stinner6d970f42011-03-02 00:04:25 +00002712 # test %A
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002713 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
2714 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
Victor Stinner9a909002010-10-18 20:59:24 +00002715
Victor Stinner6d970f42011-03-02 00:04:25 +00002716 # test %V
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002717 check_format('repr=abc',
2718 b'repr=%V', 'abc', b'xyz')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002719
2720 # Test string decode from parameter of %s using utf-8.
2721 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
2722 # '\u4eba\u6c11'
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002723 check_format('repr=\u4eba\u6c11',
2724 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002725
2726 #Test replace error handler.
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002727 check_format('repr=abc\ufffd',
2728 b'repr=%V', None, b'abc\xff')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002729
Victor Stinner6d970f42011-03-02 00:04:25 +00002730 # not supported: copy the raw format string. these tests are just here
Martin Panter2f9171d2016-12-18 01:23:09 +00002731 # to check for crashes and should not be considered as specifications
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002732 check_format('%s',
2733 b'%1%s', b'abc')
2734 check_format('%1abc',
2735 b'%1abc')
2736 check_format('%+i',
2737 b'%+i', c_int(10))
2738 check_format('%.%s',
2739 b'%.%s', b'abc')
Victor Stinner6d970f42011-03-02 00:04:25 +00002740
Serhiy Storchaka44cc4822019-01-12 09:22:29 +02002741 # Issue #33817: empty strings
2742 check_format('',
2743 b'')
2744 check_format('',
2745 b'%s', b'')
2746
Victor Stinner1c24bd02010-10-02 11:03:13 +00002747 # Test PyUnicode_AsWideChar()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002748 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002749 def test_aswidechar(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002750 from _testcapi import unicode_aswidechar
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002751 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002752 from ctypes import c_wchar, sizeof
2753
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002754 wchar, size = unicode_aswidechar('abcdef', 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002755 self.assertEqual(size, 2)
2756 self.assertEqual(wchar, 'ab')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002757
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002758 wchar, size = unicode_aswidechar('abc', 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002759 self.assertEqual(size, 3)
2760 self.assertEqual(wchar, 'abc')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002761
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002762 wchar, size = unicode_aswidechar('abc', 4)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002763 self.assertEqual(size, 3)
2764 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002765
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002766 wchar, size = unicode_aswidechar('abc', 10)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002767 self.assertEqual(size, 3)
2768 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002769
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002770 wchar, size = unicode_aswidechar('abc\0def', 20)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002771 self.assertEqual(size, 7)
2772 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002773
Victor Stinner5593d8a2010-10-02 11:11:27 +00002774 nonbmp = chr(0x10ffff)
2775 if sizeof(c_wchar) == 2:
2776 buflen = 3
2777 nchar = 2
2778 else: # sizeof(c_wchar) == 4
2779 buflen = 2
2780 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002781 wchar, size = unicode_aswidechar(nonbmp, buflen)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002782 self.assertEqual(size, nchar)
2783 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002784
Victor Stinner1c24bd02010-10-02 11:03:13 +00002785 # Test PyUnicode_AsWideCharString()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002786 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002787 def test_aswidecharstring(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002788 from _testcapi import unicode_aswidecharstring
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002789 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002790 from ctypes import c_wchar, sizeof
2791
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002792 wchar, size = unicode_aswidecharstring('abc')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002793 self.assertEqual(size, 3)
2794 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002795
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002796 wchar, size = unicode_aswidecharstring('abc\0def')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002797 self.assertEqual(size, 7)
2798 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002799
Victor Stinner5593d8a2010-10-02 11:11:27 +00002800 nonbmp = chr(0x10ffff)
2801 if sizeof(c_wchar) == 2:
2802 nchar = 2
2803 else: # sizeof(c_wchar) == 4
2804 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002805 wchar, size = unicode_aswidecharstring(nonbmp)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002806 self.assertEqual(size, nchar)
2807 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002808
Serhiy Storchakacc164232016-10-02 21:29:26 +03002809 # Test PyUnicode_AsUCS4()
2810 @support.cpython_only
2811 def test_asucs4(self):
2812 from _testcapi import unicode_asucs4
2813 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
2814 'a\ud800b\udfffc', '\ud834\udd1e']:
2815 l = len(s)
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002816 self.assertEqual(unicode_asucs4(s, l, True), s+'\0')
2817 self.assertEqual(unicode_asucs4(s, l, False), s+'\uffff')
2818 self.assertEqual(unicode_asucs4(s, l+1, True), s+'\0\uffff')
2819 self.assertEqual(unicode_asucs4(s, l+1, False), s+'\0\uffff')
2820 self.assertRaises(SystemError, unicode_asucs4, s, l-1, True)
2821 self.assertRaises(SystemError, unicode_asucs4, s, l-2, False)
Serhiy Storchakacc164232016-10-02 21:29:26 +03002822 s = '\0'.join([s, s])
Serhiy Storchaka1f21eaa2019-09-01 12:16:51 +03002823 self.assertEqual(unicode_asucs4(s, len(s), True), s+'\0')
2824 self.assertEqual(unicode_asucs4(s, len(s), False), s+'\uffff')
Serhiy Storchakacc164232016-10-02 21:29:26 +03002825
Hai Shi5623ac82019-07-20 02:56:23 -05002826 # Test PyUnicode_AsUTF8()
2827 @support.cpython_only
2828 def test_asutf8(self):
2829 from _testcapi import unicode_asutf8
2830
2831 bmp = '\u0100'
2832 bmp2 = '\uffff'
2833 nonbmp = chr(0x10ffff)
2834
2835 self.assertEqual(unicode_asutf8(bmp), b'\xc4\x80')
2836 self.assertEqual(unicode_asutf8(bmp2), b'\xef\xbf\xbf')
2837 self.assertEqual(unicode_asutf8(nonbmp), b'\xf4\x8f\xbf\xbf')
2838 self.assertRaises(UnicodeEncodeError, unicode_asutf8, 'a\ud800b\udfffc')
2839
2840 # Test PyUnicode_AsUTF8AndSize()
2841 @support.cpython_only
2842 def test_asutf8andsize(self):
2843 from _testcapi import unicode_asutf8andsize
2844
2845 bmp = '\u0100'
2846 bmp2 = '\uffff'
2847 nonbmp = chr(0x10ffff)
2848
2849 self.assertEqual(unicode_asutf8andsize(bmp), (b'\xc4\x80', 2))
2850 self.assertEqual(unicode_asutf8andsize(bmp2), (b'\xef\xbf\xbf', 3))
2851 self.assertEqual(unicode_asutf8andsize(nonbmp), (b'\xf4\x8f\xbf\xbf', 4))
2852 self.assertRaises(UnicodeEncodeError, unicode_asutf8andsize, 'a\ud800b\udfffc')
2853
Xiang Zhangb2110682016-12-20 22:52:33 +08002854 # Test PyUnicode_FindChar()
2855 @support.cpython_only
2856 def test_findchar(self):
2857 from _testcapi import unicode_findchar
2858
2859 for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1":
2860 for i, ch in enumerate(str):
2861 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), 1), i)
2862 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), -1), i)
2863
2864 str = "!>_<!"
2865 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), 1), -1)
2866 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), -1), -1)
2867 # start < end
2868 self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, 1), 4)
2869 self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, -1), 4)
2870 # start >= end
2871 self.assertEqual(unicode_findchar(str, ord('!'), 0, 0, 1), -1)
2872 self.assertEqual(unicode_findchar(str, ord('!'), len(str), 0, 1), -1)
2873 # negative
2874 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, 1), 0)
2875 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, -1), 0)
2876
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03002877 # Test PyUnicode_CopyCharacters()
2878 @support.cpython_only
2879 def test_copycharacters(self):
2880 from _testcapi import unicode_copycharacters
2881
2882 strings = [
2883 'abcde', '\xa1\xa2\xa3\xa4\xa5',
2884 '\u4f60\u597d\u4e16\u754c\uff01',
2885 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
2886 ]
2887
2888 for idx, from_ in enumerate(strings):
2889 # wide -> narrow: exceed maxchar limitation
2890 for to in strings[:idx]:
2891 self.assertRaises(
2892 SystemError,
2893 unicode_copycharacters, to, 0, from_, 0, 5
2894 )
2895 # same kind
2896 for from_start in range(5):
2897 self.assertEqual(
2898 unicode_copycharacters(from_, 0, from_, from_start, 5),
2899 (from_[from_start:from_start+5].ljust(5, '\0'),
2900 5-from_start)
2901 )
2902 for to_start in range(5):
2903 self.assertEqual(
2904 unicode_copycharacters(from_, to_start, from_, to_start, 5),
2905 (from_[to_start:to_start+5].rjust(5, '\0'),
2906 5-to_start)
2907 )
2908 # narrow -> wide
2909 # Tests omitted since this creates invalid strings.
2910
2911 s = strings[0]
2912 self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
2913 self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
2914 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
2915 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
2916 self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
2917 self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
2918 self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
2919
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002920 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002921 def test_encode_decimal(self):
2922 from _testcapi import unicode_encodedecimal
2923 self.assertEqual(unicode_encodedecimal('123'),
2924 b'123')
2925 self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
2926 b'3.14')
2927 self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2928 b' 3.14 ')
2929 self.assertRaises(UnicodeEncodeError,
2930 unicode_encodedecimal, "123\u20ac", "strict")
Victor Stinner6345be92011-11-25 20:09:01 +01002931 self.assertRaisesRegex(
2932 ValueError,
2933 "^'decimal' codec can't encode character",
2934 unicode_encodedecimal, "123\u20ac", "replace")
Victor Stinner42bf7752011-11-21 22:52:58 +01002935
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002936 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002937 def test_transform_decimal(self):
2938 from _testcapi import unicode_transformdecimaltoascii as transform_decimal
2939 self.assertEqual(transform_decimal('123'),
2940 '123')
2941 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
2942 '3.14')
2943 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2944 "\N{EM SPACE}3.14\N{EN SPACE}")
2945 self.assertEqual(transform_decimal('123\u20ac'),
2946 '123\u20ac')
2947
Serhiy Storchaka7aa69082015-12-03 01:02:03 +02002948 @support.cpython_only
2949 def test_pep393_utf8_caching_bug(self):
2950 # Issue #25709: Problem with string concatenation and utf-8 cache
2951 from _testcapi import getargs_s_hash
2952 for k in 0x24, 0xa4, 0x20ac, 0x1f40d:
2953 s = ''
2954 for i in range(5):
2955 # Due to CPython specific optimization the 's' string can be
2956 # resized in-place.
2957 s += chr(k)
2958 # Parsing with the "s#" format code calls indirectly
2959 # PyUnicode_AsUTF8AndSize() which creates the UTF-8
2960 # encoded string cached in the Unicode object.
2961 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
2962 # Check that the second call returns the same result
2963 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
2964
Eric Smitha1eac722011-01-29 11:15:35 +00002965class StringModuleTest(unittest.TestCase):
2966 def test_formatter_parser(self):
2967 def parse(format):
2968 return list(_string.formatter_parser(format))
2969
2970 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2971 self.assertEqual(formatter, [
2972 ('prefix ', '2', '', 's'),
2973 ('xxx', '0', '^+10.3f', None),
2974 ('', 'obj.attr', '', 's'),
2975 (' ', 'z[0]', '10', 's'),
2976 ])
2977
2978 formatter = parse("prefix {} suffix")
2979 self.assertEqual(formatter, [
2980 ('prefix ', '', '', None),
2981 (' suffix', None, None, None),
2982 ])
2983
2984 formatter = parse("str")
2985 self.assertEqual(formatter, [
2986 ('str', None, None, None),
2987 ])
2988
2989 formatter = parse("")
2990 self.assertEqual(formatter, [])
2991
2992 formatter = parse("{0}")
2993 self.assertEqual(formatter, [
2994 ('', '0', '', None),
2995 ])
2996
2997 self.assertRaises(TypeError, _string.formatter_parser, 1)
2998
2999 def test_formatter_field_name_split(self):
3000 def split(name):
3001 items = list(_string.formatter_field_name_split(name))
3002 items[1] = list(items[1])
3003 return items
3004 self.assertEqual(split("obj"), ["obj", []])
3005 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
3006 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
3007 self.assertEqual(split("obj.arg[key1][key2]"), [
3008 "obj",
3009 [(True, 'arg'),
3010 (False, 'key1'),
3011 (False, 'key2'),
3012 ]])
3013 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
3014
3015
Walter Dörwald28256f22003-01-19 16:59:20 +00003016if __name__ == "__main__":
Ezio Melotti0dceb562013-01-10 07:43:26 +02003017 unittest.main()