blob: 86ebd45e7b031daf9b15709e5fc4d6cd15888ad1 [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
R David Murray110b6fe2016-09-08 15:34:08 -040013import string
Guido van Rossum98297ee2007-11-06 21:34:58 +000014import sys
15import unittest
16import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000017from test import support, string_tests
Guido van Rossuma831cac2000-03-10 23:23:21 +000018
Neal Norwitz430f68b2005-11-24 22:00:56 +000019# Error handling (bad decoder return)
20def search_function(encoding):
21 def decode1(input, errors="strict"):
22 return 42 # not a tuple
23 def encode1(input, errors="strict"):
24 return 42 # not a tuple
25 def encode2(input, errors="strict"):
26 return (42, 42) # no unicode
27 def decode2(input, errors="strict"):
28 return (42, 42) # no unicode
29 if encoding=="test.unicode1":
30 return (encode1, decode1, None, None)
31 elif encoding=="test.unicode2":
32 return (encode2, decode2, None, None)
33 else:
34 return None
35codecs.register(search_function)
36
Victor Stinner9fc59812013-04-08 22:34:43 +020037def duplicate_string(text):
38 """
39 Try to get a fresh clone of the specified text:
40 new object with a reference count of 1.
41
42 This is a best-effort: latin1 single letters and the empty
43 string ('') are singletons and cannot be cloned.
44 """
45 return text.encode().decode()
46
Serhiy Storchaka15095802015-11-25 15:47:01 +020047class StrSubclass(str):
48 pass
49
Brett Cannon226b2302010-03-20 22:22:22 +000050class UnicodeTest(string_tests.CommonTest,
51 string_tests.MixinStrUnicodeUserStringTest,
Ezio Melotti0dceb562013-01-10 07:43:26 +020052 string_tests.MixinStrUnicodeTest,
53 unittest.TestCase):
Brett Cannon226b2302010-03-20 22:22:22 +000054
Guido van Rossumef87d6e2007-05-02 19:09:54 +000055 type2test = str
Walter Dörwald0fd583c2003-02-21 12:53:50 +000056
57 def checkequalnofix(self, result, object, methodname, *args):
58 method = getattr(object, methodname)
59 realresult = method(*args)
60 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000061 self.assertTrue(type(realresult) is type(result))
Walter Dörwald0fd583c2003-02-21 12:53:50 +000062
63 # if the original is returned make sure that
64 # this doesn't happen with subclasses
65 if realresult is object:
Guido van Rossumef87d6e2007-05-02 19:09:54 +000066 class usub(str):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000067 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000068 return 'usub(%r)' % str.__repr__(self)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000069 object = usub(object)
70 method = getattr(object, methodname)
71 realresult = method(*args)
72 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000073 self.assertTrue(object is not realresult)
Guido van Rossume4874ae2001-09-21 15:36:41 +000074
Jeremy Hylton504de6b2003-10-06 05:08:26 +000075 def test_literals(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000076 self.assertEqual('\xff', '\u00ff')
77 self.assertEqual('\uffff', '\U0000ffff')
Guido van Rossum36e0a922007-07-20 04:05:57 +000078 self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
79 self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
80 self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
Benjamin Petersoncd76c272008-04-05 15:09:30 +000081 # raw strings should not have unicode escapes
Florent Xiclunaa87b3832010-09-13 02:28:18 +000082 self.assertNotEqual(r"\u0020", " ")
Jeremy Hylton504de6b2003-10-06 05:08:26 +000083
Georg Brandl559e5d72008-06-11 18:37:52 +000084 def test_ascii(self):
85 if not sys.platform.startswith('java'):
86 # Test basic sanity of repr()
87 self.assertEqual(ascii('abc'), "'abc'")
88 self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
89 self.assertEqual(ascii('ab\\'), "'ab\\\\'")
90 self.assertEqual(ascii('\\c'), "'\\\\c'")
91 self.assertEqual(ascii('\\'), "'\\\\'")
92 self.assertEqual(ascii('\n'), "'\\n'")
93 self.assertEqual(ascii('\r'), "'\\r'")
94 self.assertEqual(ascii('\t'), "'\\t'")
95 self.assertEqual(ascii('\b'), "'\\x08'")
96 self.assertEqual(ascii("'\""), """'\\'"'""")
97 self.assertEqual(ascii("'\""), """'\\'"'""")
98 self.assertEqual(ascii("'"), '''"'"''')
99 self.assertEqual(ascii('"'), """'"'""")
100 latin1repr = (
101 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
102 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
103 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
104 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
105 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
106 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
107 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
108 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
109 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
110 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
111 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
112 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
113 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
114 "\\xfe\\xff'")
115 testrepr = ascii(''.join(map(chr, range(256))))
116 self.assertEqual(testrepr, latin1repr)
117 # Test ascii works on wide unicode escapes without overflow.
118 self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
119 ascii("\U00010000" * 39 + "\uffff" * 4096))
120
121 class WrongRepr:
122 def __repr__(self):
123 return b'byte-repr'
124 self.assertRaises(TypeError, ascii, WrongRepr())
125
Walter Dörwald28256f22003-01-19 16:59:20 +0000126 def test_repr(self):
127 if not sys.platform.startswith('java'):
128 # Test basic sanity of repr()
Walter Dörwald67e83882007-05-05 12:26:27 +0000129 self.assertEqual(repr('abc'), "'abc'")
130 self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
131 self.assertEqual(repr('ab\\'), "'ab\\\\'")
132 self.assertEqual(repr('\\c'), "'\\\\c'")
133 self.assertEqual(repr('\\'), "'\\\\'")
134 self.assertEqual(repr('\n'), "'\\n'")
135 self.assertEqual(repr('\r'), "'\\r'")
136 self.assertEqual(repr('\t'), "'\\t'")
137 self.assertEqual(repr('\b'), "'\\x08'")
138 self.assertEqual(repr("'\""), """'\\'"'""")
139 self.assertEqual(repr("'\""), """'\\'"'""")
140 self.assertEqual(repr("'"), '''"'"''')
141 self.assertEqual(repr('"'), """'"'""")
Walter Dörwald28256f22003-01-19 16:59:20 +0000142 latin1repr = (
Walter Dörwald67e83882007-05-05 12:26:27 +0000143 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
Walter Dörwald28256f22003-01-19 16:59:20 +0000144 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
145 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
146 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
147 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
148 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
Georg Brandl559e5d72008-06-11 18:37:52 +0000149 "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
150 "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
151 "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
152 "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
153 "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
154 "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
155 "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
156 "\xfe\xff'")
Guido van Rossum805365e2007-05-07 22:24:25 +0000157 testrepr = repr(''.join(map(chr, range(256))))
Walter Dörwald28256f22003-01-19 16:59:20 +0000158 self.assertEqual(testrepr, latin1repr)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000159 # Test repr works on wide unicode escapes without overflow.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000160 self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
161 repr("\U00010000" * 39 + "\uffff" * 4096))
Walter Dörwald28256f22003-01-19 16:59:20 +0000162
Georg Brandl559e5d72008-06-11 18:37:52 +0000163 class WrongRepr:
164 def __repr__(self):
165 return b'byte-repr'
166 self.assertRaises(TypeError, repr, WrongRepr())
167
Guido van Rossum49d6b072006-08-17 21:11:47 +0000168 def test_iterators(self):
169 # Make sure unicode objects have an __iter__ method
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000170 it = "\u1111\u2222\u3333".__iter__()
171 self.assertEqual(next(it), "\u1111")
172 self.assertEqual(next(it), "\u2222")
173 self.assertEqual(next(it), "\u3333")
Georg Brandla18af4e2007-04-21 15:47:16 +0000174 self.assertRaises(StopIteration, next, it)
Guido van Rossum49d6b072006-08-17 21:11:47 +0000175
Walter Dörwald28256f22003-01-19 16:59:20 +0000176 def test_count(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000177 string_tests.CommonTest.test_count(self)
178 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000179 self.checkequalnofix(3, 'aaa', 'count', 'a')
180 self.checkequalnofix(0, 'aaa', 'count', 'b')
181 self.checkequalnofix(3, 'aaa', 'count', 'a')
182 self.checkequalnofix(0, 'aaa', 'count', 'b')
183 self.checkequalnofix(0, 'aaa', 'count', 'b')
184 self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
185 self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
186 self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
187 self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200188 # test mixed kinds
189 self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
190 self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
191 self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
192 self.checkequal(0, 'a' * 10, 'count', '\u0102')
193 self.checkequal(0, 'a' * 10, 'count', '\U00100304')
194 self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
195 self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
196 self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
197 self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
198 self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
199 self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
200 self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000201
Walter Dörwald28256f22003-01-19 16:59:20 +0000202 def test_find(self):
Antoine Pitrouc0bbe7d2011-10-08 22:41:35 +0200203 string_tests.CommonTest.test_find(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200204 # test implementation details of the memchr fast path
205 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
206 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
207 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
208 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
209 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
210 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
211 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
212 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000213 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
214 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
215 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000216
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000217 self.assertRaises(TypeError, 'hello'.find)
218 self.assertRaises(TypeError, 'hello'.find, 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200219 # test mixed kinds
220 self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
221 self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
222 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
223 self.checkequal(-1, 'a' * 100, 'find', '\u0102')
224 self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
225 self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
226 self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
227 self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
228 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
229 self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
230 self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
231 self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000232
Walter Dörwald28256f22003-01-19 16:59:20 +0000233 def test_rfind(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000234 string_tests.CommonTest.test_rfind(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200235 # test implementation details of the memrchr fast path
236 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
237 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
238 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
239 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
240 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
241 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
242 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000243 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000244 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
245 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
246 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200247 # test mixed kinds
248 self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
249 self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
250 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
251 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
252 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
253 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
254 self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
255 self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
256 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
257 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
258 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
259 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
Guido van Rossum8b264542000-12-19 02:22:31 +0000260
Walter Dörwald28256f22003-01-19 16:59:20 +0000261 def test_index(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000262 string_tests.CommonTest.test_index(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000263 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
264 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
265 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
266 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
267 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
268 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
269 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
270 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200271 # test mixed kinds
272 self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
273 self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
274 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
275 self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
276 self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
277 self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
278 self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
279 self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
280 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
281 self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
282 self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
283 self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000284
Walter Dörwald28256f22003-01-19 16:59:20 +0000285 def test_rindex(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000286 string_tests.CommonTest.test_rindex(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000287 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
288 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
289 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
290 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000291
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000292 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
293 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
294 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
295 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
296 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200297 # test mixed kinds
298 self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
299 self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
300 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
301 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
302 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
303 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
304 self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
305 self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
306 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
307 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
308 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
309 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000310
Georg Brandlceee0772007-11-27 23:48:05 +0000311 def test_maketrans_translate(self):
312 # these work with plain translate()
313 self.checkequalnofix('bbbc', 'abababc', 'translate',
314 {ord('a'): None})
315 self.checkequalnofix('iiic', 'abababc', 'translate',
316 {ord('a'): None, ord('b'): ord('i')})
317 self.checkequalnofix('iiix', 'abababc', 'translate',
318 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
319 self.checkequalnofix('c', 'abababc', 'translate',
320 {ord('a'): None, ord('b'): ''})
321 self.checkequalnofix('xyyx', 'xzx', 'translate',
322 {ord('z'): 'yy'})
Victor Stinner5a29f252014-04-05 00:17:51 +0200323
Georg Brandlceee0772007-11-27 23:48:05 +0000324 # this needs maketrans()
325 self.checkequalnofix('abababc', 'abababc', 'translate',
326 {'b': '<i>'})
327 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
328 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
329 # test alternative way of calling maketrans()
330 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
331 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
332
Victor Stinner5a29f252014-04-05 00:17:51 +0200333 # various tests switching from ASCII to latin1 or the opposite;
334 # same length, remove a letter, or replace with a longer string.
335 self.assertEqual("[a]".translate(str.maketrans('a', 'X')),
336 "[X]")
337 self.assertEqual("[a]".translate(str.maketrans({'a': 'X'})),
338 "[X]")
339 self.assertEqual("[a]".translate(str.maketrans({'a': None})),
340 "[]")
341 self.assertEqual("[a]".translate(str.maketrans({'a': 'XXX'})),
342 "[XXX]")
343 self.assertEqual("[a]".translate(str.maketrans({'a': '\xe9'})),
344 "[\xe9]")
Victor Stinner33798672016-03-01 21:59:58 +0100345 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '123'})),
346 "x123")
347 self.assertEqual('axb'.translate(str.maketrans({'a': None, 'b': '\xe9'})),
348 "x\xe9")
349
350 # test non-ASCII (don't take the fast-path)
Victor Stinner5a29f252014-04-05 00:17:51 +0200351 self.assertEqual("[a]".translate(str.maketrans({'a': '<\xe9>'})),
352 "[<\xe9>]")
353 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': 'a'})),
354 "[a]")
355 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': None})),
356 "[]")
Victor Stinner33798672016-03-01 21:59:58 +0100357 self.assertEqual("[\xe9]".translate(str.maketrans({'\xe9': '123'})),
358 "[123]")
359 self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})),
360 "[<\u20ac>\xe9]")
Victor Stinner5a29f252014-04-05 00:17:51 +0200361
Victor Stinner4ff33af2014-04-05 11:56:37 +0200362 # invalid Unicode characters
363 invalid_char = 0x10ffff+1
364 for before in "a\xe9\u20ac\U0010ffff":
365 mapping = str.maketrans({before: invalid_char})
366 text = "[%s]" % before
367 self.assertRaises(ValueError, text.translate, mapping)
368
369 # errors
Georg Brandlceee0772007-11-27 23:48:05 +0000370 self.assertRaises(TypeError, self.type2test.maketrans)
371 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
372 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
373 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
374 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
375 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
376 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
Guido van Rossuma831cac2000-03-10 23:23:21 +0000377
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000378 self.assertRaises(TypeError, 'hello'.translate)
Walter Dörwald67e83882007-05-05 12:26:27 +0000379 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000380
Walter Dörwald28256f22003-01-19 16:59:20 +0000381 def test_split(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000382 string_tests.CommonTest.test_split(self)
Andrew M. Kuchlingeddd68d2002-03-29 16:21:44 +0000383
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200384 # test mixed kinds
385 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
386 left *= 9
387 right *= 9
388 for delim in ('c', '\u0102', '\U00010302'):
389 self.checkequal([left + right],
390 left + right, 'split', delim)
391 self.checkequal([left, right],
392 left + delim + right, 'split', delim)
393 self.checkequal([left + right],
394 left + right, 'split', delim * 2)
395 self.checkequal([left, right],
396 left + delim * 2 + right, 'split', delim *2)
397
398 def test_rsplit(self):
399 string_tests.CommonTest.test_rsplit(self)
400 # test mixed kinds
401 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
402 left *= 9
403 right *= 9
404 for delim in ('c', '\u0102', '\U00010302'):
405 self.checkequal([left + right],
406 left + right, 'rsplit', delim)
407 self.checkequal([left, right],
408 left + delim + right, 'rsplit', delim)
409 self.checkequal([left + right],
410 left + right, 'rsplit', delim * 2)
411 self.checkequal([left, right],
412 left + delim * 2 + right, 'rsplit', delim *2)
413
414 def test_partition(self):
415 string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
416 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300417 self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200418 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
419 left *= 9
420 right *= 9
421 for delim in ('c', '\u0102', '\U00010302'):
422 self.checkequal((left + right, '', ''),
423 left + right, 'partition', delim)
424 self.checkequal((left, delim, right),
425 left + delim + right, 'partition', delim)
426 self.checkequal((left + right, '', ''),
427 left + right, 'partition', delim * 2)
428 self.checkequal((left, delim * 2, right),
429 left + delim * 2 + right, 'partition', delim * 2)
430
431 def test_rpartition(self):
432 string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
433 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300434 self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200435 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
436 left *= 9
437 right *= 9
438 for delim in ('c', '\u0102', '\U00010302'):
439 self.checkequal(('', '', left + right),
440 left + right, 'rpartition', delim)
441 self.checkequal((left, delim, right),
442 left + delim + right, 'rpartition', delim)
443 self.checkequal(('', '', left + right),
444 left + right, 'rpartition', delim * 2)
445 self.checkequal((left, delim * 2, right),
446 left + delim * 2 + right, 'rpartition', delim * 2)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000447
Walter Dörwald28256f22003-01-19 16:59:20 +0000448 def test_join(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000449 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +0000450
Guido van Rossumf1044292007-09-27 18:01:22 +0000451 class MyWrapper:
452 def __init__(self, sval): self.sval = sval
453 def __str__(self): return self.sval
454
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000455 # mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000456 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
457 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
458 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
459 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
460 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
461 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
462 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000463 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
464 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
465 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
466 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
Marc-André Lemburge5034372000-08-08 08:04:29 +0000467
Martin Panterb71c0952017-01-12 11:54:59 +0000468 @unittest.skipIf(sys.maxsize > 2**32,
469 'needs too much memory on a 64-bit platform')
470 def test_join_overflow(self):
471 size = int(sys.maxsize**0.5) + 1
472 seq = ('A' * size,) * size
473 self.assertRaises(OverflowError, ''.join, seq)
474
Walter Dörwald28256f22003-01-19 16:59:20 +0000475 def test_replace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000476 string_tests.CommonTest.test_replace(self)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000477
Walter Dörwald28256f22003-01-19 16:59:20 +0000478 # method call forwarded from str implementation because of unicode argument
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000479 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
480 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200481 # test mixed kinds
482 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
483 left *= 9
484 right *= 9
485 for delim in ('c', '\u0102', '\U00010302'):
486 for repl in ('d', '\u0103', '\U00010303'):
487 self.checkequal(left + right,
488 left + right, 'replace', delim, repl)
489 self.checkequal(left + repl + right,
490 left + delim + right,
491 'replace', delim, repl)
492 self.checkequal(left + right,
493 left + right, 'replace', delim * 2, repl)
494 self.checkequal(left + repl + right,
495 left + delim * 2 + right,
496 'replace', delim * 2, repl)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000497
Victor Stinner59de0ee2011-10-07 10:01:28 +0200498 @support.cpython_only
499 def test_replace_id(self):
Victor Stinner1d972ad2011-10-07 13:31:46 +0200500 pattern = 'abc'
501 text = 'abc def'
502 self.assertIs(text.replace(pattern, pattern), text)
Victor Stinner59de0ee2011-10-07 10:01:28 +0200503
Guido van Rossum98297ee2007-11-06 21:34:58 +0000504 def test_bytes_comparison(self):
Brett Cannon226b2302010-03-20 22:22:22 +0000505 with support.check_warnings():
506 warnings.simplefilter('ignore', BytesWarning)
507 self.assertEqual('abc' == b'abc', False)
508 self.assertEqual('abc' != b'abc', True)
509 self.assertEqual('abc' == bytearray(b'abc'), False)
510 self.assertEqual('abc' != bytearray(b'abc'), True)
Brett Cannon40430012007-10-22 20:24:51 +0000511
Walter Dörwald28256f22003-01-19 16:59:20 +0000512 def test_comparison(self):
513 # Comparisons:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000514 self.assertEqual('abc', 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000515 self.assertTrue('abcd' > 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000516 self.assertTrue('abc' < 'abcd')
Walter Dörwald28256f22003-01-19 16:59:20 +0000517
518 if 0:
519 # Move these tests to a Unicode collation module test...
520 # Testing UTF-16 code point order comparisons...
521
522 # No surrogates, no fixup required.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000523 self.assertTrue('\u0061' < '\u20ac')
Walter Dörwald28256f22003-01-19 16:59:20 +0000524 # Non surrogate below surrogate value, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000525 self.assertTrue('\u0061' < '\ud800\udc02')
Walter Dörwald28256f22003-01-19 16:59:20 +0000526
527 # Non surrogate above surrogate value, fixup required
528 def test_lecmp(s, s2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000529 self.assertTrue(s < s2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000530
531 def test_fixup(s):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000532 s2 = '\ud800\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000533 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000534 s2 = '\ud900\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000535 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000536 s2 = '\uda00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000537 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000538 s2 = '\udb00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000539 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000540 s2 = '\ud800\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000541 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000542 s2 = '\ud900\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000543 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000544 s2 = '\uda00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000545 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000546 s2 = '\udb00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000547 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000548 s2 = '\ud800\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000549 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000550 s2 = '\ud900\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000551 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000552 s2 = '\uda00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000553 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000554 s2 = '\udb00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000555 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000556 s2 = '\ud800\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000557 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000558 s2 = '\ud900\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000559 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000560 s2 = '\uda00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000561 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000562 s2 = '\udb00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000563 test_lecmp(s, s2)
564
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000565 test_fixup('\ue000')
566 test_fixup('\uff61')
Walter Dörwald28256f22003-01-19 16:59:20 +0000567
568 # Surrogates on both sides, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000569 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
Walter Dörwald28256f22003-01-19 16:59:20 +0000570
Walter Dörwald28256f22003-01-19 16:59:20 +0000571 def test_islower(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000572 super().test_islower()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000573 self.checkequalnofix(False, '\u1FFc', 'islower')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500574 self.assertFalse('\u2167'.islower())
575 self.assertTrue('\u2177'.islower())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300576 # non-BMP, uppercase
577 self.assertFalse('\U00010401'.islower())
578 self.assertFalse('\U00010427'.islower())
579 # non-BMP, lowercase
580 self.assertTrue('\U00010429'.islower())
581 self.assertTrue('\U0001044E'.islower())
582 # non-BMP, non-cased
583 self.assertFalse('\U0001F40D'.islower())
584 self.assertFalse('\U0001F46F'.islower())
Walter Dörwald28256f22003-01-19 16:59:20 +0000585
586 def test_isupper(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000587 super().test_isupper()
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000588 if not sys.platform.startswith('java'):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000589 self.checkequalnofix(False, '\u1FFc', 'isupper')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500590 self.assertTrue('\u2167'.isupper())
591 self.assertFalse('\u2177'.isupper())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300592 # non-BMP, uppercase
593 self.assertTrue('\U00010401'.isupper())
594 self.assertTrue('\U00010427'.isupper())
595 # non-BMP, lowercase
596 self.assertFalse('\U00010429'.isupper())
597 self.assertFalse('\U0001044E'.isupper())
598 # non-BMP, non-cased
599 self.assertFalse('\U0001F40D'.isupper())
600 self.assertFalse('\U0001F46F'.isupper())
Walter Dörwald28256f22003-01-19 16:59:20 +0000601
602 def test_istitle(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000603 super().test_istitle()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000604 self.checkequalnofix(True, '\u1FFc', 'istitle')
605 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
Walter Dörwald28256f22003-01-19 16:59:20 +0000606
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300607 # non-BMP, uppercase + lowercase
608 self.assertTrue('\U00010401\U00010429'.istitle())
609 self.assertTrue('\U00010427\U0001044E'.istitle())
610 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
611 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
612 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
613
Walter Dörwald28256f22003-01-19 16:59:20 +0000614 def test_isspace(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000615 super().test_isspace()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000616 self.checkequalnofix(True, '\u2000', 'isspace')
617 self.checkequalnofix(True, '\u200a', 'isspace')
618 self.checkequalnofix(False, '\u2014', 'isspace')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300619 # apparently there are no non-BMP spaces chars in Unicode 6
620 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
621 '\U0001F40D', '\U0001F46F']:
622 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
623
624 def test_isalnum(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000625 super().test_isalnum()
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300626 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
627 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
628 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
Walter Dörwald28256f22003-01-19 16:59:20 +0000629
630 def test_isalpha(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000631 super().test_isalpha()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000632 self.checkequalnofix(True, '\u1FFc', 'isalpha')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300633 # non-BMP, cased
634 self.assertTrue('\U00010401'.isalpha())
635 self.assertTrue('\U00010427'.isalpha())
636 self.assertTrue('\U00010429'.isalpha())
637 self.assertTrue('\U0001044E'.isalpha())
638 # non-BMP, non-cased
639 self.assertFalse('\U0001F40D'.isalpha())
640 self.assertFalse('\U0001F46F'.isalpha())
Walter Dörwald28256f22003-01-19 16:59:20 +0000641
642 def test_isdecimal(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000643 self.checkequalnofix(False, '', 'isdecimal')
644 self.checkequalnofix(False, 'a', 'isdecimal')
645 self.checkequalnofix(True, '0', 'isdecimal')
646 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
647 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
648 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
649 self.checkequalnofix(True, '0123456789', 'isdecimal')
650 self.checkequalnofix(False, '0123456789a', 'isdecimal')
Walter Dörwald28256f22003-01-19 16:59:20 +0000651
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000652 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000653
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300654 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
655 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
656 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
657 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
658 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
659
Walter Dörwald28256f22003-01-19 16:59:20 +0000660 def test_isdigit(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000661 super().test_isdigit()
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000662 self.checkequalnofix(True, '\u2460', 'isdigit')
663 self.checkequalnofix(False, '\xbc', 'isdigit')
664 self.checkequalnofix(True, '\u0660', 'isdigit')
Walter Dörwald28256f22003-01-19 16:59:20 +0000665
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300666 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
667 '\U0001F40D', '\U0001F46F', '\U00011065']:
668 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
669 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
670 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
671
Walter Dörwald28256f22003-01-19 16:59:20 +0000672 def test_isnumeric(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000673 self.checkequalnofix(False, '', 'isnumeric')
674 self.checkequalnofix(False, 'a', 'isnumeric')
675 self.checkequalnofix(True, '0', 'isnumeric')
676 self.checkequalnofix(True, '\u2460', 'isnumeric')
677 self.checkequalnofix(True, '\xbc', 'isnumeric')
678 self.checkequalnofix(True, '\u0660', 'isnumeric')
679 self.checkequalnofix(True, '0123456789', 'isnumeric')
680 self.checkequalnofix(False, '0123456789a', 'isnumeric')
Walter Dörwald28256f22003-01-19 16:59:20 +0000681
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000682 self.assertRaises(TypeError, "abc".isnumeric, 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000683
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300684 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
685 '\U0001F40D', '\U0001F46F']:
686 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
687 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
688 '\U000104A0', '\U0001F107']:
689 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
690
Martin v. Löwis47383402007-08-15 07:32:56 +0000691 def test_isidentifier(self):
692 self.assertTrue("a".isidentifier())
693 self.assertTrue("Z".isidentifier())
694 self.assertTrue("_".isidentifier())
695 self.assertTrue("b0".isidentifier())
696 self.assertTrue("bc".isidentifier())
697 self.assertTrue("b_".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000698 self.assertTrue("µ".isidentifier())
Benjamin Petersonf413b802011-08-12 22:17:18 -0500699 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000700
701 self.assertFalse(" ".isidentifier())
702 self.assertFalse("[".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000703 self.assertFalse("©".isidentifier())
Georg Brandld52429f2008-07-04 15:55:02 +0000704 self.assertFalse("0".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000705
Georg Brandl559e5d72008-06-11 18:37:52 +0000706 def test_isprintable(self):
707 self.assertTrue("".isprintable())
Benjamin Peterson09832742009-03-26 17:15:46 +0000708 self.assertTrue(" ".isprintable())
Georg Brandl559e5d72008-06-11 18:37:52 +0000709 self.assertTrue("abcdefg".isprintable())
710 self.assertFalse("abcdefg\n".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000711 # some defined Unicode character
712 self.assertTrue("\u0374".isprintable())
713 # undefined character
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000714 self.assertFalse("\u0378".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000715 # single surrogate character
Georg Brandl559e5d72008-06-11 18:37:52 +0000716 self.assertFalse("\ud800".isprintable())
717
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300718 self.assertTrue('\U0001F46F'.isprintable())
719 self.assertFalse('\U000E0020'.isprintable())
720
721 def test_surrogates(self):
722 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
723 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
724 self.assertTrue(s.islower())
725 self.assertFalse(s.isupper())
726 self.assertFalse(s.istitle())
727 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
728 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
729 self.assertFalse(s.islower())
730 self.assertTrue(s.isupper())
731 self.assertTrue(s.istitle())
732
733 for meth_name in ('islower', 'isupper', 'istitle'):
734 meth = getattr(str, meth_name)
735 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
736 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
737
738 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
739 'isdecimal', 'isnumeric',
740 'isidentifier', 'isprintable'):
741 meth = getattr(str, meth_name)
742 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
743 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
744 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
745 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
746
747
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300748 def test_lower(self):
749 string_tests.CommonTest.test_lower(self)
750 self.assertEqual('\U00010427'.lower(), '\U0001044F')
751 self.assertEqual('\U00010427\U00010427'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300752 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300753 self.assertEqual('\U00010427\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300754 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300755 self.assertEqual('X\U00010427x\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300756 'x\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500757 self.assertEqual('fi'.lower(), 'fi')
758 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
759 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
760 self.assertEqual('\u03a3'.lower(), '\u03c3')
761 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
762 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
763 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
764 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
765 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
766 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
767 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
768 self.assertEqual('\u2177'.lower(), '\u2177')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300769
Benjamin Petersond5890c82012-01-14 13:23:30 -0500770 def test_casefold(self):
771 self.assertEqual('hello'.casefold(), 'hello')
772 self.assertEqual('hELlo'.casefold(), 'hello')
773 self.assertEqual('ß'.casefold(), 'ss')
774 self.assertEqual('fi'.casefold(), 'fi')
775 self.assertEqual('\u03a3'.casefold(), '\u03c3')
776 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
Benjamin Peterson4eda9372012-08-05 15:05:34 -0700777 self.assertEqual('\u00b5'.casefold(), '\u03bc')
Benjamin Petersond5890c82012-01-14 13:23:30 -0500778
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300779 def test_upper(self):
780 string_tests.CommonTest.test_upper(self)
781 self.assertEqual('\U0001044F'.upper(), '\U00010427')
782 self.assertEqual('\U0001044F\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300783 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300784 self.assertEqual('\U00010427\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300785 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300786 self.assertEqual('X\U00010427x\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300787 'X\U00010427X\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500788 self.assertEqual('fi'.upper(), 'FI')
789 self.assertEqual('\u0130'.upper(), '\u0130')
790 self.assertEqual('\u03a3'.upper(), '\u03a3')
791 self.assertEqual('ß'.upper(), 'SS')
792 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
793 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
794 self.assertEqual('\u2177'.upper(), '\u2167')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300795
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300796 def test_capitalize(self):
797 string_tests.CommonTest.test_capitalize(self)
798 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
799 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300800 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300801 self.assertEqual('\U00010427\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300802 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300803 self.assertEqual('\U0001044F\U00010427'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300804 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300805 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300806 'X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500807 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
808 exp = '\u0399\u0308\u0300\u0069\u0307'
809 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
810 self.assertEqual('finnish'.capitalize(), 'FInnish')
811 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300812
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300813 def test_title(self):
Martin Panter152a19c2016-04-06 06:37:17 +0000814 super().test_title()
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300815 self.assertEqual('\U0001044F'.title(), '\U00010427')
816 self.assertEqual('\U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300817 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300818 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300819 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300820 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300821 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300822 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300823 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300824 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300825 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500826 self.assertEqual('fiNNISH'.title(), 'Finnish')
827 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
828 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300829
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300830 def test_swapcase(self):
831 string_tests.CommonTest.test_swapcase(self)
832 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
833 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
834 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300835 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300836 self.assertEqual('\U00010427\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300837 '\U0001044F\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300838 self.assertEqual('\U0001044F\U00010427'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300839 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300840 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300841 'x\U0001044FX\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500842 self.assertEqual('fi'.swapcase(), 'FI')
843 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
844 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
845 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
846 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
847 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
848 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
849 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
850 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
851 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
852 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
853 self.assertEqual('ß'.swapcase(), 'SS')
854 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300855
Ezio Melottif84e01d2013-07-08 17:48:29 +0200856 def test_center(self):
857 string_tests.CommonTest.test_center(self)
858 self.assertEqual('x'.center(2, '\U0010FFFF'),
859 'x\U0010FFFF')
860 self.assertEqual('x'.center(3, '\U0010FFFF'),
861 '\U0010FFFFx\U0010FFFF')
862 self.assertEqual('x'.center(4, '\U0010FFFF'),
863 '\U0010FFFFx\U0010FFFF\U0010FFFF')
864
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400865 @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
Benjamin Peterson4d856892014-10-15 13:39:46 -0400866 @support.cpython_only
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400867 def test_case_operation_overflow(self):
868 # Issue #22643
Serhiy Storchaka411dfd82015-11-07 16:54:48 +0200869 size = 2**32//12 + 1
870 try:
871 s = "ü" * size
872 except MemoryError:
873 self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
874 try:
875 self.assertRaises(OverflowError, s.upper)
876 finally:
877 del s
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400878
Walter Dörwald28256f22003-01-19 16:59:20 +0000879 def test_contains(self):
880 # Testing Unicode contains method
Benjamin Peterson577473f2010-01-19 00:09:57 +0000881 self.assertIn('a', 'abdb')
882 self.assertIn('a', 'bdab')
883 self.assertIn('a', 'bdaba')
884 self.assertIn('a', 'bdba')
885 self.assertNotIn('a', 'bdb')
886 self.assertIn('a', 'bdba')
887 self.assertIn('a', ('a',1,None))
888 self.assertIn('a', (1,None,'a'))
889 self.assertIn('a', ('a',1,None))
890 self.assertIn('a', (1,None,'a'))
891 self.assertNotIn('a', ('x',1,'y'))
892 self.assertNotIn('a', ('x',1,None))
893 self.assertNotIn('abcd', 'abcxxxx')
894 self.assertIn('ab', 'abcd')
895 self.assertIn('ab', 'abc')
896 self.assertIn('ab', (1,None,'ab'))
897 self.assertIn('', 'abc')
898 self.assertIn('', '')
899 self.assertIn('', 'abc')
900 self.assertNotIn('\0', 'abc')
901 self.assertIn('\0', '\0abc')
902 self.assertIn('\0', 'abc\0')
903 self.assertIn('a', '\0abc')
904 self.assertIn('asdf', 'asdf')
905 self.assertNotIn('asdf', 'asd')
906 self.assertNotIn('asdf', '')
Walter Dörwald28256f22003-01-19 16:59:20 +0000907
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000908 self.assertRaises(TypeError, "abc".__contains__)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200909 # test mixed kinds
910 for fill in ('a', '\u0100', '\U00010300'):
911 fill *= 9
912 for delim in ('c', '\u0102', '\U00010302'):
913 self.assertNotIn(delim, fill)
914 self.assertIn(delim, fill + delim)
915 self.assertNotIn(delim * 2, fill)
916 self.assertIn(delim * 2, fill + delim * 2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000917
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +0300918 def test_issue18183(self):
919 '\U00010000\U00100000'.lower()
920 '\U00010000\U00100000'.casefold()
921 '\U00010000\U00100000'.upper()
922 '\U00010000\U00100000'.capitalize()
923 '\U00010000\U00100000'.title()
924 '\U00010000\U00100000'.swapcase()
925 '\U00100000'.center(3, '\U00010000')
926 '\U00100000'.ljust(3, '\U00010000')
927 '\U00100000'.rjust(3, '\U00010000')
928
Eric Smith8c663262007-08-25 02:26:07 +0000929 def test_format(self):
930 self.assertEqual(''.format(), '')
931 self.assertEqual('a'.format(), 'a')
932 self.assertEqual('ab'.format(), 'ab')
933 self.assertEqual('a{{'.format(), 'a{')
934 self.assertEqual('a}}'.format(), 'a}')
935 self.assertEqual('{{b'.format(), '{b')
936 self.assertEqual('}}b'.format(), '}b')
937 self.assertEqual('a{{b'.format(), 'a{b')
938
939 # examples from the PEP:
940 import datetime
941 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
942 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
943 "My name is Fred")
944 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
945 "My name is Fred :-{}")
946
947 d = datetime.date(2007, 8, 18)
948 self.assertEqual("The year is {0.year}".format(d),
949 "The year is 2007")
950
Eric Smith8c663262007-08-25 02:26:07 +0000951 # classes we'll use for testing
952 class C:
953 def __init__(self, x=100):
954 self._x = x
955 def __format__(self, spec):
956 return spec
957
958 class D:
959 def __init__(self, x):
960 self.x = x
961 def __format__(self, spec):
962 return str(self.x)
963
964 # class with __str__, but no __format__
965 class E:
966 def __init__(self, x):
967 self.x = x
968 def __str__(self):
969 return 'E(' + self.x + ')'
970
971 # class with __repr__, but no __format__ or __str__
972 class F:
973 def __init__(self, x):
974 self.x = x
975 def __repr__(self):
976 return 'F(' + self.x + ')'
977
978 # class with __format__ that forwards to string, for some format_spec's
979 class G:
980 def __init__(self, x):
981 self.x = x
982 def __str__(self):
983 return "string is " + self.x
984 def __format__(self, format_spec):
985 if format_spec == 'd':
986 return 'G(' + self.x + ')'
987 return object.__format__(self, format_spec)
988
Eric Smith739e2ad2007-08-27 19:07:22 +0000989 class I(datetime.date):
990 def __format__(self, format_spec):
991 return self.strftime(format_spec)
992
Eric Smith185e30c2007-08-30 22:23:08 +0000993 class J(int):
994 def __format__(self, format_spec):
995 return int.__format__(self * 2, format_spec)
996
Guido van Rossum97c1adf2016-08-18 09:22:23 -0700997 class M:
998 def __init__(self, x):
999 self.x = x
1000 def __repr__(self):
1001 return 'M(' + self.x + ')'
1002 __str__ = None
1003
1004 class N:
1005 def __init__(self, x):
1006 self.x = x
1007 def __repr__(self):
1008 return 'N(' + self.x + ')'
1009 __format__ = None
Eric Smith8c663262007-08-25 02:26:07 +00001010
1011 self.assertEqual(''.format(), '')
1012 self.assertEqual('abc'.format(), 'abc')
1013 self.assertEqual('{0}'.format('abc'), 'abc')
1014 self.assertEqual('{0:}'.format('abc'), 'abc')
1015# self.assertEqual('{ 0 }'.format('abc'), 'abc')
1016 self.assertEqual('X{0}'.format('abc'), 'Xabc')
1017 self.assertEqual('{0}X'.format('abc'), 'abcX')
1018 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
1019 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
1020 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
1021 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
1022 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
1023 self.assertEqual('{0}'.format(-15), '-15')
1024 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
1025 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
1026 self.assertEqual('{{'.format(), '{')
1027 self.assertEqual('}}'.format(), '}')
1028 self.assertEqual('{{}}'.format(), '{}')
1029 self.assertEqual('{{x}}'.format(), '{x}')
1030 self.assertEqual('{{{0}}}'.format(123), '{123}')
1031 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
1032 self.assertEqual('}}{{'.format(), '}{')
1033 self.assertEqual('}}x{{'.format(), '}x{')
1034
Eric Smith7ade6482007-08-26 22:27:13 +00001035 # weird field names
1036 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
1037 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
Eric Smith4cb4e4e2007-09-03 08:40:29 +00001038 self.assertEqual("{0[ ]}".format({' ':3}), '3')
Eric Smith7ade6482007-08-26 22:27:13 +00001039
Eric Smith8c663262007-08-25 02:26:07 +00001040 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
1041 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
1042 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
1043 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
1044 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
1045 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
1046 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
1047
Eric Smith8c663262007-08-25 02:26:07 +00001048 # strings
1049 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
1050 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
1051 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
1052 self.assertEqual('{0:.0s}'.format('abcdef'), '')
1053 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
1054 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
1055 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
1056 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
1057 self.assertEqual('{0:x<0s}'.format('result'), 'result')
1058 self.assertEqual('{0:x<5s}'.format('result'), 'result')
1059 self.assertEqual('{0:x<6s}'.format('result'), 'result')
1060 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
1061 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
1062 self.assertEqual('{0: <7s}'.format('result'), 'result ')
1063 self.assertEqual('{0:<7s}'.format('result'), 'result ')
1064 self.assertEqual('{0:>7s}'.format('result'), ' result')
1065 self.assertEqual('{0:>8s}'.format('result'), ' result')
1066 self.assertEqual('{0:^8s}'.format('result'), ' result ')
1067 self.assertEqual('{0:^9s}'.format('result'), ' result ')
1068 self.assertEqual('{0:^10s}'.format('result'), ' result ')
1069 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
1070 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
1071 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
1072
Eric V. Smith2ea97122014-04-14 11:55:10 -04001073 # issue 12546: use \x00 as a fill character
1074 self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
1075 self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
1076 self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
1077 self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
1078
1079 self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
1080 self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
1081 self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
1082 self.assertEqual('{0:<6}'.format(3), '3 ')
1083
1084 self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
1085 self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
1086 self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
1087 self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
1088
1089 self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
1090 self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
1091 self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
1092 self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
1093
Eric Smith8c663262007-08-25 02:26:07 +00001094 # format specifiers for user defined type
1095 self.assertEqual('{0:abc}'.format(C()), 'abc')
1096
Georg Brandld52429f2008-07-04 15:55:02 +00001097 # !r, !s and !a coercions
Eric Smith8c663262007-08-25 02:26:07 +00001098 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
1099 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
1100 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
1101 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
1102 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
1103 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
1104 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001105 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001106 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
1107 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
Georg Brandl559e5d72008-06-11 18:37:52 +00001108 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001109 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001110 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
Georg Brandl559e5d72008-06-11 18:37:52 +00001111 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
1112 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
Georg Brandld52429f2008-07-04 15:55:02 +00001113 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
Eric Smith8c663262007-08-25 02:26:07 +00001114
Eric Smith8c663262007-08-25 02:26:07 +00001115 # test fallback to object.__format__
1116 self.assertEqual('{0}'.format({}), '{}')
1117 self.assertEqual('{0}'.format([]), '[]')
1118 self.assertEqual('{0}'.format([1]), '[1]')
Eric Smithe4d63172010-09-13 20:48:43 +00001119
Eric Smith8c663262007-08-25 02:26:07 +00001120 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
Eric Smith8c663262007-08-25 02:26:07 +00001121 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
1122
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02001123 self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
1124 self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
1125 self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
Eric Smithe4d63172010-09-13 20:48:43 +00001126
Eric Smith739e2ad2007-08-27 19:07:22 +00001127 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
1128 month=8,
1129 day=27)),
1130 "date: 2007-08-27")
1131
Eric Smith185e30c2007-08-30 22:23:08 +00001132 # test deriving from a builtin type and overriding __format__
1133 self.assertEqual("{0}".format(J(10)), "20")
1134
1135
Eric Smith8c663262007-08-25 02:26:07 +00001136 # string format specifiers
1137 self.assertEqual('{0:}'.format('a'), 'a')
1138
1139 # computed format specifiers
1140 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
1141 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
1142 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
1143 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
1144 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
1145
1146 # test various errors
1147 self.assertRaises(ValueError, '{'.format)
1148 self.assertRaises(ValueError, '}'.format)
1149 self.assertRaises(ValueError, 'a{'.format)
1150 self.assertRaises(ValueError, 'a}'.format)
1151 self.assertRaises(ValueError, '{a'.format)
1152 self.assertRaises(ValueError, '}a'.format)
Eric Smith11529192007-09-04 23:04:22 +00001153 self.assertRaises(IndexError, '{0}'.format)
1154 self.assertRaises(IndexError, '{1}'.format, 'abc')
1155 self.assertRaises(KeyError, '{x}'.format)
Eric Smith8c663262007-08-25 02:26:07 +00001156 self.assertRaises(ValueError, "}{".format)
Eric Smith8c663262007-08-25 02:26:07 +00001157 self.assertRaises(ValueError, "abc{0:{}".format)
1158 self.assertRaises(ValueError, "{0".format)
Eric Smith11529192007-09-04 23:04:22 +00001159 self.assertRaises(IndexError, "{0.}".format)
1160 self.assertRaises(ValueError, "{0.}".format, 0)
Benjamin Peterson4d944742013-05-17 18:22:31 -05001161 self.assertRaises(ValueError, "{0[}".format)
Eric Smith4cb4e4e2007-09-03 08:40:29 +00001162 self.assertRaises(ValueError, "{0[}".format, [])
Eric Smith11529192007-09-04 23:04:22 +00001163 self.assertRaises(KeyError, "{0]}".format)
1164 self.assertRaises(ValueError, "{0.[]}".format, 0)
Eric Smith7ade6482007-08-26 22:27:13 +00001165 self.assertRaises(ValueError, "{0..foo}".format, 0)
Eric Smith11529192007-09-04 23:04:22 +00001166 self.assertRaises(ValueError, "{0[0}".format, 0)
1167 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
1168 self.assertRaises(KeyError, "{c]}".format)
1169 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
1170 self.assertRaises(ValueError, "{0}}".format, 0)
1171 self.assertRaises(KeyError, "{foo}".format, bar=3)
Eric Smith8c663262007-08-25 02:26:07 +00001172 self.assertRaises(ValueError, "{0!x}".format, 3)
Eric Smith11529192007-09-04 23:04:22 +00001173 self.assertRaises(ValueError, "{0!}".format, 0)
1174 self.assertRaises(ValueError, "{0!rs}".format, 0)
Eric Smith8c663262007-08-25 02:26:07 +00001175 self.assertRaises(ValueError, "{!}".format)
Eric Smith8ec90442009-03-14 12:29:34 +00001176 self.assertRaises(IndexError, "{:}".format)
1177 self.assertRaises(IndexError, "{:s}".format)
1178 self.assertRaises(IndexError, "{}".format)
Benjamin Peterson59a1b2f2010-06-07 22:31:26 +00001179 big = "23098475029384702983476098230754973209482573"
1180 self.assertRaises(ValueError, ("{" + big + "}").format)
1181 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
Eric Smith8c663262007-08-25 02:26:07 +00001182
Eric Smith41669ca2009-05-23 14:23:22 +00001183 # issue 6089
1184 self.assertRaises(ValueError, "{0[0]x}".format, [None])
1185 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
1186
Eric Smith8c663262007-08-25 02:26:07 +00001187 # can't have a replacement on the field name portion
1188 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
1189
1190 # exceed maximum recursion depth
1191 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
1192 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
1193 0, 1, 2, 3, 4, 5, 6, 7)
1194
1195 # string format spec errors
1196 self.assertRaises(ValueError, "{0:-s}".format, '')
1197 self.assertRaises(ValueError, format, "", "-")
1198 self.assertRaises(ValueError, "{0:=s}".format, '')
1199
Eric Smithb1ebcc62008-07-15 13:02:41 +00001200 # Alternate formatting is not supported
1201 self.assertRaises(ValueError, format, '', '#')
1202 self.assertRaises(ValueError, format, '', '#20')
1203
Victor Stinnerece58de2012-04-23 23:36:38 +02001204 # Non-ASCII
1205 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
1206 'ABC\u0410\u0411\u0412')
1207 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
1208 'ABC')
1209 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
1210 '')
1211
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001212 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
Benjamin Peterson4d944742013-05-17 18:22:31 -05001213 self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
1214 self.assertEqual("{[{]}".format({"{" : "a"}), "a")
1215 self.assertEqual("{[}]}".format({"}" : "a"}), "a")
1216 self.assertEqual("{[[]}".format({"[" : "a"}), "a")
1217 self.assertEqual("{[!]}".format({"!" : "a"}), "a")
1218 self.assertRaises(ValueError, "{a{}b}".format, 42)
1219 self.assertRaises(ValueError, "{a{b}".format, 42)
1220 self.assertRaises(ValueError, "{[}".format, 42)
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001221
Benjamin Peterson0ee22bf2013-11-26 19:22:36 -06001222 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001223
Guido van Rossum97c1adf2016-08-18 09:22:23 -07001224 # Blocking fallback
1225 m = M('data')
1226 self.assertEqual("{!r}".format(m), 'M(data)')
1227 self.assertRaises(TypeError, "{!s}".format, m)
1228 self.assertRaises(TypeError, "{}".format, m)
1229 n = N('data')
1230 self.assertEqual("{!r}".format(n), 'N(data)')
1231 self.assertEqual("{!s}".format(n), 'N(data)')
1232 self.assertRaises(TypeError, "{}".format, n)
1233
Eric Smith27bbca62010-11-04 17:06:58 +00001234 def test_format_map(self):
1235 self.assertEqual(''.format_map({}), '')
1236 self.assertEqual('a'.format_map({}), 'a')
1237 self.assertEqual('ab'.format_map({}), 'ab')
1238 self.assertEqual('a{{'.format_map({}), 'a{')
1239 self.assertEqual('a}}'.format_map({}), 'a}')
1240 self.assertEqual('{{b'.format_map({}), '{b')
1241 self.assertEqual('}}b'.format_map({}), '}b')
1242 self.assertEqual('a{{b'.format_map({}), 'a{b')
1243
1244 # using mappings
1245 class Mapping(dict):
1246 def __missing__(self, key):
1247 return key
1248 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
1249 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
1250
1251 class InternalMapping:
1252 def __init__(self):
1253 self.mapping = {'a': 'hello'}
1254 def __getitem__(self, key):
1255 return self.mapping[key]
1256 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
1257
1258
Eric Smith27bbca62010-11-04 17:06:58 +00001259 class C:
1260 def __init__(self, x=100):
1261 self._x = x
1262 def __format__(self, spec):
1263 return spec
Eric Smith27bbca62010-11-04 17:06:58 +00001264 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
1265
1266 # test various errors
Eric V. Smithedbb6ca2012-03-12 15:16:22 -07001267 self.assertRaises(TypeError, ''.format_map)
1268 self.assertRaises(TypeError, 'a'.format_map)
1269
1270 self.assertRaises(ValueError, '{'.format_map, {})
1271 self.assertRaises(ValueError, '}'.format_map, {})
1272 self.assertRaises(ValueError, 'a{'.format_map, {})
1273 self.assertRaises(ValueError, 'a}'.format_map, {})
1274 self.assertRaises(ValueError, '{a'.format_map, {})
1275 self.assertRaises(ValueError, '}a'.format_map, {})
Eric Smith27bbca62010-11-04 17:06:58 +00001276
Eric V. Smith12ebefc2011-07-18 14:03:41 -04001277 # issue #12579: can't supply positional params to format_map
1278 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1279 self.assertRaises(ValueError, '{}'.format_map, 'a')
1280 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1281
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001282 def test_format_huge_precision(self):
1283 format_string = ".{}f".format(sys.maxsize + 1)
1284 with self.assertRaises(ValueError):
1285 result = format(2.34, format_string)
1286
1287 def test_format_huge_width(self):
1288 format_string = "{}f".format(sys.maxsize + 1)
1289 with self.assertRaises(ValueError):
1290 result = format(2.34, format_string)
1291
1292 def test_format_huge_item_number(self):
1293 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1294 with self.assertRaises(ValueError):
1295 result = format_string.format(2.34)
1296
Eric Smith8ec90442009-03-14 12:29:34 +00001297 def test_format_auto_numbering(self):
1298 class C:
1299 def __init__(self, x=100):
1300 self._x = x
1301 def __format__(self, spec):
1302 return spec
1303
1304 self.assertEqual('{}'.format(10), '10')
1305 self.assertEqual('{:5}'.format('s'), 's ')
1306 self.assertEqual('{!r}'.format('s'), "'s'")
1307 self.assertEqual('{._x}'.format(C(10)), '10')
1308 self.assertEqual('{[1]}'.format([1, 2]), '2')
1309 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1310 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1311
1312 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1313 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1314
1315 # can't mix and match numbering and auto-numbering
1316 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1317 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1318 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1319 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1320
1321 # can mix and match auto-numbering and named
1322 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1323 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1324 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1325 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1326
Walter Dörwald28256f22003-01-19 16:59:20 +00001327 def test_formatting(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001328 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
Walter Dörwald28256f22003-01-19 16:59:20 +00001329 # Testing Unicode formatting strings...
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001330 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1331 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1332 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1333 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1334 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1335 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 +00001336 if not sys.platform.startswith('java'):
Walter Dörwald67e83882007-05-05 12:26:27 +00001337 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
Georg Brandl559e5d72008-06-11 18:37:52 +00001338 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1339 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001340 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1341 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
Walter Dörwald56fbcb52003-03-31 18:18:41 +00001342
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001343 self.assertEqual('%c' % 0x1234, '\u1234')
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00001344 self.assertEqual('%c' % 0x21483, '\U00021483')
1345 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1346 self.assertEqual('%c' % '\U00021483', '\U00021483')
1347 self.assertRaises(TypeError, "%c".__mod__, "aa")
Stefan Krah99212f62010-07-19 17:58:26 +00001348 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07001349 self.assertRaises(TypeError, "%i".__mod__, "aa")
Walter Dörwald28256f22003-01-19 16:59:20 +00001350
1351 # formatting jobs delegated from the string implementation:
Walter Dörwald28256f22003-01-19 16:59:20 +00001352 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001353 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1354 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1355 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1356 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1357 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1358 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1359 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1360 self.assertEqual('...%s...' % "abc", '...abc...')
1361 self.assertEqual('%*s' % (5,'abc',), ' abc')
1362 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1363 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1364 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1365 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1366 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1367 self.assertEqual('%c' % 'a', 'a')
Neil Schemenauercf52c072005-08-12 17:34:58 +00001368 class Wrapper:
1369 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001370 return '\u1234'
1371 self.assertEqual('%s' % Wrapper(), '\u1234')
Walter Dörwald28256f22003-01-19 16:59:20 +00001372
Eric Smith741191f2009-05-06 13:08:15 +00001373 # issue 3382
1374 NAN = float('nan')
1375 INF = float('inf')
1376 self.assertEqual('%f' % NAN, 'nan')
1377 self.assertEqual('%F' % NAN, 'NAN')
1378 self.assertEqual('%f' % INF, 'inf')
1379 self.assertEqual('%F' % INF, 'INF')
1380
Victor Stinnerf59c28c2012-05-09 03:24:14 +02001381 # PEP 393
1382 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1383 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1384
Ethan Furmandf3ed242014-01-05 06:50:30 -08001385 #issue 19995
Ethan Furman9ab74802014-03-21 06:38:46 -07001386 class PseudoInt:
Ethan Furmandf3ed242014-01-05 06:50:30 -08001387 def __init__(self, value):
1388 self.value = int(value)
1389 def __int__(self):
1390 return self.value
1391 def __index__(self):
1392 return self.value
Ethan Furman9ab74802014-03-21 06:38:46 -07001393 class PseudoFloat:
Ethan Furmandf3ed242014-01-05 06:50:30 -08001394 def __init__(self, value):
1395 self.value = float(value)
1396 def __int__(self):
1397 return int(self.value)
Ethan Furman9ab74802014-03-21 06:38:46 -07001398 pi = PseudoFloat(3.1415)
1399 letter_m = PseudoInt(109)
Antoine Pitroueb168042014-01-10 00:02:38 +01001400 self.assertEqual('%x' % 42, '2a')
1401 self.assertEqual('%X' % 15, 'F')
1402 self.assertEqual('%o' % 9, '11')
1403 self.assertEqual('%c' % 109, 'm')
1404 self.assertEqual('%x' % letter_m, '6d')
1405 self.assertEqual('%X' % letter_m, '6D')
1406 self.assertEqual('%o' % letter_m, '155')
1407 self.assertEqual('%c' % letter_m, 'm')
Ethan Furman9ab74802014-03-21 06:38:46 -07001408 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14),
1409 self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11),
1410 self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79),
1411 self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi),
1412 self.assertRaises(TypeError, operator.mod, '%c', pi),
Ethan Furmandf3ed242014-01-05 06:50:30 -08001413
Ethan Furmanfb137212013-08-31 10:18:55 -07001414 def test_formatting_with_enum(self):
1415 # issue18780
1416 import enum
1417 class Float(float, enum.Enum):
1418 PI = 3.1415926
1419 class Int(enum.IntEnum):
1420 IDES = 15
1421 class Str(str, enum.Enum):
1422 ABC = 'abc'
1423 # Testing Unicode formatting strings...
Ethan Furman13bdfa72013-08-31 12:48:51 -07001424 self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
1425 'Str.ABC, Str.ABC')
1426 self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
1427 (Str.ABC, Str.ABC,
1428 Int.IDES, Int.IDES, Int.IDES,
1429 Float.PI, Float.PI),
1430 'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14')
Ethan Furmanfb137212013-08-31 10:18:55 -07001431
1432 # formatting jobs delegated from the string implementation:
Ethan Furman13bdfa72013-08-31 12:48:51 -07001433 self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
1434 '...Str.ABC...')
1435 self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
1436 '...Int.IDES...')
1437 self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
1438 '...15...')
1439 self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
1440 '...15...')
1441 self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
1442 '...15...')
1443 self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
1444 '...3.141593...')
Ethan Furmanfb137212013-08-31 10:18:55 -07001445
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001446 def test_formatting_huge_precision(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001447 format_string = "%.{}f".format(sys.maxsize + 1)
1448 with self.assertRaises(ValueError):
1449 result = format_string % 2.34
1450
1451 @support.cpython_only
1452 def test_formatting_huge_precision_c_limits(self):
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001453 from _testcapi import INT_MAX
1454 format_string = "%.{}f".format(INT_MAX + 1)
1455 with self.assertRaises(ValueError):
1456 result = format_string % 2.34
1457
1458 def test_formatting_huge_width(self):
1459 format_string = "%{}f".format(sys.maxsize + 1)
1460 with self.assertRaises(ValueError):
1461 result = format_string % 2.34
1462
Ezio Melottiba42fd52011-04-26 06:09:45 +03001463 def test_startswith_endswith_errors(self):
1464 for meth in ('foo'.startswith, 'foo'.endswith):
Ezio Melottif2b3f782011-04-26 06:40:59 +03001465 with self.assertRaises(TypeError) as cm:
Ezio Melottiba42fd52011-04-26 06:09:45 +03001466 meth(['f'])
Ezio Melottif2b3f782011-04-26 06:40:59 +03001467 exc = str(cm.exception)
Ezio Melottiba42fd52011-04-26 06:09:45 +03001468 self.assertIn('str', exc)
1469 self.assertIn('tuple', exc)
1470
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001471 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
Georg Brandlda6b1072006-01-20 17:48:54 +00001472 def test_format_float(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001473 # should not format with a comma, but always with C locale
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001474 self.assertEqual('1.0', '%.1f' % 1.0)
Georg Brandlda6b1072006-01-20 17:48:54 +00001475
Walter Dörwald28256f22003-01-19 16:59:20 +00001476 def test_constructor(self):
1477 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1478
1479 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001480 str('unicode remains unicode'),
1481 'unicode remains unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001482 )
1483
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001484 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
Serhiy Storchaka15095802015-11-25 15:47:01 +02001485 subclass = StrSubclass(text)
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001486 self.assertEqual(str(subclass), text)
1487 self.assertEqual(len(subclass), len(text))
1488 if text == 'ascii':
1489 self.assertEqual(subclass.encode('ascii'), b'ascii')
1490 self.assertEqual(subclass.encode('utf-8'), b'ascii')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001491
Walter Dörwald28256f22003-01-19 16:59:20 +00001492 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001493 str('strings are converted to unicode'),
1494 'strings are converted to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001495 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001496
Walter Dörwald28256f22003-01-19 16:59:20 +00001497 class StringCompat:
1498 def __init__(self, x):
1499 self.x = x
1500 def __str__(self):
1501 return self.x
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001502
Walter Dörwald28256f22003-01-19 16:59:20 +00001503 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001504 str(StringCompat('__str__ compatible objects are recognized')),
1505 '__str__ compatible objects are recognized'
Walter Dörwald28256f22003-01-19 16:59:20 +00001506 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001507
Walter Dörwald28256f22003-01-19 16:59:20 +00001508 # unicode(obj) is compatible to str():
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001509
Walter Dörwald28256f22003-01-19 16:59:20 +00001510 o = StringCompat('unicode(obj) is compatible to str()')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001511 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Walter Dörwald28256f22003-01-19 16:59:20 +00001512 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001513
Guido van Rossume2a383d2007-01-15 16:59:06 +00001514 for obj in (123, 123.45, 123):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001515 self.assertEqual(str(obj), str(str(obj)))
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001516
Walter Dörwald28256f22003-01-19 16:59:20 +00001517 # unicode(obj, encoding, error) tests (this maps to
1518 # PyUnicode_FromEncodedObject() at C level)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001519
Walter Dörwald28256f22003-01-19 16:59:20 +00001520 if not sys.platform.startswith('java'):
1521 self.assertRaises(
1522 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001523 str,
1524 'decoding unicode is not supported',
Walter Dörwald28256f22003-01-19 16:59:20 +00001525 'utf-8',
1526 'strict'
1527 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001528
Walter Dörwald28256f22003-01-19 16:59:20 +00001529 self.assertEqual(
Walter Dörwald67e83882007-05-05 12:26:27 +00001530 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001531 'strings are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001532 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001533
Walter Dörwald28256f22003-01-19 16:59:20 +00001534 if not sys.platform.startswith('java'):
1535 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001536 str(
Guido van Rossumbae07c92007-10-08 02:46:15 +00001537 memoryview(b'character buffers are decoded to unicode'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001538 'utf-8',
1539 'strict'
1540 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001541 'character buffers are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001542 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001543
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001544 self.assertRaises(TypeError, str, 42, 42, 42)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001545
Chris Jerdonek5fae0e52012-11-20 17:45:51 -08001546 def test_constructor_keyword_args(self):
1547 """Pass various keyword argument combinations to the constructor."""
1548 # The object argument can be passed as a keyword.
1549 self.assertEqual(str(object='foo'), 'foo')
1550 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1551 # The errors argument without encoding triggers "decode" mode.
1552 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1553 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1554
1555 def test_constructor_defaults(self):
1556 """Check the constructor argument defaults."""
1557 # The object argument defaults to '' or b''.
1558 self.assertEqual(str(), '')
1559 self.assertEqual(str(errors='strict'), '')
1560 utf8_cent = '¢'.encode('utf-8')
1561 # The encoding argument defaults to utf-8.
1562 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1563 # The errors argument defaults to strict.
1564 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1565
Walter Dörwald28256f22003-01-19 16:59:20 +00001566 def test_codecs_utf7(self):
1567 utfTests = [
Walter Dörwald67e83882007-05-05 12:26:27 +00001568 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1569 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1570 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1571 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1572 ('+', b'+-'),
1573 ('+-', b'+--'),
1574 ('+?', b'+-?'),
R David Murray44b548d2016-09-08 13:59:53 -04001575 (r'\?', b'+AFw?'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001576 ('+?', b'+-?'),
1577 (r'\\?', b'+AFwAXA?'),
1578 (r'\\\?', b'+AFwAXABc?'),
Antoine Pitrou244651a2009-05-04 18:56:13 +00001579 (r'++--', b'+-+---'),
1580 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1581 ('/', b'/'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001582 ]
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001583
Walter Dörwald28256f22003-01-19 16:59:20 +00001584 for (x, y) in utfTests:
1585 self.assertEqual(x.encode('utf-7'), y)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001586
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001587 # Unpaired surrogates are passed through
1588 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1589 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1590 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1591 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1592 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1593 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1594 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1595 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001596
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001597 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1598 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001599
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001600 # Issue #2242: crash on some Windows/MSVC versions
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03001601 self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
Antoine Pitrou244651a2009-05-04 18:56:13 +00001602
1603 # Direct encoded characters
1604 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1605 # Optional direct characters
1606 set_o = '!"#$%&*;<=>@[]^_`{|}'
1607 for c in set_d:
1608 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1609 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1610 for c in set_o:
1611 self.assertEqual(c.encode('ascii').decode('utf7'), c)
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001612
Walter Dörwald28256f22003-01-19 16:59:20 +00001613 def test_codecs_utf8(self):
Walter Dörwald67e83882007-05-05 12:26:27 +00001614 self.assertEqual(''.encode('utf-8'), b'')
1615 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001616 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1617 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001618 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1619 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001620 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1621 b'\xf0\x90\x80\x82'*10)
Walter Dörwald28256f22003-01-19 16:59:20 +00001622 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001623 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1624 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1625 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1626 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1627 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1628 ' Nunstuck git und'.encode('utf-8'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001629 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1630 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1631 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1632 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1633 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1634 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1635 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1636 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1637 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1638 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
Walter Dörwald28256f22003-01-19 16:59:20 +00001639 )
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001640
Walter Dörwald28256f22003-01-19 16:59:20 +00001641 # UTF-8 specific decoding tests
Walter Dörwald67e83882007-05-05 12:26:27 +00001642 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1643 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1644 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001645
Walter Dörwald28256f22003-01-19 16:59:20 +00001646 # Other possible utf-8 test cases:
1647 # * strict decoding testing for all of the
1648 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001649
Ezio Melotti57221d02010-07-01 07:32:02 +00001650 def test_utf8_decode_valid_sequences(self):
1651 sequences = [
1652 # single byte
1653 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1654 # 2 bytes
1655 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1656 # 3 bytes
1657 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1658 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1659 # 4 bytes
1660 (b'\xF0\x90\x80\x80', '\U00010000'),
1661 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1662 ]
1663 for seq, res in sequences:
1664 self.assertEqual(seq.decode('utf-8'), res)
1665
1666
1667 def test_utf8_decode_invalid_sequences(self):
1668 # continuation bytes in a sequence of 2, 3, or 4 bytes
1669 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001670 # start bytes of a 2-byte sequence equivalent to code points < 0x7F
Ezio Melotti57221d02010-07-01 07:32:02 +00001671 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001672 # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
Ezio Melotti57221d02010-07-01 07:32:02 +00001673 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1674 invalid_start_bytes = (
1675 continuation_bytes + invalid_2B_seq_start_bytes +
1676 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1677 )
1678
1679 for byte in invalid_start_bytes:
1680 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1681
1682 for sb in invalid_2B_seq_start_bytes:
1683 for cb in continuation_bytes:
1684 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1685
1686 for sb in invalid_4B_seq_start_bytes:
1687 for cb1 in continuation_bytes[:3]:
1688 for cb3 in continuation_bytes[:3]:
1689 self.assertRaises(UnicodeDecodeError,
1690 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1691
1692 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1693 self.assertRaises(UnicodeDecodeError,
1694 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1695 self.assertRaises(UnicodeDecodeError,
1696 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1697 # surrogates
1698 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1699 self.assertRaises(UnicodeDecodeError,
1700 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1701 self.assertRaises(UnicodeDecodeError,
1702 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1703 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1704 self.assertRaises(UnicodeDecodeError,
1705 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1706 self.assertRaises(UnicodeDecodeError,
1707 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1708 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1709 self.assertRaises(UnicodeDecodeError,
1710 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1711 self.assertRaises(UnicodeDecodeError,
1712 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1713
1714 def test_issue8271(self):
1715 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1716 # only the start byte and the continuation byte(s) are now considered
1717 # invalid, instead of the number of bytes specified by the start byte.
1718 # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
1719 # table 3-8, Row 2) for more information about the algorithm used.
1720 FFFD = '\ufffd'
1721 sequences = [
1722 # invalid start bytes
1723 (b'\x80', FFFD), # continuation byte
1724 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1725 (b'\xc0', FFFD),
1726 (b'\xc0\xc0', FFFD*2),
1727 (b'\xc1', FFFD),
1728 (b'\xc1\xc0', FFFD*2),
1729 (b'\xc0\xc1', FFFD*2),
1730 # with start byte of a 2-byte sequence
1731 (b'\xc2', FFFD), # only the start byte
1732 (b'\xc2\xc2', FFFD*2), # 2 start bytes
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001733 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
Ezio Melotti57221d02010-07-01 07:32:02 +00001734 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1735 # with start byte of a 3-byte sequence
1736 (b'\xe1', FFFD), # only the start byte
1737 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1738 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1739 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1740 (b'\xe1\x80', FFFD), # only 1 continuation byte
1741 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1742 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1743 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1744 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1745 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1746 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1747 # with start byte of a 4-byte sequence
1748 (b'\xf1', FFFD), # only the start byte
1749 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1750 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1751 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1752 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1753 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1754 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1755 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1756 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1757 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1758 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1759 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1760 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1761 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1762 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1763 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1764 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1765 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1766 # with invalid start byte of a 4-byte sequence (rfc2279)
1767 (b'\xf5', FFFD), # only the start byte
1768 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1769 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1770 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1771 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1772 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1773 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1774 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1775 # with invalid start byte of a 5-byte sequence (rfc2279)
1776 (b'\xf8', FFFD), # only the start byte
1777 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1778 (b'\xf8\x80', FFFD*2), # only one continuation byte
1779 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1780 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1781 # with invalid start byte of a 6-byte sequence (rfc2279)
1782 (b'\xfc', FFFD), # only the start byte
1783 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1784 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1785 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
1786 # invalid start byte
1787 (b'\xfe', FFFD),
1788 (b'\xfe\x80\x80', FFFD*3),
1789 # other sequences
1790 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
1791 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
1792 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
1793 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
1794 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
1795 ]
1796 for n, (seq, res) in enumerate(sequences):
1797 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
1798 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1799 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
1800 self.assertEqual(seq.decode('utf-8', 'ignore'),
1801 res.replace('\uFFFD', ''))
1802
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001803 def to_bytestring(self, seq):
1804 return bytes(int(c, 16) for c in seq.split())
1805
1806 def assertCorrectUTF8Decoding(self, seq, res, err):
1807 """
Martin Panter6245cb32016-04-15 02:14:19 +00001808 Check that an invalid UTF-8 sequence raises a UnicodeDecodeError when
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001809 'strict' is used, returns res when 'replace' is used, and that doesn't
1810 return anything when 'ignore' is used.
1811 """
1812 with self.assertRaises(UnicodeDecodeError) as cm:
1813 seq.decode('utf-8')
1814 exc = cm.exception
1815
1816 self.assertIn(err, str(exc))
1817 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1818 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
1819 'aaaa' + res + 'bbbb')
1820 res = res.replace('\ufffd', '')
1821 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
1822 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
1823 'aaaa' + res + 'bbbb')
1824
1825 def test_invalid_start_byte(self):
1826 """
1827 Test that an 'invalid start byte' error is raised when the first byte
1828 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
1829 4-bytes sequence. The invalid start byte is replaced with a single
1830 U+FFFD when errors='replace'.
1831 E.g. <80> is a continuation byte and can appear only after a start byte.
1832 """
1833 FFFD = '\ufffd'
1834 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
1835 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
1836 'invalid start byte')
1837
1838 def test_unexpected_end_of_data(self):
1839 """
1840 Test that an 'unexpected end of data' error is raised when the string
1841 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
1842 enough continuation bytes. The incomplete sequence is replaced with a
1843 single U+FFFD when errors='replace'.
1844 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
1845 sequence, but it's followed by only 2 valid continuation bytes and the
1846 last continuation bytes is missing.
1847 Note: the continuation bytes must be all valid, if one of them is
1848 invalid another error will be raised.
1849 """
1850 sequences = [
1851 'C2', 'DF',
1852 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
1853 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
1854 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
1855 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
1856 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
1857 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
1858 ]
1859 FFFD = '\ufffd'
1860 for seq in sequences:
1861 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), '\ufffd',
1862 'unexpected end of data')
1863
1864 def test_invalid_cb_for_2bytes_seq(self):
1865 """
1866 Test that an 'invalid continuation byte' error is raised when the
1867 continuation byte of a 2-bytes sequence is invalid. The start byte
1868 is replaced by a single U+FFFD and the second byte is handled
1869 separately when errors='replace'.
1870 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
1871 sequence, but 41 is not a valid continuation byte because it's the
1872 ASCII letter 'A'.
1873 """
1874 FFFD = '\ufffd'
1875 FFFDx2 = FFFD * 2
1876 sequences = [
1877 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
1878 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
1879 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
1880 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
1881 ]
1882 for seq, res in sequences:
1883 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1884 'invalid continuation byte')
1885
1886 def test_invalid_cb_for_3bytes_seq(self):
1887 """
1888 Test that an 'invalid continuation byte' error is raised when the
1889 continuation byte(s) of a 3-bytes sequence are invalid. When
1890 errors='replace', if the first continuation byte is valid, the first
1891 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
1892 third byte is handled separately, otherwise only the start byte is
1893 replaced with a U+FFFD and the other continuation bytes are handled
1894 separately.
1895 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1896 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1897 because it's the ASCII letter 'A'.
1898 Note: when the start byte is E0 or ED, the valid ranges for the first
1899 continuation byte are limited to A0..BF and 80..9F respectively.
1900 Python 2 used to consider all the bytes in range 80..BF valid when the
1901 start byte was ED. This is fixed in Python 3.
1902 """
1903 FFFD = '\ufffd'
1904 FFFDx2 = FFFD * 2
1905 sequences = [
1906 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
1907 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
1908 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
1909 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
1910 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
1911 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
1912 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
1913 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
1914 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
1915 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
1916 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
1917 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
1918 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
1919 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
1920 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
1921 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
1922 ('ED 7F', FFFD+'\x7f'),
1923 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
1924 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
1925 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
1926 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
1927 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
1928 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
1929 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
1930 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
1931 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
1932 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
1933 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
1934 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
1935 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
1936 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
1937 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
1938 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
1939 ]
1940 for seq, res in sequences:
1941 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1942 'invalid continuation byte')
1943
1944 def test_invalid_cb_for_4bytes_seq(self):
1945 """
1946 Test that an 'invalid continuation byte' error is raised when the
1947 continuation byte(s) of a 4-bytes sequence are invalid. When
1948 errors='replace',the start byte and all the following valid
1949 continuation bytes are replaced with a single U+FFFD, and all the bytes
1950 starting from the first invalid continuation bytes (included) are
1951 handled separately.
1952 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1953 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1954 because it's the ASCII letter 'A'.
1955 Note: when the start byte is E0 or ED, the valid ranges for the first
1956 continuation byte are limited to A0..BF and 80..9F respectively.
1957 However, when the start byte is ED, Python 2 considers all the bytes
1958 in range 80..BF valid. This is fixed in Python 3.
1959 """
1960 FFFD = '\ufffd'
1961 FFFDx2 = FFFD * 2
1962 sequences = [
1963 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
1964 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
1965 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
1966 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
1967 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
1968 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
1969 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
1970 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
1971 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
1972 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
1973 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
1974 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
1975 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
1976 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
1977 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
1978 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
1979 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
1980 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
1981 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
1982 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
1983 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
1984 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
1985 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
1986 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
1987 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
1988 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
1989 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
1990 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
1991 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
1992 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
1993 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
1994 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
1995 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
1996 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
1997 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
1998 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
1999 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
2000 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
2001 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
2002 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
2003 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
2004 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
2005 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
2006 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
2007 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
2008 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
2009 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
2010 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
2011 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
2012 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
2013 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
2014 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
2015 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
2016 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
2017 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
2018 ]
2019 for seq, res in sequences:
2020 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
2021 'invalid continuation byte')
2022
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00002023 def test_codecs_idna(self):
2024 # Test whether trailing dot is preserved
Walter Dörwald1324c6f2007-05-11 19:57:05 +00002025 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00002026
Walter Dörwald28256f22003-01-19 16:59:20 +00002027 def test_codecs_errors(self):
2028 # Error handling (encoding)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002029 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
2030 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
Walter Dörwald67e83882007-05-05 12:26:27 +00002031 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
2032 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
Benjamin Peterson308d6372009-09-18 21:42:35 +00002033 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
2034 'Andr\202 x'.encode('ascii', errors='replace'))
2035 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
2036 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002037
Walter Dörwald28256f22003-01-19 16:59:20 +00002038 # Error handling (decoding)
Walter Dörwald67e83882007-05-05 12:26:27 +00002039 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
2040 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
2041 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
2042 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03002043 self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00002044
Walter Dörwald28256f22003-01-19 16:59:20 +00002045 # Error handling (unknown character names)
Guido van Rossum39478e82007-08-27 17:23:59 +00002046 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
Marc-André Lemburg3688a882002-02-06 18:09:02 +00002047
Walter Dörwald28256f22003-01-19 16:59:20 +00002048 # Error handling (truncated escape sequence)
Guido van Rossum9c627722007-08-27 18:31:48 +00002049 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00002050
Guido van Rossum9c627722007-08-27 18:31:48 +00002051 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
2052 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002053 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
2054 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00002055
Walter Dörwald28256f22003-01-19 16:59:20 +00002056 # Error handling (wrong arguments)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002057 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002058
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002059 # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00002060 self.assertRaises(UnicodeError, float, "\ud800")
2061 self.assertRaises(UnicodeError, float, "\udf00")
2062 self.assertRaises(UnicodeError, complex, "\ud800")
2063 self.assertRaises(UnicodeError, complex, "\udf00")
Guido van Rossum97064862000-04-10 13:52:48 +00002064
Walter Dörwald28256f22003-01-19 16:59:20 +00002065 def test_codecs(self):
2066 # Encoding
Walter Dörwald67e83882007-05-05 12:26:27 +00002067 self.assertEqual('hello'.encode('ascii'), b'hello')
2068 self.assertEqual('hello'.encode('utf-7'), b'hello')
2069 self.assertEqual('hello'.encode('utf-8'), b'hello')
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002070 self.assertEqual('hello'.encode('utf-8'), b'hello')
Walter Dörwald67e83882007-05-05 12:26:27 +00002071 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
2072 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
2073 self.assertEqual('hello'.encode('latin-1'), b'hello')
Guido van Rossum97064862000-04-10 13:52:48 +00002074
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002075 # Default encoding is utf-8
2076 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
2077
Walter Dörwald28256f22003-01-19 16:59:20 +00002078 # Roundtrip safety for BMP (just the first 1024 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002079 for c in range(1024):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002080 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002081 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
2082 'utf-16-be', 'raw_unicode_escape',
2083 'unicode_escape', 'unicode_internal'):
Victor Stinner040e16e2011-11-15 22:44:05 +01002084 with warnings.catch_warnings():
2085 # unicode-internal has been deprecated
2086 warnings.simplefilter("ignore", DeprecationWarning)
2087
2088 self.assertEqual(str(u.encode(encoding),encoding), u)
Martin v. Löwis047c05e2002-03-21 08:55:28 +00002089
Walter Dörwald28256f22003-01-19 16:59:20 +00002090 # Roundtrip safety for BMP (just the first 256 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002091 for c in range(256):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002092 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002093 for encoding in ('latin-1',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002094 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002095
Walter Dörwald28256f22003-01-19 16:59:20 +00002096 # Roundtrip safety for BMP (just the first 128 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002097 for c in range(128):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002098 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002099 for encoding in ('ascii',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002100 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002101
Walter Dörwald28256f22003-01-19 16:59:20 +00002102 # Roundtrip safety for non-BMP (just a few chars)
Victor Stinner040e16e2011-11-15 22:44:05 +01002103 with warnings.catch_warnings():
2104 # unicode-internal has been deprecated
2105 warnings.simplefilter("ignore", DeprecationWarning)
2106
2107 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
2108 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
2109 'raw_unicode_escape',
2110 'unicode_escape', 'unicode_internal'):
2111 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002112
Antoine Pitrou51f66482011-11-11 13:35:44 +01002113 # UTF-8 must be roundtrip safe for all code points
2114 # (except surrogates, which are forbidden).
2115 u = ''.join(map(chr, list(range(0, 0xd800)) +
Ezio Melotti40dc9192011-11-11 17:00:46 +02002116 list(range(0xe000, 0x110000))))
Walter Dörwald28256f22003-01-19 16:59:20 +00002117 for encoding in ('utf-8',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002118 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002119
Walter Dörwald28256f22003-01-19 16:59:20 +00002120 def test_codecs_charmap(self):
2121 # 0-127
Guido van Rossum805365e2007-05-07 22:24:25 +00002122 s = bytes(range(128))
Walter Dörwald28256f22003-01-19 16:59:20 +00002123 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002124 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002125 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2126 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002127 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002128 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2129 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002130 'iso8859_7', 'iso8859_9',
2131 'koi8_r', 'koi8_t', 'koi8_u', 'kz1048', 'latin_1',
Walter Dörwald28256f22003-01-19 16:59:20 +00002132 'mac_cyrillic', 'mac_latin2',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002133
Walter Dörwald28256f22003-01-19 16:59:20 +00002134 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2135 'cp1256', 'cp1257', 'cp1258',
2136 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002137
Walter Dörwald28256f22003-01-19 16:59:20 +00002138 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
2139 'cp1006', 'iso8859_8',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002140
Walter Dörwald28256f22003-01-19 16:59:20 +00002141 ### These have undefined mappings:
2142 #'cp424',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002143
Walter Dörwald28256f22003-01-19 16:59:20 +00002144 ### These fail the round-trip:
2145 #'cp875'
Guido van Rossum9e896b32000-04-05 20:11:21 +00002146
Walter Dörwald28256f22003-01-19 16:59:20 +00002147 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002148 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002149
Walter Dörwald28256f22003-01-19 16:59:20 +00002150 # 128-255
Guido van Rossum805365e2007-05-07 22:24:25 +00002151 s = bytes(range(128, 256))
Walter Dörwald28256f22003-01-19 16:59:20 +00002152 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002153 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002154 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2155 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002156 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002157 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2158 'iso8859_2', 'iso8859_4', 'iso8859_5',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002159 'iso8859_9', 'koi8_r', 'koi8_u', 'latin_1',
Walter Dörwald28256f22003-01-19 16:59:20 +00002160 'mac_cyrillic', 'mac_latin2',
Fred Drake004d5e62000-10-23 17:22:08 +00002161
Walter Dörwald28256f22003-01-19 16:59:20 +00002162 ### These have undefined mappings:
2163 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2164 #'cp1256', 'cp1257', 'cp1258',
2165 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Serhiy Storchakaf0eeedf2015-05-12 23:24:19 +03002166 #'iso8859_3', 'iso8859_6', 'iso8859_7', 'koi8_t', 'kz1048',
Walter Dörwald28256f22003-01-19 16:59:20 +00002167 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
Fred Drake004d5e62000-10-23 17:22:08 +00002168
Walter Dörwald28256f22003-01-19 16:59:20 +00002169 ### These fail the round-trip:
2170 #'cp1006', 'cp875', 'iso8859_8',
Tim Peters2f228e72001-05-13 00:19:31 +00002171
Walter Dörwald28256f22003-01-19 16:59:20 +00002172 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002173 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002174
Walter Dörwald28256f22003-01-19 16:59:20 +00002175 def test_concatenation(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002176 self.assertEqual(("abc" "def"), "abcdef")
2177 self.assertEqual(("abc" "def"), "abcdef")
2178 self.assertEqual(("abc" "def"), "abcdef")
2179 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
2180 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
Fred Drake004d5e62000-10-23 17:22:08 +00002181
Walter Dörwald28256f22003-01-19 16:59:20 +00002182 def test_printing(self):
2183 class BitBucket:
2184 def write(self, text):
2185 pass
Fred Drake004d5e62000-10-23 17:22:08 +00002186
Walter Dörwald28256f22003-01-19 16:59:20 +00002187 out = BitBucket()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002188 print('abc', file=out)
2189 print('abc', 'def', file=out)
2190 print('abc', 'def', file=out)
2191 print('abc', 'def', file=out)
2192 print('abc\n', file=out)
2193 print('abc\n', end=' ', file=out)
2194 print('abc\n', end=' ', file=out)
2195 print('def\n', file=out)
2196 print('def\n', file=out)
Fred Drake004d5e62000-10-23 17:22:08 +00002197
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002198 def test_ucs4(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002199 x = '\U00100000'
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002200 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
2201 self.assertEqual(x, y)
2202
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002203 y = br'\U00100000'
2204 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2205 self.assertEqual(x, y)
2206 y = br'\U00010000'
2207 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2208 self.assertEqual(x, y)
Christian Heimesfe337bf2008-03-23 21:54:12 +00002209
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002210 try:
2211 br'\U11111111'.decode("raw-unicode-escape")
2212 except UnicodeDecodeError as e:
2213 self.assertEqual(e.start, 0)
2214 self.assertEqual(e.end, 10)
2215 else:
2216 self.fail("Should have raised UnicodeDecodeError")
Christian Heimesfe337bf2008-03-23 21:54:12 +00002217
Brett Cannonc3647ac2005-04-26 03:45:26 +00002218 def test_conversion(self):
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002219 # Make sure __str__() works properly
2220 class ObjectToStr:
Brett Cannonc3647ac2005-04-26 03:45:26 +00002221 def __str__(self):
2222 return "foo"
2223
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002224 class StrSubclassToStr(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00002225 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002226 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00002227
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002228 class StrSubclassToStrSubclass(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002229 def __new__(cls, content=""):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002230 return str.__new__(cls, 2*content)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002231 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002232 return self
2233
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002234 self.assertEqual(str(ObjectToStr()), "foo")
2235 self.assertEqual(str(StrSubclassToStr("bar")), "foo")
2236 s = str(StrSubclassToStrSubclass("foo"))
2237 self.assertEqual(s, "foofoo")
2238 self.assertIs(type(s), StrSubclassToStrSubclass)
Serhiy Storchaka15095802015-11-25 15:47:01 +02002239 s = StrSubclass(StrSubclassToStrSubclass("foo"))
2240 self.assertEqual(s, "foofoo")
2241 self.assertIs(type(s), StrSubclass)
Brett Cannonc3647ac2005-04-26 03:45:26 +00002242
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002243 def test_unicode_repr(self):
2244 class s1:
2245 def __repr__(self):
2246 return '\\n'
2247
2248 class s2:
2249 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002250 return '\\n'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002251
2252 self.assertEqual(repr(s1()), '\\n')
2253 self.assertEqual(repr(s2()), '\\n')
2254
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002255 def test_printable_repr(self):
2256 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
Martin v. Löwisbaecd722010-10-11 22:42:28 +00002257 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002258
Zachary Ware9fe6d862013-12-08 00:20:35 -06002259 # This test only affects 32-bit platforms because expandtabs can only take
2260 # an int as the max value, not a 64-bit C long. If expandtabs is changed
2261 # to take a 64-bit long, this test should apply to all platforms.
2262 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
2263 'only applies to 32-bit platforms')
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002264 def test_expandtabs_overflows_gracefully(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +00002265 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002266
Victor Stinner1d972ad2011-10-07 13:31:46 +02002267 @support.cpython_only
Antoine Pitroue19aa382011-10-04 16:04:01 +02002268 def test_expandtabs_optimization(self):
2269 s = 'abc'
2270 self.assertIs(s.expandtabs(), s)
2271
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002272 def test_raiseMemError(self):
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002273 if struct.calcsize('P') == 8:
2274 # 64 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002275 ascii_struct_size = 48
2276 compact_struct_size = 72
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002277 else:
2278 # 32 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002279 ascii_struct_size = 24
2280 compact_struct_size = 36
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002281
2282 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
2283 code = ord(char)
2284 if code < 0x100:
2285 char_size = 1 # sizeof(Py_UCS1)
2286 struct_size = ascii_struct_size
2287 elif code < 0x10000:
2288 char_size = 2 # sizeof(Py_UCS2)
2289 struct_size = compact_struct_size
2290 else:
2291 char_size = 4 # sizeof(Py_UCS4)
2292 struct_size = compact_struct_size
2293 # Note: sys.maxsize is half of the actual max allocation because of
Martin v. Löwis287eca62011-09-28 10:03:28 +02002294 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2295 # be allocatable, given enough memory.
2296 maxlen = ((sys.maxsize - struct_size) // char_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002297 alloc = lambda: char * maxlen
2298 self.assertRaises(MemoryError, alloc)
2299 self.assertRaises(MemoryError, alloc)
Antoine Pitrou3db3e872008-08-17 17:06:51 +00002300
Victor Stinner808fc0a2010-03-22 12:50:40 +00002301 def test_format_subclass(self):
2302 class S(str):
2303 def __str__(self):
2304 return '__str__ overridden'
2305 s = S('xxx')
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002306 self.assertEqual("%s" % s, '__str__ overridden')
2307 self.assertEqual("{}".format(s), '__str__ overridden')
Victor Stinner808fc0a2010-03-22 12:50:40 +00002308
Serhiy Storchaka63b5b6f2016-10-02 21:16:38 +03002309 def test_subclass_add(self):
2310 class S(str):
2311 def __add__(self, o):
2312 return "3"
2313 self.assertEqual(S("4") + S("5"), "3")
2314 class S(str):
2315 def __iadd__(self, o):
2316 return "3"
2317 s = S("1")
2318 s += "4"
2319 self.assertEqual(s, "3")
2320
2321 def test_getnewargs(self):
2322 text = 'abc'
2323 args = text.__getnewargs__()
2324 self.assertIsNot(args[0], text)
2325 self.assertEqual(args[0], text)
2326 self.assertEqual(len(args), 1)
2327
2328 def test_resize(self):
2329 for length in range(1, 100, 7):
2330 # generate a fresh string (refcount=1)
2331 text = 'a' * length + 'b'
2332
2333 with support.check_warnings(('unicode_internal codec has been '
2334 'deprecated', DeprecationWarning)):
2335 # fill wstr internal field
2336 abc = text.encode('unicode_internal')
2337 self.assertEqual(abc.decode('unicode_internal'), text)
2338
2339 # resize text: wstr field must be cleared and then recomputed
2340 text += 'c'
2341 abcdef = text.encode('unicode_internal')
2342 self.assertNotEqual(abc, abcdef)
2343 self.assertEqual(abcdef.decode('unicode_internal'), text)
2344
2345 def test_compare(self):
2346 # Issue #17615
2347 N = 10
2348 ascii = 'a' * N
2349 ascii2 = 'z' * N
2350 latin = '\x80' * N
2351 latin2 = '\xff' * N
2352 bmp = '\u0100' * N
2353 bmp2 = '\uffff' * N
2354 astral = '\U00100000' * N
2355 astral2 = '\U0010ffff' * N
2356 strings = (
2357 ascii, ascii2,
2358 latin, latin2,
2359 bmp, bmp2,
2360 astral, astral2)
2361 for text1, text2 in itertools.combinations(strings, 2):
2362 equal = (text1 is text2)
2363 self.assertEqual(text1 == text2, equal)
2364 self.assertEqual(text1 != text2, not equal)
2365
2366 if equal:
2367 self.assertTrue(text1 <= text2)
2368 self.assertTrue(text1 >= text2)
2369
2370 # text1 is text2: duplicate strings to skip the "str1 == str2"
2371 # optimization in unicode_compare_eq() and really compare
2372 # character per character
2373 copy1 = duplicate_string(text1)
2374 copy2 = duplicate_string(text2)
2375 self.assertIsNot(copy1, copy2)
2376
2377 self.assertTrue(copy1 == copy2)
2378 self.assertFalse(copy1 != copy2)
2379
2380 self.assertTrue(copy1 <= copy2)
2381 self.assertTrue(copy2 >= copy2)
2382
2383 self.assertTrue(ascii < ascii2)
2384 self.assertTrue(ascii < latin)
2385 self.assertTrue(ascii < bmp)
2386 self.assertTrue(ascii < astral)
2387 self.assertFalse(ascii >= ascii2)
2388 self.assertFalse(ascii >= latin)
2389 self.assertFalse(ascii >= bmp)
2390 self.assertFalse(ascii >= astral)
2391
2392 self.assertFalse(latin < ascii)
2393 self.assertTrue(latin < latin2)
2394 self.assertTrue(latin < bmp)
2395 self.assertTrue(latin < astral)
2396 self.assertTrue(latin >= ascii)
2397 self.assertFalse(latin >= latin2)
2398 self.assertFalse(latin >= bmp)
2399 self.assertFalse(latin >= astral)
2400
2401 self.assertFalse(bmp < ascii)
2402 self.assertFalse(bmp < latin)
2403 self.assertTrue(bmp < bmp2)
2404 self.assertTrue(bmp < astral)
2405 self.assertTrue(bmp >= ascii)
2406 self.assertTrue(bmp >= latin)
2407 self.assertFalse(bmp >= bmp2)
2408 self.assertFalse(bmp >= astral)
2409
2410 self.assertFalse(astral < ascii)
2411 self.assertFalse(astral < latin)
2412 self.assertFalse(astral < bmp2)
2413 self.assertTrue(astral < astral2)
2414 self.assertTrue(astral >= ascii)
2415 self.assertTrue(astral >= latin)
2416 self.assertTrue(astral >= bmp2)
2417 self.assertFalse(astral >= astral2)
2418
2419 def test_free_after_iterating(self):
2420 support.check_free_after_iterating(self, iter, str)
2421 support.check_free_after_iterating(self, reversed, str)
2422
2423
2424class CAPITest(unittest.TestCase):
2425
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002426 # Test PyUnicode_FromFormat()
Victor Stinner1205f272010-09-11 00:54:47 +00002427 def test_from_format(self):
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002428 support.import_module('ctypes')
Victor Stinner15a11362012-10-06 23:48:20 +02002429 from ctypes import (
2430 pythonapi, py_object, sizeof,
Victor Stinner6d970f42011-03-02 00:04:25 +00002431 c_int, c_long, c_longlong, c_ssize_t,
Victor Stinner15a11362012-10-06 23:48:20 +02002432 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002433 name = "PyUnicode_FromFormat"
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002434 _PyUnicode_FromFormat = getattr(pythonapi, name)
2435 _PyUnicode_FromFormat.restype = py_object
2436
2437 def PyUnicode_FromFormat(format, *args):
2438 cargs = tuple(
2439 py_object(arg) if isinstance(arg, str) else arg
2440 for arg in args)
2441 return _PyUnicode_FromFormat(format, *cargs)
Victor Stinner1205f272010-09-11 00:54:47 +00002442
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002443 def check_format(expected, format, *args):
2444 text = PyUnicode_FromFormat(format, *args)
2445 self.assertEqual(expected, text)
2446
Victor Stinner1205f272010-09-11 00:54:47 +00002447 # ascii format, non-ascii argument
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002448 check_format('ascii\x7f=unicode\xe9',
2449 b'ascii\x7f=%U', 'unicode\xe9')
Victor Stinner1205f272010-09-11 00:54:47 +00002450
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002451 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
2452 # raises an error
Ezio Melottied3a7d22010-12-01 02:32:32 +00002453 self.assertRaisesRegex(ValueError,
R David Murray44b548d2016-09-08 13:59:53 -04002454 r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
Victor Stinner4c7db312010-09-12 07:51:18 +00002455 'string, got a non-ASCII byte: 0xe9$',
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002456 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002457
Victor Stinner96865452011-03-01 23:44:09 +00002458 # test "%c"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002459 check_format('\uabcd',
2460 b'%c', c_int(0xabcd))
2461 check_format('\U0010ffff',
2462 b'%c', c_int(0x10ffff))
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002463 with self.assertRaises(OverflowError):
2464 PyUnicode_FromFormat(b'%c', c_int(0x110000))
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +03002465 # Issue #18183
Serhiy Storchakaf15ffe02013-06-12 09:28:20 +03002466 check_format('\U00010000\U00100000',
2467 b'%c%c', c_int(0x10000), c_int(0x100000))
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002468
Victor Stinner96865452011-03-01 23:44:09 +00002469 # test "%"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002470 check_format('%',
2471 b'%')
2472 check_format('%',
2473 b'%%')
2474 check_format('%s',
2475 b'%%s')
2476 check_format('[%]',
2477 b'[%%]')
2478 check_format('%abc',
2479 b'%%%s', b'abc')
2480
2481 # truncated string
2482 check_format('abc',
2483 b'%.3s', b'abcdef')
2484 check_format('abc[\ufffd',
2485 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
2486 check_format("'\\u20acABC'",
2487 b'%A', '\u20acABC')
2488 check_format("'\\u20",
2489 b'%.5A', '\u20acABCDEF')
2490 check_format("'\u20acABC'",
2491 b'%R', '\u20acABC')
2492 check_format("'\u20acA",
2493 b'%.3R', '\u20acABCDEF')
2494 check_format('\u20acAB',
2495 b'%.3S', '\u20acABCDEF')
2496 check_format('\u20acAB',
2497 b'%.3U', '\u20acABCDEF')
2498 check_format('\u20acAB',
2499 b'%.3V', '\u20acABCDEF', None)
2500 check_format('abc[\ufffd',
2501 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
2502
2503 # following tests comes from #7330
2504 # test width modifier and precision modifier with %S
2505 check_format("repr= abc",
2506 b'repr=%5S', 'abc')
2507 check_format("repr=ab",
2508 b'repr=%.2S', 'abc')
2509 check_format("repr= ab",
2510 b'repr=%5.2S', 'abc')
2511
2512 # test width modifier and precision modifier with %R
2513 check_format("repr= 'abc'",
2514 b'repr=%8R', 'abc')
2515 check_format("repr='ab",
2516 b'repr=%.3R', 'abc')
2517 check_format("repr= 'ab",
2518 b'repr=%5.3R', 'abc')
2519
2520 # test width modifier and precision modifier with %A
2521 check_format("repr= 'abc'",
2522 b'repr=%8A', 'abc')
2523 check_format("repr='ab",
2524 b'repr=%.3A', 'abc')
2525 check_format("repr= 'ab",
2526 b'repr=%5.3A', 'abc')
2527
2528 # test width modifier and precision modifier with %s
2529 check_format("repr= abc",
2530 b'repr=%5s', b'abc')
2531 check_format("repr=ab",
2532 b'repr=%.2s', b'abc')
2533 check_format("repr= ab",
2534 b'repr=%5.2s', b'abc')
2535
2536 # test width modifier and precision modifier with %U
2537 check_format("repr= abc",
2538 b'repr=%5U', 'abc')
2539 check_format("repr=ab",
2540 b'repr=%.2U', 'abc')
2541 check_format("repr= ab",
2542 b'repr=%5.2U', 'abc')
2543
2544 # test width modifier and precision modifier with %V
2545 check_format("repr= abc",
2546 b'repr=%5V', 'abc', b'123')
2547 check_format("repr=ab",
2548 b'repr=%.2V', 'abc', b'123')
2549 check_format("repr= ab",
2550 b'repr=%5.2V', 'abc', b'123')
2551 check_format("repr= 123",
2552 b'repr=%5V', None, b'123')
2553 check_format("repr=12",
2554 b'repr=%.2V', None, b'123')
2555 check_format("repr= 12",
2556 b'repr=%5.2V', None, b'123')
Victor Stinner96865452011-03-01 23:44:09 +00002557
Victor Stinner6d970f42011-03-02 00:04:25 +00002558 # test integer formats (%i, %d, %u)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002559 check_format('010',
2560 b'%03i', c_int(10))
2561 check_format('0010',
2562 b'%0.4i', c_int(10))
2563 check_format('-123',
2564 b'%i', c_int(-123))
2565 check_format('-123',
2566 b'%li', c_long(-123))
2567 check_format('-123',
2568 b'%lli', c_longlong(-123))
2569 check_format('-123',
2570 b'%zi', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002571
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002572 check_format('-123',
2573 b'%d', c_int(-123))
2574 check_format('-123',
2575 b'%ld', c_long(-123))
2576 check_format('-123',
2577 b'%lld', c_longlong(-123))
2578 check_format('-123',
2579 b'%zd', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002580
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002581 check_format('123',
2582 b'%u', c_uint(123))
2583 check_format('123',
2584 b'%lu', c_ulong(123))
2585 check_format('123',
2586 b'%llu', c_ulonglong(123))
2587 check_format('123',
2588 b'%zu', c_size_t(123))
Victor Stinner6d970f42011-03-02 00:04:25 +00002589
Victor Stinner15a11362012-10-06 23:48:20 +02002590 # test long output
2591 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
2592 max_longlong = -min_longlong - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002593 check_format(str(min_longlong),
2594 b'%lld', c_longlong(min_longlong))
2595 check_format(str(max_longlong),
2596 b'%lld', c_longlong(max_longlong))
Victor Stinner15a11362012-10-06 23:48:20 +02002597 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002598 check_format(str(max_ulonglong),
2599 b'%llu', c_ulonglong(max_ulonglong))
Victor Stinner15a11362012-10-06 23:48:20 +02002600 PyUnicode_FromFormat(b'%p', c_void_p(-1))
2601
Victor Stinnere215d962012-10-06 23:03:36 +02002602 # test padding (width and/or precision)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002603 check_format('123'.rjust(10, '0'),
2604 b'%010i', c_int(123))
2605 check_format('123'.rjust(100),
2606 b'%100i', c_int(123))
2607 check_format('123'.rjust(100, '0'),
2608 b'%.100i', c_int(123))
2609 check_format('123'.rjust(80, '0').rjust(100),
2610 b'%100.80i', c_int(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002611
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002612 check_format('123'.rjust(10, '0'),
2613 b'%010u', c_uint(123))
2614 check_format('123'.rjust(100),
2615 b'%100u', c_uint(123))
2616 check_format('123'.rjust(100, '0'),
2617 b'%.100u', c_uint(123))
2618 check_format('123'.rjust(80, '0').rjust(100),
2619 b'%100.80u', c_uint(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002620
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002621 check_format('123'.rjust(10, '0'),
2622 b'%010x', c_int(0x123))
2623 check_format('123'.rjust(100),
2624 b'%100x', c_int(0x123))
2625 check_format('123'.rjust(100, '0'),
2626 b'%.100x', c_int(0x123))
2627 check_format('123'.rjust(80, '0').rjust(100),
2628 b'%100.80x', c_int(0x123))
Victor Stinnere215d962012-10-06 23:03:36 +02002629
Victor Stinner6d970f42011-03-02 00:04:25 +00002630 # test %A
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002631 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
2632 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
Victor Stinner9a909002010-10-18 20:59:24 +00002633
Victor Stinner6d970f42011-03-02 00:04:25 +00002634 # test %V
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002635 check_format('repr=abc',
2636 b'repr=%V', 'abc', b'xyz')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002637
2638 # Test string decode from parameter of %s using utf-8.
2639 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
2640 # '\u4eba\u6c11'
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002641 check_format('repr=\u4eba\u6c11',
2642 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002643
2644 #Test replace error handler.
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002645 check_format('repr=abc\ufffd',
2646 b'repr=%V', None, b'abc\xff')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002647
Victor Stinner6d970f42011-03-02 00:04:25 +00002648 # not supported: copy the raw format string. these tests are just here
Martin Panter2f9171d2016-12-18 01:23:09 +00002649 # to check for crashes and should not be considered as specifications
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002650 check_format('%s',
2651 b'%1%s', b'abc')
2652 check_format('%1abc',
2653 b'%1abc')
2654 check_format('%+i',
2655 b'%+i', c_int(10))
2656 check_format('%.%s',
2657 b'%.%s', b'abc')
Victor Stinner6d970f42011-03-02 00:04:25 +00002658
Victor Stinner1c24bd02010-10-02 11:03:13 +00002659 # Test PyUnicode_AsWideChar()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002660 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002661 def test_aswidechar(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002662 from _testcapi import unicode_aswidechar
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002663 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002664 from ctypes import c_wchar, sizeof
2665
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002666 wchar, size = unicode_aswidechar('abcdef', 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002667 self.assertEqual(size, 2)
2668 self.assertEqual(wchar, 'ab')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002669
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002670 wchar, size = unicode_aswidechar('abc', 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002671 self.assertEqual(size, 3)
2672 self.assertEqual(wchar, 'abc')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002673
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002674 wchar, size = unicode_aswidechar('abc', 4)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002675 self.assertEqual(size, 3)
2676 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002677
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002678 wchar, size = unicode_aswidechar('abc', 10)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002679 self.assertEqual(size, 3)
2680 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002681
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002682 wchar, size = unicode_aswidechar('abc\0def', 20)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002683 self.assertEqual(size, 7)
2684 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002685
Victor Stinner5593d8a2010-10-02 11:11:27 +00002686 nonbmp = chr(0x10ffff)
2687 if sizeof(c_wchar) == 2:
2688 buflen = 3
2689 nchar = 2
2690 else: # sizeof(c_wchar) == 4
2691 buflen = 2
2692 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002693 wchar, size = unicode_aswidechar(nonbmp, buflen)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002694 self.assertEqual(size, nchar)
2695 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002696
Victor Stinner1c24bd02010-10-02 11:03:13 +00002697 # Test PyUnicode_AsWideCharString()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002698 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002699 def test_aswidecharstring(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002700 from _testcapi import unicode_aswidecharstring
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002701 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002702 from ctypes import c_wchar, sizeof
2703
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002704 wchar, size = unicode_aswidecharstring('abc')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002705 self.assertEqual(size, 3)
2706 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002707
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002708 wchar, size = unicode_aswidecharstring('abc\0def')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002709 self.assertEqual(size, 7)
2710 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002711
Victor Stinner5593d8a2010-10-02 11:11:27 +00002712 nonbmp = chr(0x10ffff)
2713 if sizeof(c_wchar) == 2:
2714 nchar = 2
2715 else: # sizeof(c_wchar) == 4
2716 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002717 wchar, size = unicode_aswidecharstring(nonbmp)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002718 self.assertEqual(size, nchar)
2719 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002720
Serhiy Storchakacc164232016-10-02 21:29:26 +03002721 # Test PyUnicode_AsUCS4()
2722 @support.cpython_only
2723 def test_asucs4(self):
2724 from _testcapi import unicode_asucs4
2725 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
2726 'a\ud800b\udfffc', '\ud834\udd1e']:
2727 l = len(s)
2728 self.assertEqual(unicode_asucs4(s, l, 1), s+'\0')
2729 self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff')
2730 self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff')
2731 self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff')
2732 self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1)
2733 self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0)
2734 s = '\0'.join([s, s])
2735 self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0')
2736 self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff')
2737
Serhiy Storchaka9c0e1f82016-10-08 22:45:38 +03002738 # Test PyUnicode_CopyCharacters()
2739 @support.cpython_only
2740 def test_copycharacters(self):
2741 from _testcapi import unicode_copycharacters
2742
2743 strings = [
2744 'abcde', '\xa1\xa2\xa3\xa4\xa5',
2745 '\u4f60\u597d\u4e16\u754c\uff01',
2746 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
2747 ]
2748
2749 for idx, from_ in enumerate(strings):
2750 # wide -> narrow: exceed maxchar limitation
2751 for to in strings[:idx]:
2752 self.assertRaises(
2753 SystemError,
2754 unicode_copycharacters, to, 0, from_, 0, 5
2755 )
2756 # same kind
2757 for from_start in range(5):
2758 self.assertEqual(
2759 unicode_copycharacters(from_, 0, from_, from_start, 5),
2760 (from_[from_start:from_start+5].ljust(5, '\0'),
2761 5-from_start)
2762 )
2763 for to_start in range(5):
2764 self.assertEqual(
2765 unicode_copycharacters(from_, to_start, from_, to_start, 5),
2766 (from_[to_start:to_start+5].rjust(5, '\0'),
2767 5-to_start)
2768 )
2769 # narrow -> wide
2770 # Tests omitted since this creates invalid strings.
2771
2772 s = strings[0]
2773 self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
2774 self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
2775 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
2776 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
2777 self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
2778 self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
2779 self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
2780
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002781 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002782 def test_encode_decimal(self):
2783 from _testcapi import unicode_encodedecimal
2784 self.assertEqual(unicode_encodedecimal('123'),
2785 b'123')
2786 self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
2787 b'3.14')
2788 self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2789 b' 3.14 ')
2790 self.assertRaises(UnicodeEncodeError,
2791 unicode_encodedecimal, "123\u20ac", "strict")
Victor Stinner6345be92011-11-25 20:09:01 +01002792 self.assertRaisesRegex(
2793 ValueError,
2794 "^'decimal' codec can't encode character",
2795 unicode_encodedecimal, "123\u20ac", "replace")
Victor Stinner42bf7752011-11-21 22:52:58 +01002796
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002797 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002798 def test_transform_decimal(self):
2799 from _testcapi import unicode_transformdecimaltoascii as transform_decimal
2800 self.assertEqual(transform_decimal('123'),
2801 '123')
2802 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
2803 '3.14')
2804 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2805 "\N{EM SPACE}3.14\N{EN SPACE}")
2806 self.assertEqual(transform_decimal('123\u20ac'),
2807 '123\u20ac')
2808
Serhiy Storchaka7aa69082015-12-03 01:02:03 +02002809 @support.cpython_only
2810 def test_pep393_utf8_caching_bug(self):
2811 # Issue #25709: Problem with string concatenation and utf-8 cache
2812 from _testcapi import getargs_s_hash
2813 for k in 0x24, 0xa4, 0x20ac, 0x1f40d:
2814 s = ''
2815 for i in range(5):
2816 # Due to CPython specific optimization the 's' string can be
2817 # resized in-place.
2818 s += chr(k)
2819 # Parsing with the "s#" format code calls indirectly
2820 # PyUnicode_AsUTF8AndSize() which creates the UTF-8
2821 # encoded string cached in the Unicode object.
2822 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
2823 # Check that the second call returns the same result
2824 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
2825
Eric Smitha1eac722011-01-29 11:15:35 +00002826class StringModuleTest(unittest.TestCase):
2827 def test_formatter_parser(self):
2828 def parse(format):
2829 return list(_string.formatter_parser(format))
2830
2831 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2832 self.assertEqual(formatter, [
2833 ('prefix ', '2', '', 's'),
2834 ('xxx', '0', '^+10.3f', None),
2835 ('', 'obj.attr', '', 's'),
2836 (' ', 'z[0]', '10', 's'),
2837 ])
2838
2839 formatter = parse("prefix {} suffix")
2840 self.assertEqual(formatter, [
2841 ('prefix ', '', '', None),
2842 (' suffix', None, None, None),
2843 ])
2844
2845 formatter = parse("str")
2846 self.assertEqual(formatter, [
2847 ('str', None, None, None),
2848 ])
2849
2850 formatter = parse("")
2851 self.assertEqual(formatter, [])
2852
2853 formatter = parse("{0}")
2854 self.assertEqual(formatter, [
2855 ('', '0', '', None),
2856 ])
2857
2858 self.assertRaises(TypeError, _string.formatter_parser, 1)
2859
2860 def test_formatter_field_name_split(self):
2861 def split(name):
2862 items = list(_string.formatter_field_name_split(name))
2863 items[1] = list(items[1])
2864 return items
2865 self.assertEqual(split("obj"), ["obj", []])
2866 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
2867 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
2868 self.assertEqual(split("obj.arg[key1][key2]"), [
2869 "obj",
2870 [(True, 'arg'),
2871 (False, 'key1'),
2872 (False, 'key2'),
2873 ]])
2874 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
2875
2876
Walter Dörwald28256f22003-01-19 16:59:20 +00002877if __name__ == "__main__":
Ezio Melotti0dceb562013-01-10 07:43:26 +02002878 unittest.main()