blob: 9ae31d17d234e39069d19056f4f7577b7efafc7b [file] [log] [blame]
Guido van Rossuma831cac2000-03-10 23:23:21 +00001""" Test script for the Unicode implementation.
2
Guido van Rossuma831cac2000-03-10 23:23:21 +00003Written by Marc-Andre Lemburg (mal@lemburg.com).
4
5(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
6
Marc-André Lemburg36619082001-01-17 19:11:13 +00007"""#"
Victor Stinner040e16e2011-11-15 22:44:05 +01008import _string
Guido van Rossum98297ee2007-11-06 21:34:58 +00009import codecs
Victor Stinner9fc59812013-04-08 22:34:43 +020010import itertools
Guido van Rossum98297ee2007-11-06 21:34:58 +000011import struct
12import sys
13import unittest
14import warnings
Benjamin Petersonee8712c2008-05-20 21:35:26 +000015from test import support, string_tests
Guido van Rossuma831cac2000-03-10 23:23:21 +000016
Neal Norwitz430f68b2005-11-24 22:00:56 +000017# Error handling (bad decoder return)
18def search_function(encoding):
19 def decode1(input, errors="strict"):
20 return 42 # not a tuple
21 def encode1(input, errors="strict"):
22 return 42 # not a tuple
23 def encode2(input, errors="strict"):
24 return (42, 42) # no unicode
25 def decode2(input, errors="strict"):
26 return (42, 42) # no unicode
27 if encoding=="test.unicode1":
28 return (encode1, decode1, None, None)
29 elif encoding=="test.unicode2":
30 return (encode2, decode2, None, None)
31 else:
32 return None
33codecs.register(search_function)
34
Victor Stinner9fc59812013-04-08 22:34:43 +020035def duplicate_string(text):
36 """
37 Try to get a fresh clone of the specified text:
38 new object with a reference count of 1.
39
40 This is a best-effort: latin1 single letters and the empty
41 string ('') are singletons and cannot be cloned.
42 """
43 return text.encode().decode()
44
Brett Cannon226b2302010-03-20 22:22:22 +000045class UnicodeTest(string_tests.CommonTest,
46 string_tests.MixinStrUnicodeUserStringTest,
Ezio Melotti0dceb562013-01-10 07:43:26 +020047 string_tests.MixinStrUnicodeTest,
48 unittest.TestCase):
Brett Cannon226b2302010-03-20 22:22:22 +000049
Guido van Rossumef87d6e2007-05-02 19:09:54 +000050 type2test = str
Walter Dörwald0fd583c2003-02-21 12:53:50 +000051
52 def checkequalnofix(self, result, object, methodname, *args):
53 method = getattr(object, methodname)
54 realresult = method(*args)
55 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000056 self.assertTrue(type(realresult) is type(result))
Walter Dörwald0fd583c2003-02-21 12:53:50 +000057
58 # if the original is returned make sure that
59 # this doesn't happen with subclasses
60 if realresult is object:
Guido van Rossumef87d6e2007-05-02 19:09:54 +000061 class usub(str):
Walter Dörwald0fd583c2003-02-21 12:53:50 +000062 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000063 return 'usub(%r)' % str.__repr__(self)
Walter Dörwald0fd583c2003-02-21 12:53:50 +000064 object = usub(object)
65 method = getattr(object, methodname)
66 realresult = method(*args)
67 self.assertEqual(realresult, result)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000068 self.assertTrue(object is not realresult)
Guido van Rossume4874ae2001-09-21 15:36:41 +000069
Jeremy Hylton504de6b2003-10-06 05:08:26 +000070 def test_literals(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +000071 self.assertEqual('\xff', '\u00ff')
72 self.assertEqual('\uffff', '\U0000ffff')
Guido van Rossum36e0a922007-07-20 04:05:57 +000073 self.assertRaises(SyntaxError, eval, '\'\\Ufffffffe\'')
74 self.assertRaises(SyntaxError, eval, '\'\\Uffffffff\'')
75 self.assertRaises(SyntaxError, eval, '\'\\U%08x\'' % 0x110000)
Benjamin Petersoncd76c272008-04-05 15:09:30 +000076 # raw strings should not have unicode escapes
Florent Xiclunaa87b3832010-09-13 02:28:18 +000077 self.assertNotEqual(r"\u0020", " ")
Jeremy Hylton504de6b2003-10-06 05:08:26 +000078
Georg Brandl559e5d72008-06-11 18:37:52 +000079 def test_ascii(self):
80 if not sys.platform.startswith('java'):
81 # Test basic sanity of repr()
82 self.assertEqual(ascii('abc'), "'abc'")
83 self.assertEqual(ascii('ab\\c'), "'ab\\\\c'")
84 self.assertEqual(ascii('ab\\'), "'ab\\\\'")
85 self.assertEqual(ascii('\\c'), "'\\\\c'")
86 self.assertEqual(ascii('\\'), "'\\\\'")
87 self.assertEqual(ascii('\n'), "'\\n'")
88 self.assertEqual(ascii('\r'), "'\\r'")
89 self.assertEqual(ascii('\t'), "'\\t'")
90 self.assertEqual(ascii('\b'), "'\\x08'")
91 self.assertEqual(ascii("'\""), """'\\'"'""")
92 self.assertEqual(ascii("'\""), """'\\'"'""")
93 self.assertEqual(ascii("'"), '''"'"''')
94 self.assertEqual(ascii('"'), """'"'""")
95 latin1repr = (
96 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
97 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
98 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
99 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
100 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
101 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
102 "\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9"
103 "\\xaa\\xab\\xac\\xad\\xae\\xaf\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7"
104 "\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5"
105 "\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3"
106 "\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1"
107 "\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef"
108 "\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd"
109 "\\xfe\\xff'")
110 testrepr = ascii(''.join(map(chr, range(256))))
111 self.assertEqual(testrepr, latin1repr)
112 # Test ascii works on wide unicode escapes without overflow.
113 self.assertEqual(ascii("\U00010000" * 39 + "\uffff" * 4096),
114 ascii("\U00010000" * 39 + "\uffff" * 4096))
115
116 class WrongRepr:
117 def __repr__(self):
118 return b'byte-repr'
119 self.assertRaises(TypeError, ascii, WrongRepr())
120
Walter Dörwald28256f22003-01-19 16:59:20 +0000121 def test_repr(self):
122 if not sys.platform.startswith('java'):
123 # Test basic sanity of repr()
Walter Dörwald67e83882007-05-05 12:26:27 +0000124 self.assertEqual(repr('abc'), "'abc'")
125 self.assertEqual(repr('ab\\c'), "'ab\\\\c'")
126 self.assertEqual(repr('ab\\'), "'ab\\\\'")
127 self.assertEqual(repr('\\c'), "'\\\\c'")
128 self.assertEqual(repr('\\'), "'\\\\'")
129 self.assertEqual(repr('\n'), "'\\n'")
130 self.assertEqual(repr('\r'), "'\\r'")
131 self.assertEqual(repr('\t'), "'\\t'")
132 self.assertEqual(repr('\b'), "'\\x08'")
133 self.assertEqual(repr("'\""), """'\\'"'""")
134 self.assertEqual(repr("'\""), """'\\'"'""")
135 self.assertEqual(repr("'"), '''"'"''')
136 self.assertEqual(repr('"'), """'"'""")
Walter Dörwald28256f22003-01-19 16:59:20 +0000137 latin1repr = (
Walter Dörwald67e83882007-05-05 12:26:27 +0000138 "'\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\t\\n\\x0b\\x0c\\r"
Walter Dörwald28256f22003-01-19 16:59:20 +0000139 "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a"
140 "\\x1b\\x1c\\x1d\\x1e\\x1f !\"#$%&\\'()*+,-./0123456789:;<=>?@ABCDEFGHI"
141 "JKLMNOPQRSTUVWXYZ[\\\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f"
142 "\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d"
143 "\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b"
Georg Brandl559e5d72008-06-11 18:37:52 +0000144 "\\x9c\\x9d\\x9e\\x9f\\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9"
145 "\xaa\xab\xac\\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7"
146 "\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5"
147 "\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
148 "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1"
149 "\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef"
150 "\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd"
151 "\xfe\xff'")
Guido van Rossum805365e2007-05-07 22:24:25 +0000152 testrepr = repr(''.join(map(chr, range(256))))
Walter Dörwald28256f22003-01-19 16:59:20 +0000153 self.assertEqual(testrepr, latin1repr)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000154 # Test repr works on wide unicode escapes without overflow.
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000155 self.assertEqual(repr("\U00010000" * 39 + "\uffff" * 4096),
156 repr("\U00010000" * 39 + "\uffff" * 4096))
Walter Dörwald28256f22003-01-19 16:59:20 +0000157
Georg Brandl559e5d72008-06-11 18:37:52 +0000158 class WrongRepr:
159 def __repr__(self):
160 return b'byte-repr'
161 self.assertRaises(TypeError, repr, WrongRepr())
162
Guido van Rossum49d6b072006-08-17 21:11:47 +0000163 def test_iterators(self):
164 # Make sure unicode objects have an __iter__ method
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000165 it = "\u1111\u2222\u3333".__iter__()
166 self.assertEqual(next(it), "\u1111")
167 self.assertEqual(next(it), "\u2222")
168 self.assertEqual(next(it), "\u3333")
Georg Brandla18af4e2007-04-21 15:47:16 +0000169 self.assertRaises(StopIteration, next, it)
Guido van Rossum49d6b072006-08-17 21:11:47 +0000170
Walter Dörwald28256f22003-01-19 16:59:20 +0000171 def test_count(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000172 string_tests.CommonTest.test_count(self)
173 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000174 self.checkequalnofix(3, 'aaa', 'count', 'a')
175 self.checkequalnofix(0, 'aaa', 'count', 'b')
176 self.checkequalnofix(3, 'aaa', 'count', 'a')
177 self.checkequalnofix(0, 'aaa', 'count', 'b')
178 self.checkequalnofix(0, 'aaa', 'count', 'b')
179 self.checkequalnofix(1, 'aaa', 'count', 'a', -1)
180 self.checkequalnofix(3, 'aaa', 'count', 'a', -10)
181 self.checkequalnofix(2, 'aaa', 'count', 'a', 0, -1)
182 self.checkequalnofix(0, 'aaa', 'count', 'a', 0, -10)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000183
Walter Dörwald28256f22003-01-19 16:59:20 +0000184 def test_find(self):
Antoine Pitrouc0bbe7d2011-10-08 22:41:35 +0200185 string_tests.CommonTest.test_find(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200186 # test implementation details of the memchr fast path
187 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
188 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
189 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
190 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
191 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
192 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
193 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
194 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000195 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
196 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
197 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000198
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000199 self.assertRaises(TypeError, 'hello'.find)
200 self.assertRaises(TypeError, 'hello'.find, 42)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000201
Walter Dörwald28256f22003-01-19 16:59:20 +0000202 def test_rfind(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000203 string_tests.CommonTest.test_rfind(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200204 # test implementation details of the memrchr fast path
205 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
206 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
207 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
208 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
209 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
210 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
211 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000212 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000213 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
214 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
215 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
Guido van Rossum8b264542000-12-19 02:22:31 +0000216
Walter Dörwald28256f22003-01-19 16:59:20 +0000217 def test_index(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000218 string_tests.CommonTest.test_index(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000219 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
220 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
221 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
222 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
223 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
224 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
225 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
226 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000227
Walter Dörwald28256f22003-01-19 16:59:20 +0000228 def test_rindex(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000229 string_tests.CommonTest.test_rindex(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000230 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
231 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
232 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
233 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000234
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000235 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
236 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
237 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
238 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
239 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000240
Georg Brandlceee0772007-11-27 23:48:05 +0000241 def test_maketrans_translate(self):
242 # these work with plain translate()
243 self.checkequalnofix('bbbc', 'abababc', 'translate',
244 {ord('a'): None})
245 self.checkequalnofix('iiic', 'abababc', 'translate',
246 {ord('a'): None, ord('b'): ord('i')})
247 self.checkequalnofix('iiix', 'abababc', 'translate',
248 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
249 self.checkequalnofix('c', 'abababc', 'translate',
250 {ord('a'): None, ord('b'): ''})
251 self.checkequalnofix('xyyx', 'xzx', 'translate',
252 {ord('z'): 'yy'})
253 # this needs maketrans()
254 self.checkequalnofix('abababc', 'abababc', 'translate',
255 {'b': '<i>'})
256 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
257 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
258 # test alternative way of calling maketrans()
259 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
260 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
261
262 self.assertRaises(TypeError, self.type2test.maketrans)
263 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
264 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
265 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
266 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
267 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
268 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
Guido van Rossuma831cac2000-03-10 23:23:21 +0000269
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000270 self.assertRaises(TypeError, 'hello'.translate)
Walter Dörwald67e83882007-05-05 12:26:27 +0000271 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000272
Walter Dörwald28256f22003-01-19 16:59:20 +0000273 def test_split(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000274 string_tests.CommonTest.test_split(self)
Andrew M. Kuchlingeddd68d2002-03-29 16:21:44 +0000275
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000276 # Mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000277 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
278 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
279 self.checkequalnofix(['endcase ', ''], 'endcase test', 'split', 'test')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000280
Walter Dörwald28256f22003-01-19 16:59:20 +0000281 def test_join(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000282 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +0000283
Guido van Rossumf1044292007-09-27 18:01:22 +0000284 class MyWrapper:
285 def __init__(self, sval): self.sval = sval
286 def __str__(self): return self.sval
287
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000288 # mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000289 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
290 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
291 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
292 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
293 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
294 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
295 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000296 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
297 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
298 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
299 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
Marc-André Lemburge5034372000-08-08 08:04:29 +0000300
Walter Dörwald28256f22003-01-19 16:59:20 +0000301 def test_replace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000302 string_tests.CommonTest.test_replace(self)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000303
Walter Dörwald28256f22003-01-19 16:59:20 +0000304 # method call forwarded from str implementation because of unicode argument
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000305 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
306 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000307
Victor Stinner59de0ee2011-10-07 10:01:28 +0200308 @support.cpython_only
309 def test_replace_id(self):
Victor Stinner1d972ad2011-10-07 13:31:46 +0200310 pattern = 'abc'
311 text = 'abc def'
312 self.assertIs(text.replace(pattern, pattern), text)
Victor Stinner59de0ee2011-10-07 10:01:28 +0200313
Guido van Rossum98297ee2007-11-06 21:34:58 +0000314 def test_bytes_comparison(self):
Brett Cannon226b2302010-03-20 22:22:22 +0000315 with support.check_warnings():
316 warnings.simplefilter('ignore', BytesWarning)
317 self.assertEqual('abc' == b'abc', False)
318 self.assertEqual('abc' != b'abc', True)
319 self.assertEqual('abc' == bytearray(b'abc'), False)
320 self.assertEqual('abc' != bytearray(b'abc'), True)
Brett Cannon40430012007-10-22 20:24:51 +0000321
Walter Dörwald28256f22003-01-19 16:59:20 +0000322 def test_comparison(self):
323 # Comparisons:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000324 self.assertEqual('abc', 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000325 self.assertTrue('abcd' > 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000326 self.assertTrue('abc' < 'abcd')
Walter Dörwald28256f22003-01-19 16:59:20 +0000327
328 if 0:
329 # Move these tests to a Unicode collation module test...
330 # Testing UTF-16 code point order comparisons...
331
332 # No surrogates, no fixup required.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000333 self.assertTrue('\u0061' < '\u20ac')
Walter Dörwald28256f22003-01-19 16:59:20 +0000334 # Non surrogate below surrogate value, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000335 self.assertTrue('\u0061' < '\ud800\udc02')
Walter Dörwald28256f22003-01-19 16:59:20 +0000336
337 # Non surrogate above surrogate value, fixup required
338 def test_lecmp(s, s2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000339 self.assertTrue(s < s2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000340
341 def test_fixup(s):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000342 s2 = '\ud800\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000343 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000344 s2 = '\ud900\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000345 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000346 s2 = '\uda00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000347 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000348 s2 = '\udb00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000349 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000350 s2 = '\ud800\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000351 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000352 s2 = '\ud900\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000353 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000354 s2 = '\uda00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000355 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000356 s2 = '\udb00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000357 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000358 s2 = '\ud800\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000359 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000360 s2 = '\ud900\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000361 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000362 s2 = '\uda00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000363 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000364 s2 = '\udb00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000365 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000366 s2 = '\ud800\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000367 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000368 s2 = '\ud900\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000369 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000370 s2 = '\uda00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000371 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000372 s2 = '\udb00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000373 test_lecmp(s, s2)
374
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000375 test_fixup('\ue000')
376 test_fixup('\uff61')
Walter Dörwald28256f22003-01-19 16:59:20 +0000377
378 # Surrogates on both sides, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000379 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
Walter Dörwald28256f22003-01-19 16:59:20 +0000380
Walter Dörwald28256f22003-01-19 16:59:20 +0000381 def test_islower(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000382 string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000383 self.checkequalnofix(False, '\u1FFc', 'islower')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500384 self.assertFalse('\u2167'.islower())
385 self.assertTrue('\u2177'.islower())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300386 # non-BMP, uppercase
387 self.assertFalse('\U00010401'.islower())
388 self.assertFalse('\U00010427'.islower())
389 # non-BMP, lowercase
390 self.assertTrue('\U00010429'.islower())
391 self.assertTrue('\U0001044E'.islower())
392 # non-BMP, non-cased
393 self.assertFalse('\U0001F40D'.islower())
394 self.assertFalse('\U0001F46F'.islower())
Walter Dörwald28256f22003-01-19 16:59:20 +0000395
396 def test_isupper(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000397 string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
398 if not sys.platform.startswith('java'):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000399 self.checkequalnofix(False, '\u1FFc', 'isupper')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500400 self.assertTrue('\u2167'.isupper())
401 self.assertFalse('\u2177'.isupper())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300402 # non-BMP, uppercase
403 self.assertTrue('\U00010401'.isupper())
404 self.assertTrue('\U00010427'.isupper())
405 # non-BMP, lowercase
406 self.assertFalse('\U00010429'.isupper())
407 self.assertFalse('\U0001044E'.isupper())
408 # non-BMP, non-cased
409 self.assertFalse('\U0001F40D'.isupper())
410 self.assertFalse('\U0001F46F'.isupper())
Walter Dörwald28256f22003-01-19 16:59:20 +0000411
412 def test_istitle(self):
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300413 string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000414 self.checkequalnofix(True, '\u1FFc', 'istitle')
415 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
Walter Dörwald28256f22003-01-19 16:59:20 +0000416
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300417 # non-BMP, uppercase + lowercase
418 self.assertTrue('\U00010401\U00010429'.istitle())
419 self.assertTrue('\U00010427\U0001044E'.istitle())
420 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
421 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
422 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
423
Walter Dörwald28256f22003-01-19 16:59:20 +0000424 def test_isspace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000425 string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000426 self.checkequalnofix(True, '\u2000', 'isspace')
427 self.checkequalnofix(True, '\u200a', 'isspace')
428 self.checkequalnofix(False, '\u2014', 'isspace')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300429 # apparently there are no non-BMP spaces chars in Unicode 6
430 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
431 '\U0001F40D', '\U0001F46F']:
432 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
433
434 def test_isalnum(self):
435 string_tests.MixinStrUnicodeUserStringTest.test_isalnum(self)
436 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
437 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
438 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
Walter Dörwald28256f22003-01-19 16:59:20 +0000439
440 def test_isalpha(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000441 string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000442 self.checkequalnofix(True, '\u1FFc', 'isalpha')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300443 # non-BMP, cased
444 self.assertTrue('\U00010401'.isalpha())
445 self.assertTrue('\U00010427'.isalpha())
446 self.assertTrue('\U00010429'.isalpha())
447 self.assertTrue('\U0001044E'.isalpha())
448 # non-BMP, non-cased
449 self.assertFalse('\U0001F40D'.isalpha())
450 self.assertFalse('\U0001F46F'.isalpha())
Walter Dörwald28256f22003-01-19 16:59:20 +0000451
452 def test_isdecimal(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000453 self.checkequalnofix(False, '', 'isdecimal')
454 self.checkequalnofix(False, 'a', 'isdecimal')
455 self.checkequalnofix(True, '0', 'isdecimal')
456 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
457 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
458 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
459 self.checkequalnofix(True, '0123456789', 'isdecimal')
460 self.checkequalnofix(False, '0123456789a', 'isdecimal')
Walter Dörwald28256f22003-01-19 16:59:20 +0000461
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000462 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000463
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300464 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
465 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
466 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
467 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
468 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
469
Walter Dörwald28256f22003-01-19 16:59:20 +0000470 def test_isdigit(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000471 string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000472 self.checkequalnofix(True, '\u2460', 'isdigit')
473 self.checkequalnofix(False, '\xbc', 'isdigit')
474 self.checkequalnofix(True, '\u0660', 'isdigit')
Walter Dörwald28256f22003-01-19 16:59:20 +0000475
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300476 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
477 '\U0001F40D', '\U0001F46F', '\U00011065']:
478 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
479 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
480 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
481
Walter Dörwald28256f22003-01-19 16:59:20 +0000482 def test_isnumeric(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000483 self.checkequalnofix(False, '', 'isnumeric')
484 self.checkequalnofix(False, 'a', 'isnumeric')
485 self.checkequalnofix(True, '0', 'isnumeric')
486 self.checkequalnofix(True, '\u2460', 'isnumeric')
487 self.checkequalnofix(True, '\xbc', 'isnumeric')
488 self.checkequalnofix(True, '\u0660', 'isnumeric')
489 self.checkequalnofix(True, '0123456789', 'isnumeric')
490 self.checkequalnofix(False, '0123456789a', 'isnumeric')
Walter Dörwald28256f22003-01-19 16:59:20 +0000491
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000492 self.assertRaises(TypeError, "abc".isnumeric, 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000493
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300494 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
495 '\U0001F40D', '\U0001F46F']:
496 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
497 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
498 '\U000104A0', '\U0001F107']:
499 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
500
Martin v. Löwis47383402007-08-15 07:32:56 +0000501 def test_isidentifier(self):
502 self.assertTrue("a".isidentifier())
503 self.assertTrue("Z".isidentifier())
504 self.assertTrue("_".isidentifier())
505 self.assertTrue("b0".isidentifier())
506 self.assertTrue("bc".isidentifier())
507 self.assertTrue("b_".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000508 self.assertTrue("µ".isidentifier())
Benjamin Petersonf413b802011-08-12 22:17:18 -0500509 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000510
511 self.assertFalse(" ".isidentifier())
512 self.assertFalse("[".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000513 self.assertFalse("©".isidentifier())
Georg Brandld52429f2008-07-04 15:55:02 +0000514 self.assertFalse("0".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000515
Georg Brandl559e5d72008-06-11 18:37:52 +0000516 def test_isprintable(self):
517 self.assertTrue("".isprintable())
Benjamin Peterson09832742009-03-26 17:15:46 +0000518 self.assertTrue(" ".isprintable())
Georg Brandl559e5d72008-06-11 18:37:52 +0000519 self.assertTrue("abcdefg".isprintable())
520 self.assertFalse("abcdefg\n".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000521 # some defined Unicode character
522 self.assertTrue("\u0374".isprintable())
523 # undefined character
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000524 self.assertFalse("\u0378".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000525 # single surrogate character
Georg Brandl559e5d72008-06-11 18:37:52 +0000526 self.assertFalse("\ud800".isprintable())
527
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300528 self.assertTrue('\U0001F46F'.isprintable())
529 self.assertFalse('\U000E0020'.isprintable())
530
531 def test_surrogates(self):
532 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
533 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
534 self.assertTrue(s.islower())
535 self.assertFalse(s.isupper())
536 self.assertFalse(s.istitle())
537 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
538 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
539 self.assertFalse(s.islower())
540 self.assertTrue(s.isupper())
541 self.assertTrue(s.istitle())
542
543 for meth_name in ('islower', 'isupper', 'istitle'):
544 meth = getattr(str, meth_name)
545 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
546 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
547
548 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
549 'isdecimal', 'isnumeric',
550 'isidentifier', 'isprintable'):
551 meth = getattr(str, meth_name)
552 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
553 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
554 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
555 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
556
557
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300558 def test_lower(self):
559 string_tests.CommonTest.test_lower(self)
560 self.assertEqual('\U00010427'.lower(), '\U0001044F')
561 self.assertEqual('\U00010427\U00010427'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300562 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300563 self.assertEqual('\U00010427\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300564 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300565 self.assertEqual('X\U00010427x\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300566 'x\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500567 self.assertEqual('fi'.lower(), 'fi')
568 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
569 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
570 self.assertEqual('\u03a3'.lower(), '\u03c3')
571 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
572 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
573 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
574 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
575 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
576 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
577 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
578 self.assertEqual('\u2177'.lower(), '\u2177')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300579
Benjamin Petersond5890c82012-01-14 13:23:30 -0500580 def test_casefold(self):
581 self.assertEqual('hello'.casefold(), 'hello')
582 self.assertEqual('hELlo'.casefold(), 'hello')
583 self.assertEqual('ß'.casefold(), 'ss')
584 self.assertEqual('fi'.casefold(), 'fi')
585 self.assertEqual('\u03a3'.casefold(), '\u03c3')
586 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
Benjamin Peterson4eda9372012-08-05 15:05:34 -0700587 self.assertEqual('\u00b5'.casefold(), '\u03bc')
Benjamin Petersond5890c82012-01-14 13:23:30 -0500588
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300589 def test_upper(self):
590 string_tests.CommonTest.test_upper(self)
591 self.assertEqual('\U0001044F'.upper(), '\U00010427')
592 self.assertEqual('\U0001044F\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300593 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300594 self.assertEqual('\U00010427\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300595 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300596 self.assertEqual('X\U00010427x\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300597 'X\U00010427X\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500598 self.assertEqual('fi'.upper(), 'FI')
599 self.assertEqual('\u0130'.upper(), '\u0130')
600 self.assertEqual('\u03a3'.upper(), '\u03a3')
601 self.assertEqual('ß'.upper(), 'SS')
602 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
603 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
604 self.assertEqual('\u2177'.upper(), '\u2167')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300605
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300606 def test_capitalize(self):
607 string_tests.CommonTest.test_capitalize(self)
608 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
609 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300610 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300611 self.assertEqual('\U00010427\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300612 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300613 self.assertEqual('\U0001044F\U00010427'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300614 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300615 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300616 'X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500617 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
618 exp = '\u0399\u0308\u0300\u0069\u0307'
619 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
620 self.assertEqual('finnish'.capitalize(), 'FInnish')
621 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300622
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300623 def test_title(self):
624 string_tests.MixinStrUnicodeUserStringTest.test_title(self)
625 self.assertEqual('\U0001044F'.title(), '\U00010427')
626 self.assertEqual('\U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300627 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300628 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300629 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300630 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300631 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300632 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300633 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300634 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300635 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500636 self.assertEqual('fiNNISH'.title(), 'Finnish')
637 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
638 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300639
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300640 def test_swapcase(self):
641 string_tests.CommonTest.test_swapcase(self)
642 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
643 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
644 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300645 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300646 self.assertEqual('\U00010427\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300647 '\U0001044F\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300648 self.assertEqual('\U0001044F\U00010427'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300649 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300650 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300651 'x\U0001044FX\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500652 self.assertEqual('fi'.swapcase(), 'FI')
653 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
654 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
655 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
656 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
657 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
658 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
659 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
660 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
661 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
662 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
663 self.assertEqual('ß'.swapcase(), 'SS')
664 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300665
Ezio Melottif84e01d2013-07-08 17:48:29 +0200666 def test_center(self):
667 string_tests.CommonTest.test_center(self)
668 self.assertEqual('x'.center(2, '\U0010FFFF'),
669 'x\U0010FFFF')
670 self.assertEqual('x'.center(3, '\U0010FFFF'),
671 '\U0010FFFFx\U0010FFFF')
672 self.assertEqual('x'.center(4, '\U0010FFFF'),
673 '\U0010FFFFx\U0010FFFF\U0010FFFF')
674
Walter Dörwald28256f22003-01-19 16:59:20 +0000675 def test_contains(self):
676 # Testing Unicode contains method
Benjamin Peterson577473f2010-01-19 00:09:57 +0000677 self.assertIn('a', 'abdb')
678 self.assertIn('a', 'bdab')
679 self.assertIn('a', 'bdaba')
680 self.assertIn('a', 'bdba')
681 self.assertNotIn('a', 'bdb')
682 self.assertIn('a', 'bdba')
683 self.assertIn('a', ('a',1,None))
684 self.assertIn('a', (1,None,'a'))
685 self.assertIn('a', ('a',1,None))
686 self.assertIn('a', (1,None,'a'))
687 self.assertNotIn('a', ('x',1,'y'))
688 self.assertNotIn('a', ('x',1,None))
689 self.assertNotIn('abcd', 'abcxxxx')
690 self.assertIn('ab', 'abcd')
691 self.assertIn('ab', 'abc')
692 self.assertIn('ab', (1,None,'ab'))
693 self.assertIn('', 'abc')
694 self.assertIn('', '')
695 self.assertIn('', 'abc')
696 self.assertNotIn('\0', 'abc')
697 self.assertIn('\0', '\0abc')
698 self.assertIn('\0', 'abc\0')
699 self.assertIn('a', '\0abc')
700 self.assertIn('asdf', 'asdf')
701 self.assertNotIn('asdf', 'asd')
702 self.assertNotIn('asdf', '')
Walter Dörwald28256f22003-01-19 16:59:20 +0000703
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000704 self.assertRaises(TypeError, "abc".__contains__)
Walter Dörwald28256f22003-01-19 16:59:20 +0000705
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +0300706 def test_issue18183(self):
707 '\U00010000\U00100000'.lower()
708 '\U00010000\U00100000'.casefold()
709 '\U00010000\U00100000'.upper()
710 '\U00010000\U00100000'.capitalize()
711 '\U00010000\U00100000'.title()
712 '\U00010000\U00100000'.swapcase()
713 '\U00100000'.center(3, '\U00010000')
714 '\U00100000'.ljust(3, '\U00010000')
715 '\U00100000'.rjust(3, '\U00010000')
716
Eric Smith8c663262007-08-25 02:26:07 +0000717 def test_format(self):
718 self.assertEqual(''.format(), '')
719 self.assertEqual('a'.format(), 'a')
720 self.assertEqual('ab'.format(), 'ab')
721 self.assertEqual('a{{'.format(), 'a{')
722 self.assertEqual('a}}'.format(), 'a}')
723 self.assertEqual('{{b'.format(), '{b')
724 self.assertEqual('}}b'.format(), '}b')
725 self.assertEqual('a{{b'.format(), 'a{b')
726
727 # examples from the PEP:
728 import datetime
729 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
730 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
731 "My name is Fred")
732 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
733 "My name is Fred :-{}")
734
735 d = datetime.date(2007, 8, 18)
736 self.assertEqual("The year is {0.year}".format(d),
737 "The year is 2007")
738
Eric Smith8c663262007-08-25 02:26:07 +0000739 # classes we'll use for testing
740 class C:
741 def __init__(self, x=100):
742 self._x = x
743 def __format__(self, spec):
744 return spec
745
746 class D:
747 def __init__(self, x):
748 self.x = x
749 def __format__(self, spec):
750 return str(self.x)
751
752 # class with __str__, but no __format__
753 class E:
754 def __init__(self, x):
755 self.x = x
756 def __str__(self):
757 return 'E(' + self.x + ')'
758
759 # class with __repr__, but no __format__ or __str__
760 class F:
761 def __init__(self, x):
762 self.x = x
763 def __repr__(self):
764 return 'F(' + self.x + ')'
765
766 # class with __format__ that forwards to string, for some format_spec's
767 class G:
768 def __init__(self, x):
769 self.x = x
770 def __str__(self):
771 return "string is " + self.x
772 def __format__(self, format_spec):
773 if format_spec == 'd':
774 return 'G(' + self.x + ')'
775 return object.__format__(self, format_spec)
776
Eric Smith739e2ad2007-08-27 19:07:22 +0000777 class I(datetime.date):
778 def __format__(self, format_spec):
779 return self.strftime(format_spec)
780
Eric Smith185e30c2007-08-30 22:23:08 +0000781 class J(int):
782 def __format__(self, format_spec):
783 return int.__format__(self * 2, format_spec)
784
Eric Smith8c663262007-08-25 02:26:07 +0000785
786 self.assertEqual(''.format(), '')
787 self.assertEqual('abc'.format(), 'abc')
788 self.assertEqual('{0}'.format('abc'), 'abc')
789 self.assertEqual('{0:}'.format('abc'), 'abc')
790# self.assertEqual('{ 0 }'.format('abc'), 'abc')
791 self.assertEqual('X{0}'.format('abc'), 'Xabc')
792 self.assertEqual('{0}X'.format('abc'), 'abcX')
793 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
794 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
795 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
796 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
797 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
798 self.assertEqual('{0}'.format(-15), '-15')
799 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
800 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
801 self.assertEqual('{{'.format(), '{')
802 self.assertEqual('}}'.format(), '}')
803 self.assertEqual('{{}}'.format(), '{}')
804 self.assertEqual('{{x}}'.format(), '{x}')
805 self.assertEqual('{{{0}}}'.format(123), '{123}')
806 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
807 self.assertEqual('}}{{'.format(), '}{')
808 self.assertEqual('}}x{{'.format(), '}x{')
809
Eric Smith7ade6482007-08-26 22:27:13 +0000810 # weird field names
811 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
812 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
Eric Smith4cb4e4e2007-09-03 08:40:29 +0000813 self.assertEqual("{0[ ]}".format({' ':3}), '3')
Eric Smith7ade6482007-08-26 22:27:13 +0000814
Eric Smith8c663262007-08-25 02:26:07 +0000815 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
816 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
817 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
818 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
819 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
820 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
821 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
822
Eric Smith8c663262007-08-25 02:26:07 +0000823 # strings
824 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
825 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
826 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
827 self.assertEqual('{0:.0s}'.format('abcdef'), '')
828 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
829 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
830 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
831 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
832 self.assertEqual('{0:x<0s}'.format('result'), 'result')
833 self.assertEqual('{0:x<5s}'.format('result'), 'result')
834 self.assertEqual('{0:x<6s}'.format('result'), 'result')
835 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
836 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
837 self.assertEqual('{0: <7s}'.format('result'), 'result ')
838 self.assertEqual('{0:<7s}'.format('result'), 'result ')
839 self.assertEqual('{0:>7s}'.format('result'), ' result')
840 self.assertEqual('{0:>8s}'.format('result'), ' result')
841 self.assertEqual('{0:^8s}'.format('result'), ' result ')
842 self.assertEqual('{0:^9s}'.format('result'), ' result ')
843 self.assertEqual('{0:^10s}'.format('result'), ' result ')
844 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
845 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
846 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
847
Eric V. Smith2ea97122014-04-14 11:55:10 -0400848 # issue 12546: use \x00 as a fill character
849 self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
850 self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
851 self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
852 self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
853
854 self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
855 self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
856 self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
857 self.assertEqual('{0:<6}'.format(3), '3 ')
858
859 self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
860 self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
861 self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
862 self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
863
864 self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
865 self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
866 self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
867 self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
868
Eric Smith8c663262007-08-25 02:26:07 +0000869 # format specifiers for user defined type
870 self.assertEqual('{0:abc}'.format(C()), 'abc')
871
Georg Brandld52429f2008-07-04 15:55:02 +0000872 # !r, !s and !a coercions
Eric Smith8c663262007-08-25 02:26:07 +0000873 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
874 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
875 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
876 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
877 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
878 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
879 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000880 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +0000881 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
882 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
Georg Brandl559e5d72008-06-11 18:37:52 +0000883 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000884 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +0000885 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
Georg Brandl559e5d72008-06-11 18:37:52 +0000886 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
887 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
Georg Brandld52429f2008-07-04 15:55:02 +0000888 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
Eric Smith8c663262007-08-25 02:26:07 +0000889
Eric Smith8c663262007-08-25 02:26:07 +0000890 # test fallback to object.__format__
891 self.assertEqual('{0}'.format({}), '{}')
892 self.assertEqual('{0}'.format([]), '[]')
893 self.assertEqual('{0}'.format([1]), '[1]')
Eric Smithe4d63172010-09-13 20:48:43 +0000894
Eric Smith8c663262007-08-25 02:26:07 +0000895 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
Eric Smith8c663262007-08-25 02:26:07 +0000896 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
897
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +0200898 self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
899 self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
900 self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
Eric Smithe4d63172010-09-13 20:48:43 +0000901
Eric Smith739e2ad2007-08-27 19:07:22 +0000902 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
903 month=8,
904 day=27)),
905 "date: 2007-08-27")
906
Eric Smith185e30c2007-08-30 22:23:08 +0000907 # test deriving from a builtin type and overriding __format__
908 self.assertEqual("{0}".format(J(10)), "20")
909
910
Eric Smith8c663262007-08-25 02:26:07 +0000911 # string format specifiers
912 self.assertEqual('{0:}'.format('a'), 'a')
913
914 # computed format specifiers
915 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
916 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
917 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
918 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
919 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
920
921 # test various errors
922 self.assertRaises(ValueError, '{'.format)
923 self.assertRaises(ValueError, '}'.format)
924 self.assertRaises(ValueError, 'a{'.format)
925 self.assertRaises(ValueError, 'a}'.format)
926 self.assertRaises(ValueError, '{a'.format)
927 self.assertRaises(ValueError, '}a'.format)
Eric Smith11529192007-09-04 23:04:22 +0000928 self.assertRaises(IndexError, '{0}'.format)
929 self.assertRaises(IndexError, '{1}'.format, 'abc')
930 self.assertRaises(KeyError, '{x}'.format)
Eric Smith8c663262007-08-25 02:26:07 +0000931 self.assertRaises(ValueError, "}{".format)
Eric Smith8c663262007-08-25 02:26:07 +0000932 self.assertRaises(ValueError, "abc{0:{}".format)
933 self.assertRaises(ValueError, "{0".format)
Eric Smith11529192007-09-04 23:04:22 +0000934 self.assertRaises(IndexError, "{0.}".format)
935 self.assertRaises(ValueError, "{0.}".format, 0)
Benjamin Peterson4d944742013-05-17 18:22:31 -0500936 self.assertRaises(ValueError, "{0[}".format)
Eric Smith4cb4e4e2007-09-03 08:40:29 +0000937 self.assertRaises(ValueError, "{0[}".format, [])
Eric Smith11529192007-09-04 23:04:22 +0000938 self.assertRaises(KeyError, "{0]}".format)
939 self.assertRaises(ValueError, "{0.[]}".format, 0)
Eric Smith7ade6482007-08-26 22:27:13 +0000940 self.assertRaises(ValueError, "{0..foo}".format, 0)
Eric Smith11529192007-09-04 23:04:22 +0000941 self.assertRaises(ValueError, "{0[0}".format, 0)
942 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
943 self.assertRaises(KeyError, "{c]}".format)
944 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
945 self.assertRaises(ValueError, "{0}}".format, 0)
946 self.assertRaises(KeyError, "{foo}".format, bar=3)
Eric Smith8c663262007-08-25 02:26:07 +0000947 self.assertRaises(ValueError, "{0!x}".format, 3)
Eric Smith11529192007-09-04 23:04:22 +0000948 self.assertRaises(ValueError, "{0!}".format, 0)
949 self.assertRaises(ValueError, "{0!rs}".format, 0)
Eric Smith8c663262007-08-25 02:26:07 +0000950 self.assertRaises(ValueError, "{!}".format)
Eric Smith8ec90442009-03-14 12:29:34 +0000951 self.assertRaises(IndexError, "{:}".format)
952 self.assertRaises(IndexError, "{:s}".format)
953 self.assertRaises(IndexError, "{}".format)
Benjamin Peterson59a1b2f2010-06-07 22:31:26 +0000954 big = "23098475029384702983476098230754973209482573"
955 self.assertRaises(ValueError, ("{" + big + "}").format)
956 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
Eric Smith8c663262007-08-25 02:26:07 +0000957
Eric Smith41669ca2009-05-23 14:23:22 +0000958 # issue 6089
959 self.assertRaises(ValueError, "{0[0]x}".format, [None])
960 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
961
Eric Smith8c663262007-08-25 02:26:07 +0000962 # can't have a replacement on the field name portion
963 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
964
965 # exceed maximum recursion depth
966 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
967 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
968 0, 1, 2, 3, 4, 5, 6, 7)
969
970 # string format spec errors
971 self.assertRaises(ValueError, "{0:-s}".format, '')
972 self.assertRaises(ValueError, format, "", "-")
973 self.assertRaises(ValueError, "{0:=s}".format, '')
974
Eric Smithb1ebcc62008-07-15 13:02:41 +0000975 # Alternate formatting is not supported
976 self.assertRaises(ValueError, format, '', '#')
977 self.assertRaises(ValueError, format, '', '#20')
978
Victor Stinnerece58de2012-04-23 23:36:38 +0200979 # Non-ASCII
980 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
981 'ABC\u0410\u0411\u0412')
982 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
983 'ABC')
984 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
985 '')
986
Benjamin Petersond2b58a92013-05-17 17:34:30 -0500987 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
Benjamin Peterson4d944742013-05-17 18:22:31 -0500988 self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
989 self.assertEqual("{[{]}".format({"{" : "a"}), "a")
990 self.assertEqual("{[}]}".format({"}" : "a"}), "a")
991 self.assertEqual("{[[]}".format({"[" : "a"}), "a")
992 self.assertEqual("{[!]}".format({"!" : "a"}), "a")
993 self.assertRaises(ValueError, "{a{}b}".format, 42)
994 self.assertRaises(ValueError, "{a{b}".format, 42)
995 self.assertRaises(ValueError, "{[}".format, 42)
Benjamin Petersond2b58a92013-05-17 17:34:30 -0500996
Benjamin Peterson0ee22bf2013-11-26 19:22:36 -0600997 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
Benjamin Petersond2b58a92013-05-17 17:34:30 -0500998
Eric Smith27bbca62010-11-04 17:06:58 +0000999 def test_format_map(self):
1000 self.assertEqual(''.format_map({}), '')
1001 self.assertEqual('a'.format_map({}), 'a')
1002 self.assertEqual('ab'.format_map({}), 'ab')
1003 self.assertEqual('a{{'.format_map({}), 'a{')
1004 self.assertEqual('a}}'.format_map({}), 'a}')
1005 self.assertEqual('{{b'.format_map({}), '{b')
1006 self.assertEqual('}}b'.format_map({}), '}b')
1007 self.assertEqual('a{{b'.format_map({}), 'a{b')
1008
1009 # using mappings
1010 class Mapping(dict):
1011 def __missing__(self, key):
1012 return key
1013 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
1014 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
1015
1016 class InternalMapping:
1017 def __init__(self):
1018 self.mapping = {'a': 'hello'}
1019 def __getitem__(self, key):
1020 return self.mapping[key]
1021 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
1022
1023
Eric Smith27bbca62010-11-04 17:06:58 +00001024 class C:
1025 def __init__(self, x=100):
1026 self._x = x
1027 def __format__(self, spec):
1028 return spec
Eric Smith27bbca62010-11-04 17:06:58 +00001029 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
1030
1031 # test various errors
Eric V. Smithedbb6ca2012-03-12 15:16:22 -07001032 self.assertRaises(TypeError, ''.format_map)
1033 self.assertRaises(TypeError, 'a'.format_map)
1034
1035 self.assertRaises(ValueError, '{'.format_map, {})
1036 self.assertRaises(ValueError, '}'.format_map, {})
1037 self.assertRaises(ValueError, 'a{'.format_map, {})
1038 self.assertRaises(ValueError, 'a}'.format_map, {})
1039 self.assertRaises(ValueError, '{a'.format_map, {})
1040 self.assertRaises(ValueError, '}a'.format_map, {})
Eric Smith27bbca62010-11-04 17:06:58 +00001041
Eric V. Smith12ebefc2011-07-18 14:03:41 -04001042 # issue #12579: can't supply positional params to format_map
1043 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1044 self.assertRaises(ValueError, '{}'.format_map, 'a')
1045 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1046
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001047 def test_format_huge_precision(self):
1048 format_string = ".{}f".format(sys.maxsize + 1)
1049 with self.assertRaises(ValueError):
1050 result = format(2.34, format_string)
1051
1052 def test_format_huge_width(self):
1053 format_string = "{}f".format(sys.maxsize + 1)
1054 with self.assertRaises(ValueError):
1055 result = format(2.34, format_string)
1056
1057 def test_format_huge_item_number(self):
1058 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1059 with self.assertRaises(ValueError):
1060 result = format_string.format(2.34)
1061
Eric Smith8ec90442009-03-14 12:29:34 +00001062 def test_format_auto_numbering(self):
1063 class C:
1064 def __init__(self, x=100):
1065 self._x = x
1066 def __format__(self, spec):
1067 return spec
1068
1069 self.assertEqual('{}'.format(10), '10')
1070 self.assertEqual('{:5}'.format('s'), 's ')
1071 self.assertEqual('{!r}'.format('s'), "'s'")
1072 self.assertEqual('{._x}'.format(C(10)), '10')
1073 self.assertEqual('{[1]}'.format([1, 2]), '2')
1074 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1075 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1076
1077 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1078 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1079
1080 # can't mix and match numbering and auto-numbering
1081 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1082 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1083 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1084 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1085
1086 # can mix and match auto-numbering and named
1087 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1088 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1089 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1090 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1091
Walter Dörwald28256f22003-01-19 16:59:20 +00001092 def test_formatting(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001093 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
Walter Dörwald28256f22003-01-19 16:59:20 +00001094 # Testing Unicode formatting strings...
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001095 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1096 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1097 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1098 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1099 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1100 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 +00001101 if not sys.platform.startswith('java'):
Walter Dörwald67e83882007-05-05 12:26:27 +00001102 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
Georg Brandl559e5d72008-06-11 18:37:52 +00001103 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1104 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001105 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1106 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
Walter Dörwald56fbcb52003-03-31 18:18:41 +00001107
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001108 self.assertEqual('%c' % 0x1234, '\u1234')
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00001109 self.assertEqual('%c' % 0x21483, '\U00021483')
1110 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1111 self.assertEqual('%c' % '\U00021483', '\U00021483')
1112 self.assertRaises(TypeError, "%c".__mod__, "aa")
Stefan Krah99212f62010-07-19 17:58:26 +00001113 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07001114 self.assertRaises(TypeError, "%i".__mod__, "aa")
Walter Dörwald28256f22003-01-19 16:59:20 +00001115
1116 # formatting jobs delegated from the string implementation:
Walter Dörwald28256f22003-01-19 16:59:20 +00001117 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001118 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1119 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1120 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1121 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1122 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1123 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1124 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1125 self.assertEqual('...%s...' % "abc", '...abc...')
1126 self.assertEqual('%*s' % (5,'abc',), ' abc')
1127 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1128 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1129 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1130 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1131 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1132 self.assertEqual('%c' % 'a', 'a')
Neil Schemenauercf52c072005-08-12 17:34:58 +00001133 class Wrapper:
1134 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001135 return '\u1234'
1136 self.assertEqual('%s' % Wrapper(), '\u1234')
Walter Dörwald28256f22003-01-19 16:59:20 +00001137
Eric Smith741191f2009-05-06 13:08:15 +00001138 # issue 3382
1139 NAN = float('nan')
1140 INF = float('inf')
1141 self.assertEqual('%f' % NAN, 'nan')
1142 self.assertEqual('%F' % NAN, 'NAN')
1143 self.assertEqual('%f' % INF, 'inf')
1144 self.assertEqual('%F' % INF, 'INF')
1145
Victor Stinnerf59c28c2012-05-09 03:24:14 +02001146 # PEP 393
1147 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1148 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1149
Ethan Furmandf3ed242014-01-05 06:50:30 -08001150 #issue 19995
1151 class PsuedoInt:
1152 def __init__(self, value):
1153 self.value = int(value)
1154 def __int__(self):
1155 return self.value
1156 def __index__(self):
1157 return self.value
1158 class PsuedoFloat:
1159 def __init__(self, value):
1160 self.value = float(value)
1161 def __int__(self):
1162 return int(self.value)
1163 pi = PsuedoFloat(3.1415)
1164 letter_m = PsuedoInt(109)
Antoine Pitroueb168042014-01-10 00:02:38 +01001165 self.assertEqual('%x' % 42, '2a')
1166 self.assertEqual('%X' % 15, 'F')
1167 self.assertEqual('%o' % 9, '11')
1168 self.assertEqual('%c' % 109, 'm')
1169 self.assertEqual('%x' % letter_m, '6d')
1170 self.assertEqual('%X' % letter_m, '6D')
1171 self.assertEqual('%o' % letter_m, '155')
1172 self.assertEqual('%c' % letter_m, 'm')
Ethan Furmana70805e2014-01-12 08:42:35 -08001173 self.assertWarns(DeprecationWarning, '%x'.__mod__, pi),
1174 self.assertWarns(DeprecationWarning, '%x'.__mod__, 3.14),
1175 self.assertWarns(DeprecationWarning, '%X'.__mod__, 2.11),
1176 self.assertWarns(DeprecationWarning, '%o'.__mod__, 1.79),
1177 self.assertWarns(DeprecationWarning, '%c'.__mod__, pi),
Ethan Furmandf3ed242014-01-05 06:50:30 -08001178
Ethan Furmanfb137212013-08-31 10:18:55 -07001179 def test_formatting_with_enum(self):
1180 # issue18780
1181 import enum
1182 class Float(float, enum.Enum):
1183 PI = 3.1415926
1184 class Int(enum.IntEnum):
1185 IDES = 15
1186 class Str(str, enum.Enum):
1187 ABC = 'abc'
1188 # Testing Unicode formatting strings...
Ethan Furman13bdfa72013-08-31 12:48:51 -07001189 self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
1190 'Str.ABC, Str.ABC')
1191 self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
1192 (Str.ABC, Str.ABC,
1193 Int.IDES, Int.IDES, Int.IDES,
1194 Float.PI, Float.PI),
1195 'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14')
Ethan Furmanfb137212013-08-31 10:18:55 -07001196
1197 # formatting jobs delegated from the string implementation:
Ethan Furman13bdfa72013-08-31 12:48:51 -07001198 self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
1199 '...Str.ABC...')
1200 self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
1201 '...Int.IDES...')
1202 self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
1203 '...15...')
1204 self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
1205 '...15...')
1206 self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
1207 '...15...')
1208 self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
1209 '...3.141593...')
Ethan Furmanfb137212013-08-31 10:18:55 -07001210
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001211 def test_formatting_huge_precision(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001212 format_string = "%.{}f".format(sys.maxsize + 1)
1213 with self.assertRaises(ValueError):
1214 result = format_string % 2.34
1215
1216 @support.cpython_only
1217 def test_formatting_huge_precision_c_limits(self):
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001218 from _testcapi import INT_MAX
1219 format_string = "%.{}f".format(INT_MAX + 1)
1220 with self.assertRaises(ValueError):
1221 result = format_string % 2.34
1222
1223 def test_formatting_huge_width(self):
1224 format_string = "%{}f".format(sys.maxsize + 1)
1225 with self.assertRaises(ValueError):
1226 result = format_string % 2.34
1227
Ezio Melottiba42fd52011-04-26 06:09:45 +03001228 def test_startswith_endswith_errors(self):
1229 for meth in ('foo'.startswith, 'foo'.endswith):
Ezio Melottif2b3f782011-04-26 06:40:59 +03001230 with self.assertRaises(TypeError) as cm:
Ezio Melottiba42fd52011-04-26 06:09:45 +03001231 meth(['f'])
Ezio Melottif2b3f782011-04-26 06:40:59 +03001232 exc = str(cm.exception)
Ezio Melottiba42fd52011-04-26 06:09:45 +03001233 self.assertIn('str', exc)
1234 self.assertIn('tuple', exc)
1235
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001236 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
Georg Brandlda6b1072006-01-20 17:48:54 +00001237 def test_format_float(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001238 # should not format with a comma, but always with C locale
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001239 self.assertEqual('1.0', '%.1f' % 1.0)
Georg Brandlda6b1072006-01-20 17:48:54 +00001240
Walter Dörwald28256f22003-01-19 16:59:20 +00001241 def test_constructor(self):
1242 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1243
1244 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001245 str('unicode remains unicode'),
1246 'unicode remains unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001247 )
1248
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001249 class UnicodeSubclass(str):
Marc-André Lemburg79f57832002-12-29 19:44:06 +00001250 pass
Guido van Rossuma831cac2000-03-10 23:23:21 +00001251
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001252 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
1253 subclass = UnicodeSubclass(text)
1254 self.assertEqual(str(subclass), text)
1255 self.assertEqual(len(subclass), len(text))
1256 if text == 'ascii':
1257 self.assertEqual(subclass.encode('ascii'), b'ascii')
1258 self.assertEqual(subclass.encode('utf-8'), b'ascii')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001259
Walter Dörwald28256f22003-01-19 16:59:20 +00001260 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001261 str('strings are converted to unicode'),
1262 'strings are converted to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001263 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001264
Walter Dörwald28256f22003-01-19 16:59:20 +00001265 class StringCompat:
1266 def __init__(self, x):
1267 self.x = x
1268 def __str__(self):
1269 return self.x
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001270
Walter Dörwald28256f22003-01-19 16:59:20 +00001271 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001272 str(StringCompat('__str__ compatible objects are recognized')),
1273 '__str__ compatible objects are recognized'
Walter Dörwald28256f22003-01-19 16:59:20 +00001274 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001275
Walter Dörwald28256f22003-01-19 16:59:20 +00001276 # unicode(obj) is compatible to str():
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001277
Walter Dörwald28256f22003-01-19 16:59:20 +00001278 o = StringCompat('unicode(obj) is compatible to str()')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001279 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Walter Dörwald28256f22003-01-19 16:59:20 +00001280 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001281
Guido van Rossume2a383d2007-01-15 16:59:06 +00001282 for obj in (123, 123.45, 123):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001283 self.assertEqual(str(obj), str(str(obj)))
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001284
Walter Dörwald28256f22003-01-19 16:59:20 +00001285 # unicode(obj, encoding, error) tests (this maps to
1286 # PyUnicode_FromEncodedObject() at C level)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001287
Walter Dörwald28256f22003-01-19 16:59:20 +00001288 if not sys.platform.startswith('java'):
1289 self.assertRaises(
1290 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001291 str,
1292 'decoding unicode is not supported',
Walter Dörwald28256f22003-01-19 16:59:20 +00001293 'utf-8',
1294 'strict'
1295 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001296
Walter Dörwald28256f22003-01-19 16:59:20 +00001297 self.assertEqual(
Walter Dörwald67e83882007-05-05 12:26:27 +00001298 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001299 'strings are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001300 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001301
Walter Dörwald28256f22003-01-19 16:59:20 +00001302 if not sys.platform.startswith('java'):
1303 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001304 str(
Guido van Rossumbae07c92007-10-08 02:46:15 +00001305 memoryview(b'character buffers are decoded to unicode'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001306 'utf-8',
1307 'strict'
1308 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001309 'character buffers are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001310 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001311
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001312 self.assertRaises(TypeError, str, 42, 42, 42)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001313
Chris Jerdonek5fae0e52012-11-20 17:45:51 -08001314 def test_constructor_keyword_args(self):
1315 """Pass various keyword argument combinations to the constructor."""
1316 # The object argument can be passed as a keyword.
1317 self.assertEqual(str(object='foo'), 'foo')
1318 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1319 # The errors argument without encoding triggers "decode" mode.
1320 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1321 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1322
1323 def test_constructor_defaults(self):
1324 """Check the constructor argument defaults."""
1325 # The object argument defaults to '' or b''.
1326 self.assertEqual(str(), '')
1327 self.assertEqual(str(errors='strict'), '')
1328 utf8_cent = '¢'.encode('utf-8')
1329 # The encoding argument defaults to utf-8.
1330 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1331 # The errors argument defaults to strict.
1332 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1333
Walter Dörwald28256f22003-01-19 16:59:20 +00001334 def test_codecs_utf7(self):
1335 utfTests = [
Walter Dörwald67e83882007-05-05 12:26:27 +00001336 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1337 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1338 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1339 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1340 ('+', b'+-'),
1341 ('+-', b'+--'),
1342 ('+?', b'+-?'),
1343 ('\?', b'+AFw?'),
1344 ('+?', b'+-?'),
1345 (r'\\?', b'+AFwAXA?'),
1346 (r'\\\?', b'+AFwAXABc?'),
Antoine Pitrou244651a2009-05-04 18:56:13 +00001347 (r'++--', b'+-+---'),
1348 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1349 ('/', b'/'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001350 ]
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001351
Walter Dörwald28256f22003-01-19 16:59:20 +00001352 for (x, y) in utfTests:
1353 self.assertEqual(x.encode('utf-7'), y)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001354
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001355 # Unpaired surrogates are passed through
1356 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1357 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1358 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1359 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1360 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1361 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1362 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1363 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001364
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001365 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1366 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001367
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001368 # Issue #2242: crash on some Windows/MSVC versions
Antoine Pitrou244651a2009-05-04 18:56:13 +00001369 self.assertEqual(b'+\xc1'.decode('utf-7'), '\xc1')
1370
1371 # Direct encoded characters
1372 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1373 # Optional direct characters
1374 set_o = '!"#$%&*;<=>@[]^_`{|}'
1375 for c in set_d:
1376 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1377 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1378 for c in set_o:
1379 self.assertEqual(c.encode('ascii').decode('utf7'), c)
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001380
Walter Dörwald28256f22003-01-19 16:59:20 +00001381 def test_codecs_utf8(self):
Walter Dörwald67e83882007-05-05 12:26:27 +00001382 self.assertEqual(''.encode('utf-8'), b'')
1383 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001384 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1385 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001386 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1387 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001388 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1389 b'\xf0\x90\x80\x82'*10)
Walter Dörwald28256f22003-01-19 16:59:20 +00001390 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001391 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1392 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1393 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1394 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1395 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1396 ' Nunstuck git und'.encode('utf-8'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001397 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1398 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1399 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1400 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1401 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1402 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1403 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1404 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1405 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1406 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
Walter Dörwald28256f22003-01-19 16:59:20 +00001407 )
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001408
Walter Dörwald28256f22003-01-19 16:59:20 +00001409 # UTF-8 specific decoding tests
Walter Dörwald67e83882007-05-05 12:26:27 +00001410 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1411 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1412 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001413
Walter Dörwald28256f22003-01-19 16:59:20 +00001414 # Other possible utf-8 test cases:
1415 # * strict decoding testing for all of the
1416 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001417
Ezio Melotti57221d02010-07-01 07:32:02 +00001418 def test_utf8_decode_valid_sequences(self):
1419 sequences = [
1420 # single byte
1421 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1422 # 2 bytes
1423 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1424 # 3 bytes
1425 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1426 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1427 # 4 bytes
1428 (b'\xF0\x90\x80\x80', '\U00010000'),
1429 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1430 ]
1431 for seq, res in sequences:
1432 self.assertEqual(seq.decode('utf-8'), res)
1433
1434
1435 def test_utf8_decode_invalid_sequences(self):
1436 # continuation bytes in a sequence of 2, 3, or 4 bytes
1437 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
1438 # start bytes of a 2-byte sequence equivalent to codepoints < 0x7F
1439 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
1440 # start bytes of a 4-byte sequence equivalent to codepoints > 0x10FFFF
1441 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1442 invalid_start_bytes = (
1443 continuation_bytes + invalid_2B_seq_start_bytes +
1444 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1445 )
1446
1447 for byte in invalid_start_bytes:
1448 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1449
1450 for sb in invalid_2B_seq_start_bytes:
1451 for cb in continuation_bytes:
1452 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1453
1454 for sb in invalid_4B_seq_start_bytes:
1455 for cb1 in continuation_bytes[:3]:
1456 for cb3 in continuation_bytes[:3]:
1457 self.assertRaises(UnicodeDecodeError,
1458 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1459
1460 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1461 self.assertRaises(UnicodeDecodeError,
1462 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1463 self.assertRaises(UnicodeDecodeError,
1464 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1465 # surrogates
1466 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1467 self.assertRaises(UnicodeDecodeError,
1468 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1469 self.assertRaises(UnicodeDecodeError,
1470 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1471 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1472 self.assertRaises(UnicodeDecodeError,
1473 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1474 self.assertRaises(UnicodeDecodeError,
1475 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1476 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1477 self.assertRaises(UnicodeDecodeError,
1478 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1479 self.assertRaises(UnicodeDecodeError,
1480 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1481
1482 def test_issue8271(self):
1483 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1484 # only the start byte and the continuation byte(s) are now considered
1485 # invalid, instead of the number of bytes specified by the start byte.
1486 # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
1487 # table 3-8, Row 2) for more information about the algorithm used.
1488 FFFD = '\ufffd'
1489 sequences = [
1490 # invalid start bytes
1491 (b'\x80', FFFD), # continuation byte
1492 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1493 (b'\xc0', FFFD),
1494 (b'\xc0\xc0', FFFD*2),
1495 (b'\xc1', FFFD),
1496 (b'\xc1\xc0', FFFD*2),
1497 (b'\xc0\xc1', FFFD*2),
1498 # with start byte of a 2-byte sequence
1499 (b'\xc2', FFFD), # only the start byte
1500 (b'\xc2\xc2', FFFD*2), # 2 start bytes
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001501 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
Ezio Melotti57221d02010-07-01 07:32:02 +00001502 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1503 # with start byte of a 3-byte sequence
1504 (b'\xe1', FFFD), # only the start byte
1505 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1506 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1507 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1508 (b'\xe1\x80', FFFD), # only 1 continuation byte
1509 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1510 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1511 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1512 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1513 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1514 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1515 # with start byte of a 4-byte sequence
1516 (b'\xf1', FFFD), # only the start byte
1517 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1518 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1519 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1520 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1521 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1522 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1523 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1524 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1525 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1526 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1527 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1528 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1529 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1530 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1531 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1532 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1533 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1534 # with invalid start byte of a 4-byte sequence (rfc2279)
1535 (b'\xf5', FFFD), # only the start byte
1536 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1537 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1538 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1539 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1540 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1541 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1542 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1543 # with invalid start byte of a 5-byte sequence (rfc2279)
1544 (b'\xf8', FFFD), # only the start byte
1545 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1546 (b'\xf8\x80', FFFD*2), # only one continuation byte
1547 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1548 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1549 # with invalid start byte of a 6-byte sequence (rfc2279)
1550 (b'\xfc', FFFD), # only the start byte
1551 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1552 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1553 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
1554 # invalid start byte
1555 (b'\xfe', FFFD),
1556 (b'\xfe\x80\x80', FFFD*3),
1557 # other sequences
1558 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
1559 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
1560 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
1561 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
1562 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
1563 ]
1564 for n, (seq, res) in enumerate(sequences):
1565 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
1566 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1567 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
1568 self.assertEqual(seq.decode('utf-8', 'ignore'),
1569 res.replace('\uFFFD', ''))
1570
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001571 def to_bytestring(self, seq):
1572 return bytes(int(c, 16) for c in seq.split())
1573
1574 def assertCorrectUTF8Decoding(self, seq, res, err):
1575 """
1576 Check that an invalid UTF-8 sequence raises an UnicodeDecodeError when
1577 'strict' is used, returns res when 'replace' is used, and that doesn't
1578 return anything when 'ignore' is used.
1579 """
1580 with self.assertRaises(UnicodeDecodeError) as cm:
1581 seq.decode('utf-8')
1582 exc = cm.exception
1583
1584 self.assertIn(err, str(exc))
1585 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1586 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
1587 'aaaa' + res + 'bbbb')
1588 res = res.replace('\ufffd', '')
1589 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
1590 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
1591 'aaaa' + res + 'bbbb')
1592
1593 def test_invalid_start_byte(self):
1594 """
1595 Test that an 'invalid start byte' error is raised when the first byte
1596 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
1597 4-bytes sequence. The invalid start byte is replaced with a single
1598 U+FFFD when errors='replace'.
1599 E.g. <80> is a continuation byte and can appear only after a start byte.
1600 """
1601 FFFD = '\ufffd'
1602 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
1603 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
1604 'invalid start byte')
1605
1606 def test_unexpected_end_of_data(self):
1607 """
1608 Test that an 'unexpected end of data' error is raised when the string
1609 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
1610 enough continuation bytes. The incomplete sequence is replaced with a
1611 single U+FFFD when errors='replace'.
1612 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
1613 sequence, but it's followed by only 2 valid continuation bytes and the
1614 last continuation bytes is missing.
1615 Note: the continuation bytes must be all valid, if one of them is
1616 invalid another error will be raised.
1617 """
1618 sequences = [
1619 'C2', 'DF',
1620 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
1621 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
1622 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
1623 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
1624 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
1625 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
1626 ]
1627 FFFD = '\ufffd'
1628 for seq in sequences:
1629 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), '\ufffd',
1630 'unexpected end of data')
1631
1632 def test_invalid_cb_for_2bytes_seq(self):
1633 """
1634 Test that an 'invalid continuation byte' error is raised when the
1635 continuation byte of a 2-bytes sequence is invalid. The start byte
1636 is replaced by a single U+FFFD and the second byte is handled
1637 separately when errors='replace'.
1638 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
1639 sequence, but 41 is not a valid continuation byte because it's the
1640 ASCII letter 'A'.
1641 """
1642 FFFD = '\ufffd'
1643 FFFDx2 = FFFD * 2
1644 sequences = [
1645 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
1646 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
1647 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
1648 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
1649 ]
1650 for seq, res in sequences:
1651 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1652 'invalid continuation byte')
1653
1654 def test_invalid_cb_for_3bytes_seq(self):
1655 """
1656 Test that an 'invalid continuation byte' error is raised when the
1657 continuation byte(s) of a 3-bytes sequence are invalid. When
1658 errors='replace', if the first continuation byte is valid, the first
1659 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
1660 third byte is handled separately, otherwise only the start byte is
1661 replaced with a U+FFFD and the other continuation bytes are handled
1662 separately.
1663 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1664 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1665 because it's the ASCII letter 'A'.
1666 Note: when the start byte is E0 or ED, the valid ranges for the first
1667 continuation byte are limited to A0..BF and 80..9F respectively.
1668 Python 2 used to consider all the bytes in range 80..BF valid when the
1669 start byte was ED. This is fixed in Python 3.
1670 """
1671 FFFD = '\ufffd'
1672 FFFDx2 = FFFD * 2
1673 sequences = [
1674 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
1675 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
1676 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
1677 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
1678 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
1679 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
1680 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
1681 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
1682 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
1683 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
1684 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
1685 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
1686 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
1687 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
1688 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
1689 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
1690 ('ED 7F', FFFD+'\x7f'),
1691 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
1692 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
1693 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
1694 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
1695 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
1696 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
1697 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
1698 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
1699 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
1700 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
1701 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
1702 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
1703 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
1704 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
1705 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
1706 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
1707 ]
1708 for seq, res in sequences:
1709 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1710 'invalid continuation byte')
1711
1712 def test_invalid_cb_for_4bytes_seq(self):
1713 """
1714 Test that an 'invalid continuation byte' error is raised when the
1715 continuation byte(s) of a 4-bytes sequence are invalid. When
1716 errors='replace',the start byte and all the following valid
1717 continuation bytes are replaced with a single U+FFFD, and all the bytes
1718 starting from the first invalid continuation bytes (included) are
1719 handled separately.
1720 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1721 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1722 because it's the ASCII letter 'A'.
1723 Note: when the start byte is E0 or ED, the valid ranges for the first
1724 continuation byte are limited to A0..BF and 80..9F respectively.
1725 However, when the start byte is ED, Python 2 considers all the bytes
1726 in range 80..BF valid. This is fixed in Python 3.
1727 """
1728 FFFD = '\ufffd'
1729 FFFDx2 = FFFD * 2
1730 sequences = [
1731 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
1732 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
1733 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
1734 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
1735 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
1736 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
1737 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
1738 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
1739 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
1740 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
1741 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
1742 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
1743 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
1744 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
1745 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
1746 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
1747 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
1748 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
1749 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
1750 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
1751 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
1752 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
1753 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
1754 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
1755 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
1756 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
1757 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
1758 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
1759 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
1760 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
1761 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
1762 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
1763 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
1764 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
1765 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
1766 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
1767 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
1768 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
1769 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
1770 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
1771 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
1772 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
1773 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
1774 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
1775 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
1776 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
1777 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
1778 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
1779 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
1780 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
1781 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
1782 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
1783 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
1784 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
1785 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
1786 ]
1787 for seq, res in sequences:
1788 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1789 'invalid continuation byte')
1790
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001791 def test_codecs_idna(self):
1792 # Test whether trailing dot is preserved
Walter Dörwald1324c6f2007-05-11 19:57:05 +00001793 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001794
Walter Dörwald28256f22003-01-19 16:59:20 +00001795 def test_codecs_errors(self):
1796 # Error handling (encoding)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001797 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
1798 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
Walter Dörwald67e83882007-05-05 12:26:27 +00001799 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
1800 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
Benjamin Peterson308d6372009-09-18 21:42:35 +00001801 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
1802 'Andr\202 x'.encode('ascii', errors='replace'))
1803 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
1804 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001805
Walter Dörwald28256f22003-01-19 16:59:20 +00001806 # Error handling (decoding)
Walter Dörwald67e83882007-05-05 12:26:27 +00001807 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
1808 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
1809 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
1810 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001811
Walter Dörwald28256f22003-01-19 16:59:20 +00001812 # Error handling (unknown character names)
Guido van Rossum39478e82007-08-27 17:23:59 +00001813 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
Marc-André Lemburg3688a882002-02-06 18:09:02 +00001814
Walter Dörwald28256f22003-01-19 16:59:20 +00001815 # Error handling (truncated escape sequence)
Guido van Rossum9c627722007-08-27 18:31:48 +00001816 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001817
Guido van Rossum9c627722007-08-27 18:31:48 +00001818 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
1819 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001820 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
1821 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001822
Walter Dörwald28256f22003-01-19 16:59:20 +00001823 # Error handling (wrong arguments)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001824 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001825
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001826 # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001827 self.assertRaises(UnicodeError, float, "\ud800")
1828 self.assertRaises(UnicodeError, float, "\udf00")
1829 self.assertRaises(UnicodeError, complex, "\ud800")
1830 self.assertRaises(UnicodeError, complex, "\udf00")
Guido van Rossum97064862000-04-10 13:52:48 +00001831
Walter Dörwald28256f22003-01-19 16:59:20 +00001832 def test_codecs(self):
1833 # Encoding
Walter Dörwald67e83882007-05-05 12:26:27 +00001834 self.assertEqual('hello'.encode('ascii'), b'hello')
1835 self.assertEqual('hello'.encode('utf-7'), b'hello')
1836 self.assertEqual('hello'.encode('utf-8'), b'hello')
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001837 self.assertEqual('hello'.encode('utf-8'), b'hello')
Walter Dörwald67e83882007-05-05 12:26:27 +00001838 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
1839 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
1840 self.assertEqual('hello'.encode('latin-1'), b'hello')
Guido van Rossum97064862000-04-10 13:52:48 +00001841
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00001842 # Default encoding is utf-8
1843 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
1844
Walter Dörwald28256f22003-01-19 16:59:20 +00001845 # Roundtrip safety for BMP (just the first 1024 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001846 for c in range(1024):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001847 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001848 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
1849 'utf-16-be', 'raw_unicode_escape',
1850 'unicode_escape', 'unicode_internal'):
Victor Stinner040e16e2011-11-15 22:44:05 +01001851 with warnings.catch_warnings():
1852 # unicode-internal has been deprecated
1853 warnings.simplefilter("ignore", DeprecationWarning)
1854
1855 self.assertEqual(str(u.encode(encoding),encoding), u)
Martin v. Löwis047c05e2002-03-21 08:55:28 +00001856
Walter Dörwald28256f22003-01-19 16:59:20 +00001857 # Roundtrip safety for BMP (just the first 256 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001858 for c in range(256):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001859 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001860 for encoding in ('latin-1',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001861 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001862
Walter Dörwald28256f22003-01-19 16:59:20 +00001863 # Roundtrip safety for BMP (just the first 128 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00001864 for c in range(128):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00001865 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00001866 for encoding in ('ascii',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001867 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001868
Walter Dörwald28256f22003-01-19 16:59:20 +00001869 # Roundtrip safety for non-BMP (just a few chars)
Victor Stinner040e16e2011-11-15 22:44:05 +01001870 with warnings.catch_warnings():
1871 # unicode-internal has been deprecated
1872 warnings.simplefilter("ignore", DeprecationWarning)
1873
1874 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
1875 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
1876 'raw_unicode_escape',
1877 'unicode_escape', 'unicode_internal'):
1878 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001879
Antoine Pitrou51f66482011-11-11 13:35:44 +01001880 # UTF-8 must be roundtrip safe for all code points
1881 # (except surrogates, which are forbidden).
1882 u = ''.join(map(chr, list(range(0, 0xd800)) +
Ezio Melotti40dc9192011-11-11 17:00:46 +02001883 list(range(0xe000, 0x110000))))
Walter Dörwald28256f22003-01-19 16:59:20 +00001884 for encoding in ('utf-8',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001885 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001886
Walter Dörwald28256f22003-01-19 16:59:20 +00001887 def test_codecs_charmap(self):
1888 # 0-127
Guido van Rossum805365e2007-05-07 22:24:25 +00001889 s = bytes(range(128))
Walter Dörwald28256f22003-01-19 16:59:20 +00001890 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05001891 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001892 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
1893 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001894 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00001895 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
1896 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
1897 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
1898 'mac_cyrillic', 'mac_latin2',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00001899
Walter Dörwald28256f22003-01-19 16:59:20 +00001900 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
1901 'cp1256', 'cp1257', 'cp1258',
1902 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00001903
Walter Dörwald28256f22003-01-19 16:59:20 +00001904 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
1905 'cp1006', 'iso8859_8',
Guido van Rossum9e896b32000-04-05 20:11:21 +00001906
Walter Dörwald28256f22003-01-19 16:59:20 +00001907 ### These have undefined mappings:
1908 #'cp424',
Guido van Rossum9e896b32000-04-05 20:11:21 +00001909
Walter Dörwald28256f22003-01-19 16:59:20 +00001910 ### These fail the round-trip:
1911 #'cp875'
Guido van Rossum9e896b32000-04-05 20:11:21 +00001912
Walter Dörwald28256f22003-01-19 16:59:20 +00001913 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001914 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001915
Walter Dörwald28256f22003-01-19 16:59:20 +00001916 # 128-255
Guido van Rossum805365e2007-05-07 22:24:25 +00001917 s = bytes(range(128, 256))
Walter Dörwald28256f22003-01-19 16:59:20 +00001918 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05001919 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00001920 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
1921 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02001922 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00001923 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
1924 'iso8859_2', 'iso8859_4', 'iso8859_5',
1925 'iso8859_9', 'koi8_r', 'latin_1',
1926 'mac_cyrillic', 'mac_latin2',
Fred Drake004d5e62000-10-23 17:22:08 +00001927
Walter Dörwald28256f22003-01-19 16:59:20 +00001928 ### These have undefined mappings:
1929 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
1930 #'cp1256', 'cp1257', 'cp1258',
1931 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
1932 #'iso8859_3', 'iso8859_6', 'iso8859_7',
1933 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
Fred Drake004d5e62000-10-23 17:22:08 +00001934
Walter Dörwald28256f22003-01-19 16:59:20 +00001935 ### These fail the round-trip:
1936 #'cp1006', 'cp875', 'iso8859_8',
Tim Peters2f228e72001-05-13 00:19:31 +00001937
Walter Dörwald28256f22003-01-19 16:59:20 +00001938 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001939 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00001940
Walter Dörwald28256f22003-01-19 16:59:20 +00001941 def test_concatenation(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001942 self.assertEqual(("abc" "def"), "abcdef")
1943 self.assertEqual(("abc" "def"), "abcdef")
1944 self.assertEqual(("abc" "def"), "abcdef")
1945 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
1946 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
Fred Drake004d5e62000-10-23 17:22:08 +00001947
Walter Dörwald28256f22003-01-19 16:59:20 +00001948 def test_printing(self):
1949 class BitBucket:
1950 def write(self, text):
1951 pass
Fred Drake004d5e62000-10-23 17:22:08 +00001952
Walter Dörwald28256f22003-01-19 16:59:20 +00001953 out = BitBucket()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001954 print('abc', file=out)
1955 print('abc', 'def', file=out)
1956 print('abc', 'def', file=out)
1957 print('abc', 'def', file=out)
1958 print('abc\n', file=out)
1959 print('abc\n', end=' ', file=out)
1960 print('abc\n', end=' ', file=out)
1961 print('def\n', file=out)
1962 print('def\n', file=out)
Fred Drake004d5e62000-10-23 17:22:08 +00001963
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00001964 def test_ucs4(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001965 x = '\U00100000'
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00001966 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
1967 self.assertEqual(x, y)
1968
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001969 y = br'\U00100000'
1970 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
1971 self.assertEqual(x, y)
1972 y = br'\U00010000'
1973 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
1974 self.assertEqual(x, y)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001975
Florent Xiclunaa87b3832010-09-13 02:28:18 +00001976 try:
1977 br'\U11111111'.decode("raw-unicode-escape")
1978 except UnicodeDecodeError as e:
1979 self.assertEqual(e.start, 0)
1980 self.assertEqual(e.end, 10)
1981 else:
1982 self.fail("Should have raised UnicodeDecodeError")
Christian Heimesfe337bf2008-03-23 21:54:12 +00001983
Brett Cannonc3647ac2005-04-26 03:45:26 +00001984 def test_conversion(self):
1985 # Make sure __unicode__() works properly
1986 class Foo0:
1987 def __str__(self):
1988 return "foo"
1989
1990 class Foo1:
Guido van Rossum98297ee2007-11-06 21:34:58 +00001991 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001992 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001993
1994 class Foo2(object):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001995 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001996 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00001997
1998 class Foo3(object):
Guido van Rossum98297ee2007-11-06 21:34:58 +00001999 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002000 return "foo"
2001
2002 class Foo4(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00002003 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002004 return "foo"
2005
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002006 class Foo5(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00002007 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002008 return "foo"
2009
2010 class Foo6(str):
2011 def __str__(self):
2012 return "foos"
2013
Guido van Rossum98297ee2007-11-06 21:34:58 +00002014 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002015 return "foou"
Brett Cannonc3647ac2005-04-26 03:45:26 +00002016
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002017 class Foo7(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002018 def __str__(self):
2019 return "foos"
Guido van Rossum98297ee2007-11-06 21:34:58 +00002020 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002021 return "foou"
Brett Cannonc3647ac2005-04-26 03:45:26 +00002022
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002023 class Foo8(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002024 def __new__(cls, content=""):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002025 return str.__new__(cls, 2*content)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002026 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002027 return self
2028
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002029 class Foo9(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002030 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002031 return "not unicode"
2032
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002033 self.assertEqual(str(Foo0()), "foo")
2034 self.assertEqual(str(Foo1()), "foo")
2035 self.assertEqual(str(Foo2()), "foo")
2036 self.assertEqual(str(Foo3()), "foo")
2037 self.assertEqual(str(Foo4("bar")), "foo")
2038 self.assertEqual(str(Foo5("bar")), "foo")
2039 self.assertEqual(str(Foo6("bar")), "foou")
2040 self.assertEqual(str(Foo7("bar")), "foou")
2041 self.assertEqual(str(Foo8("foo")), "foofoo")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002042 self.assertEqual(str(Foo9("foo")), "not unicode")
Brett Cannonc3647ac2005-04-26 03:45:26 +00002043
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002044 def test_unicode_repr(self):
2045 class s1:
2046 def __repr__(self):
2047 return '\\n'
2048
2049 class s2:
2050 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002051 return '\\n'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002052
2053 self.assertEqual(repr(s1()), '\\n')
2054 self.assertEqual(repr(s2()), '\\n')
2055
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002056 def test_printable_repr(self):
2057 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
Martin v. Löwisbaecd722010-10-11 22:42:28 +00002058 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002059
Zachary Ware9fe6d862013-12-08 00:20:35 -06002060 # This test only affects 32-bit platforms because expandtabs can only take
2061 # an int as the max value, not a 64-bit C long. If expandtabs is changed
2062 # to take a 64-bit long, this test should apply to all platforms.
2063 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
2064 'only applies to 32-bit platforms')
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002065 def test_expandtabs_overflows_gracefully(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +00002066 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002067
Victor Stinner1d972ad2011-10-07 13:31:46 +02002068 @support.cpython_only
Antoine Pitroue19aa382011-10-04 16:04:01 +02002069 def test_expandtabs_optimization(self):
2070 s = 'abc'
2071 self.assertIs(s.expandtabs(), s)
2072
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002073 def test_raiseMemError(self):
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002074 if struct.calcsize('P') == 8:
2075 # 64 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002076 ascii_struct_size = 48
2077 compact_struct_size = 72
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002078 else:
2079 # 32 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002080 ascii_struct_size = 24
2081 compact_struct_size = 36
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002082
2083 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
2084 code = ord(char)
2085 if code < 0x100:
2086 char_size = 1 # sizeof(Py_UCS1)
2087 struct_size = ascii_struct_size
2088 elif code < 0x10000:
2089 char_size = 2 # sizeof(Py_UCS2)
2090 struct_size = compact_struct_size
2091 else:
2092 char_size = 4 # sizeof(Py_UCS4)
2093 struct_size = compact_struct_size
2094 # Note: sys.maxsize is half of the actual max allocation because of
Martin v. Löwis287eca62011-09-28 10:03:28 +02002095 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2096 # be allocatable, given enough memory.
2097 maxlen = ((sys.maxsize - struct_size) // char_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002098 alloc = lambda: char * maxlen
2099 self.assertRaises(MemoryError, alloc)
2100 self.assertRaises(MemoryError, alloc)
Antoine Pitrou3db3e872008-08-17 17:06:51 +00002101
Victor Stinner808fc0a2010-03-22 12:50:40 +00002102 def test_format_subclass(self):
2103 class S(str):
2104 def __str__(self):
2105 return '__str__ overridden'
2106 s = S('xxx')
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002107 self.assertEqual("%s" % s, '__str__ overridden')
2108 self.assertEqual("{}".format(s), '__str__ overridden')
Victor Stinner808fc0a2010-03-22 12:50:40 +00002109
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002110 # Test PyUnicode_FromFormat()
Victor Stinner1205f272010-09-11 00:54:47 +00002111 def test_from_format(self):
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002112 support.import_module('ctypes')
Victor Stinner15a11362012-10-06 23:48:20 +02002113 from ctypes import (
2114 pythonapi, py_object, sizeof,
Victor Stinner6d970f42011-03-02 00:04:25 +00002115 c_int, c_long, c_longlong, c_ssize_t,
Victor Stinner15a11362012-10-06 23:48:20 +02002116 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002117 name = "PyUnicode_FromFormat"
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002118 _PyUnicode_FromFormat = getattr(pythonapi, name)
2119 _PyUnicode_FromFormat.restype = py_object
2120
2121 def PyUnicode_FromFormat(format, *args):
2122 cargs = tuple(
2123 py_object(arg) if isinstance(arg, str) else arg
2124 for arg in args)
2125 return _PyUnicode_FromFormat(format, *cargs)
Victor Stinner1205f272010-09-11 00:54:47 +00002126
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002127 def check_format(expected, format, *args):
2128 text = PyUnicode_FromFormat(format, *args)
2129 self.assertEqual(expected, text)
2130
Victor Stinner1205f272010-09-11 00:54:47 +00002131 # ascii format, non-ascii argument
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002132 check_format('ascii\x7f=unicode\xe9',
2133 b'ascii\x7f=%U', 'unicode\xe9')
Victor Stinner1205f272010-09-11 00:54:47 +00002134
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002135 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
2136 # raises an error
Ezio Melottied3a7d22010-12-01 02:32:32 +00002137 self.assertRaisesRegex(ValueError,
Victor Stinner1205f272010-09-11 00:54:47 +00002138 '^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
Victor Stinner4c7db312010-09-12 07:51:18 +00002139 'string, got a non-ASCII byte: 0xe9$',
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002140 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002141
Victor Stinner96865452011-03-01 23:44:09 +00002142 # test "%c"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002143 check_format('\uabcd',
2144 b'%c', c_int(0xabcd))
2145 check_format('\U0010ffff',
2146 b'%c', c_int(0x10ffff))
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002147 with self.assertRaises(OverflowError):
2148 PyUnicode_FromFormat(b'%c', c_int(0x110000))
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +03002149 # Issue #18183
Serhiy Storchakaf15ffe02013-06-12 09:28:20 +03002150 check_format('\U00010000\U00100000',
2151 b'%c%c', c_int(0x10000), c_int(0x100000))
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002152
Victor Stinner96865452011-03-01 23:44:09 +00002153 # test "%"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002154 check_format('%',
2155 b'%')
2156 check_format('%',
2157 b'%%')
2158 check_format('%s',
2159 b'%%s')
2160 check_format('[%]',
2161 b'[%%]')
2162 check_format('%abc',
2163 b'%%%s', b'abc')
2164
2165 # truncated string
2166 check_format('abc',
2167 b'%.3s', b'abcdef')
2168 check_format('abc[\ufffd',
2169 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
2170 check_format("'\\u20acABC'",
2171 b'%A', '\u20acABC')
2172 check_format("'\\u20",
2173 b'%.5A', '\u20acABCDEF')
2174 check_format("'\u20acABC'",
2175 b'%R', '\u20acABC')
2176 check_format("'\u20acA",
2177 b'%.3R', '\u20acABCDEF')
2178 check_format('\u20acAB',
2179 b'%.3S', '\u20acABCDEF')
2180 check_format('\u20acAB',
2181 b'%.3U', '\u20acABCDEF')
2182 check_format('\u20acAB',
2183 b'%.3V', '\u20acABCDEF', None)
2184 check_format('abc[\ufffd',
2185 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
2186
2187 # following tests comes from #7330
2188 # test width modifier and precision modifier with %S
2189 check_format("repr= abc",
2190 b'repr=%5S', 'abc')
2191 check_format("repr=ab",
2192 b'repr=%.2S', 'abc')
2193 check_format("repr= ab",
2194 b'repr=%5.2S', 'abc')
2195
2196 # test width modifier and precision modifier with %R
2197 check_format("repr= 'abc'",
2198 b'repr=%8R', 'abc')
2199 check_format("repr='ab",
2200 b'repr=%.3R', 'abc')
2201 check_format("repr= 'ab",
2202 b'repr=%5.3R', 'abc')
2203
2204 # test width modifier and precision modifier with %A
2205 check_format("repr= 'abc'",
2206 b'repr=%8A', 'abc')
2207 check_format("repr='ab",
2208 b'repr=%.3A', 'abc')
2209 check_format("repr= 'ab",
2210 b'repr=%5.3A', 'abc')
2211
2212 # test width modifier and precision modifier with %s
2213 check_format("repr= abc",
2214 b'repr=%5s', b'abc')
2215 check_format("repr=ab",
2216 b'repr=%.2s', b'abc')
2217 check_format("repr= ab",
2218 b'repr=%5.2s', b'abc')
2219
2220 # test width modifier and precision modifier with %U
2221 check_format("repr= abc",
2222 b'repr=%5U', 'abc')
2223 check_format("repr=ab",
2224 b'repr=%.2U', 'abc')
2225 check_format("repr= ab",
2226 b'repr=%5.2U', 'abc')
2227
2228 # test width modifier and precision modifier with %V
2229 check_format("repr= abc",
2230 b'repr=%5V', 'abc', b'123')
2231 check_format("repr=ab",
2232 b'repr=%.2V', 'abc', b'123')
2233 check_format("repr= ab",
2234 b'repr=%5.2V', 'abc', b'123')
2235 check_format("repr= 123",
2236 b'repr=%5V', None, b'123')
2237 check_format("repr=12",
2238 b'repr=%.2V', None, b'123')
2239 check_format("repr= 12",
2240 b'repr=%5.2V', None, b'123')
Victor Stinner96865452011-03-01 23:44:09 +00002241
Victor Stinner6d970f42011-03-02 00:04:25 +00002242 # test integer formats (%i, %d, %u)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002243 check_format('010',
2244 b'%03i', c_int(10))
2245 check_format('0010',
2246 b'%0.4i', c_int(10))
2247 check_format('-123',
2248 b'%i', c_int(-123))
2249 check_format('-123',
2250 b'%li', c_long(-123))
2251 check_format('-123',
2252 b'%lli', c_longlong(-123))
2253 check_format('-123',
2254 b'%zi', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002255
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002256 check_format('-123',
2257 b'%d', c_int(-123))
2258 check_format('-123',
2259 b'%ld', c_long(-123))
2260 check_format('-123',
2261 b'%lld', c_longlong(-123))
2262 check_format('-123',
2263 b'%zd', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002264
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002265 check_format('123',
2266 b'%u', c_uint(123))
2267 check_format('123',
2268 b'%lu', c_ulong(123))
2269 check_format('123',
2270 b'%llu', c_ulonglong(123))
2271 check_format('123',
2272 b'%zu', c_size_t(123))
Victor Stinner6d970f42011-03-02 00:04:25 +00002273
Victor Stinner15a11362012-10-06 23:48:20 +02002274 # test long output
2275 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
2276 max_longlong = -min_longlong - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002277 check_format(str(min_longlong),
2278 b'%lld', c_longlong(min_longlong))
2279 check_format(str(max_longlong),
2280 b'%lld', c_longlong(max_longlong))
Victor Stinner15a11362012-10-06 23:48:20 +02002281 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002282 check_format(str(max_ulonglong),
2283 b'%llu', c_ulonglong(max_ulonglong))
Victor Stinner15a11362012-10-06 23:48:20 +02002284 PyUnicode_FromFormat(b'%p', c_void_p(-1))
2285
Victor Stinnere215d962012-10-06 23:03:36 +02002286 # test padding (width and/or precision)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002287 check_format('123'.rjust(10, '0'),
2288 b'%010i', c_int(123))
2289 check_format('123'.rjust(100),
2290 b'%100i', c_int(123))
2291 check_format('123'.rjust(100, '0'),
2292 b'%.100i', c_int(123))
2293 check_format('123'.rjust(80, '0').rjust(100),
2294 b'%100.80i', c_int(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002295
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002296 check_format('123'.rjust(10, '0'),
2297 b'%010u', c_uint(123))
2298 check_format('123'.rjust(100),
2299 b'%100u', c_uint(123))
2300 check_format('123'.rjust(100, '0'),
2301 b'%.100u', c_uint(123))
2302 check_format('123'.rjust(80, '0').rjust(100),
2303 b'%100.80u', c_uint(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002304
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002305 check_format('123'.rjust(10, '0'),
2306 b'%010x', c_int(0x123))
2307 check_format('123'.rjust(100),
2308 b'%100x', c_int(0x123))
2309 check_format('123'.rjust(100, '0'),
2310 b'%.100x', c_int(0x123))
2311 check_format('123'.rjust(80, '0').rjust(100),
2312 b'%100.80x', c_int(0x123))
Victor Stinnere215d962012-10-06 23:03:36 +02002313
Victor Stinner6d970f42011-03-02 00:04:25 +00002314 # test %A
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002315 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
2316 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
Victor Stinner9a909002010-10-18 20:59:24 +00002317
Victor Stinner6d970f42011-03-02 00:04:25 +00002318 # test %V
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002319 check_format('repr=abc',
2320 b'repr=%V', 'abc', b'xyz')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002321
2322 # Test string decode from parameter of %s using utf-8.
2323 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
2324 # '\u4eba\u6c11'
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002325 check_format('repr=\u4eba\u6c11',
2326 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002327
2328 #Test replace error handler.
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002329 check_format('repr=abc\ufffd',
2330 b'repr=%V', None, b'abc\xff')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002331
Victor Stinner6d970f42011-03-02 00:04:25 +00002332 # not supported: copy the raw format string. these tests are just here
2333 # to check for crashs and should not be considered as specifications
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002334 check_format('%s',
2335 b'%1%s', b'abc')
2336 check_format('%1abc',
2337 b'%1abc')
2338 check_format('%+i',
2339 b'%+i', c_int(10))
2340 check_format('%.%s',
2341 b'%.%s', b'abc')
Victor Stinner6d970f42011-03-02 00:04:25 +00002342
Victor Stinner1c24bd02010-10-02 11:03:13 +00002343 # Test PyUnicode_AsWideChar()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002344 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002345 def test_aswidechar(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002346 from _testcapi import unicode_aswidechar
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002347 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002348 from ctypes import c_wchar, sizeof
2349
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002350 wchar, size = unicode_aswidechar('abcdef', 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002351 self.assertEqual(size, 2)
2352 self.assertEqual(wchar, 'ab')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002353
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002354 wchar, size = unicode_aswidechar('abc', 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002355 self.assertEqual(size, 3)
2356 self.assertEqual(wchar, 'abc')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002357
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002358 wchar, size = unicode_aswidechar('abc', 4)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002359 self.assertEqual(size, 3)
2360 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002361
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002362 wchar, size = unicode_aswidechar('abc', 10)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002363 self.assertEqual(size, 3)
2364 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002365
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002366 wchar, size = unicode_aswidechar('abc\0def', 20)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002367 self.assertEqual(size, 7)
2368 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002369
Victor Stinner5593d8a2010-10-02 11:11:27 +00002370 nonbmp = chr(0x10ffff)
2371 if sizeof(c_wchar) == 2:
2372 buflen = 3
2373 nchar = 2
2374 else: # sizeof(c_wchar) == 4
2375 buflen = 2
2376 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002377 wchar, size = unicode_aswidechar(nonbmp, buflen)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002378 self.assertEqual(size, nchar)
2379 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002380
Victor Stinner1c24bd02010-10-02 11:03:13 +00002381 # Test PyUnicode_AsWideCharString()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002382 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002383 def test_aswidecharstring(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002384 from _testcapi import unicode_aswidecharstring
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002385 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002386 from ctypes import c_wchar, sizeof
2387
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002388 wchar, size = unicode_aswidecharstring('abc')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002389 self.assertEqual(size, 3)
2390 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002391
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002392 wchar, size = unicode_aswidecharstring('abc\0def')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002393 self.assertEqual(size, 7)
2394 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002395
Victor Stinner5593d8a2010-10-02 11:11:27 +00002396 nonbmp = chr(0x10ffff)
2397 if sizeof(c_wchar) == 2:
2398 nchar = 2
2399 else: # sizeof(c_wchar) == 4
2400 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002401 wchar, size = unicode_aswidecharstring(nonbmp)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002402 self.assertEqual(size, nchar)
2403 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002404
Benjamin Peterson811c2f12011-09-30 21:31:21 -04002405 def test_subclass_add(self):
2406 class S(str):
2407 def __add__(self, o):
2408 return "3"
2409 self.assertEqual(S("4") + S("5"), "3")
2410 class S(str):
2411 def __iadd__(self, o):
2412 return "3"
2413 s = S("1")
2414 s += "4"
2415 self.assertEqual(s, "3")
2416
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002417 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002418 def test_encode_decimal(self):
2419 from _testcapi import unicode_encodedecimal
2420 self.assertEqual(unicode_encodedecimal('123'),
2421 b'123')
2422 self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
2423 b'3.14')
2424 self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2425 b' 3.14 ')
2426 self.assertRaises(UnicodeEncodeError,
2427 unicode_encodedecimal, "123\u20ac", "strict")
Victor Stinner6345be92011-11-25 20:09:01 +01002428 self.assertRaisesRegex(
2429 ValueError,
2430 "^'decimal' codec can't encode character",
2431 unicode_encodedecimal, "123\u20ac", "replace")
Victor Stinner42bf7752011-11-21 22:52:58 +01002432
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002433 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002434 def test_transform_decimal(self):
2435 from _testcapi import unicode_transformdecimaltoascii as transform_decimal
2436 self.assertEqual(transform_decimal('123'),
2437 '123')
2438 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
2439 '3.14')
2440 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2441 "\N{EM SPACE}3.14\N{EN SPACE}")
2442 self.assertEqual(transform_decimal('123\u20ac'),
2443 '123\u20ac')
2444
Victor Stinnerc814a382011-11-22 01:06:15 +01002445 def test_getnewargs(self):
2446 text = 'abc'
2447 args = text.__getnewargs__()
2448 self.assertIsNot(args[0], text)
2449 self.assertEqual(args[0], text)
2450 self.assertEqual(len(args), 1)
2451
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002452 def test_resize(self):
2453 for length in range(1, 100, 7):
2454 # generate a fresh string (refcount=1)
2455 text = 'a' * length + 'b'
2456
Ezio Melotti51e243f2013-02-20 23:56:01 +02002457 with support.check_warnings(('unicode_internal codec has been '
2458 'deprecated', DeprecationWarning)):
2459 # fill wstr internal field
2460 abc = text.encode('unicode_internal')
2461 self.assertEqual(abc.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002462
Ezio Melotti51e243f2013-02-20 23:56:01 +02002463 # resize text: wstr field must be cleared and then recomputed
2464 text += 'c'
2465 abcdef = text.encode('unicode_internal')
2466 self.assertNotEqual(abc, abcdef)
2467 self.assertEqual(abcdef.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002468
Victor Stinner9fc59812013-04-08 22:34:43 +02002469 def test_compare(self):
2470 # Issue #17615
2471 N = 10
2472 ascii = 'a' * N
2473 ascii2 = 'z' * N
2474 latin = '\x80' * N
2475 latin2 = '\xff' * N
2476 bmp = '\u0100' * N
2477 bmp2 = '\uffff' * N
2478 astral = '\U00100000' * N
2479 astral2 = '\U0010ffff' * N
2480 strings = (
2481 ascii, ascii2,
2482 latin, latin2,
2483 bmp, bmp2,
2484 astral, astral2)
2485 for text1, text2 in itertools.combinations(strings, 2):
2486 equal = (text1 is text2)
2487 self.assertEqual(text1 == text2, equal)
2488 self.assertEqual(text1 != text2, not equal)
2489
2490 if equal:
2491 self.assertTrue(text1 <= text2)
2492 self.assertTrue(text1 >= text2)
2493
2494 # text1 is text2: duplicate strings to skip the "str1 == str2"
2495 # optimization in unicode_compare_eq() and really compare
2496 # character per character
2497 copy1 = duplicate_string(text1)
2498 copy2 = duplicate_string(text2)
2499 self.assertIsNot(copy1, copy2)
2500
2501 self.assertTrue(copy1 == copy2)
2502 self.assertFalse(copy1 != copy2)
2503
2504 self.assertTrue(copy1 <= copy2)
2505 self.assertTrue(copy2 >= copy2)
2506
2507 self.assertTrue(ascii < ascii2)
2508 self.assertTrue(ascii < latin)
2509 self.assertTrue(ascii < bmp)
2510 self.assertTrue(ascii < astral)
2511 self.assertFalse(ascii >= ascii2)
2512 self.assertFalse(ascii >= latin)
2513 self.assertFalse(ascii >= bmp)
2514 self.assertFalse(ascii >= astral)
2515
2516 self.assertFalse(latin < ascii)
2517 self.assertTrue(latin < latin2)
2518 self.assertTrue(latin < bmp)
2519 self.assertTrue(latin < astral)
2520 self.assertTrue(latin >= ascii)
2521 self.assertFalse(latin >= latin2)
2522 self.assertFalse(latin >= bmp)
2523 self.assertFalse(latin >= astral)
2524
2525 self.assertFalse(bmp < ascii)
2526 self.assertFalse(bmp < latin)
2527 self.assertTrue(bmp < bmp2)
2528 self.assertTrue(bmp < astral)
2529 self.assertTrue(bmp >= ascii)
2530 self.assertTrue(bmp >= latin)
2531 self.assertFalse(bmp >= bmp2)
2532 self.assertFalse(bmp >= astral)
2533
2534 self.assertFalse(astral < ascii)
2535 self.assertFalse(astral < latin)
2536 self.assertFalse(astral < bmp2)
2537 self.assertTrue(astral < astral2)
2538 self.assertTrue(astral >= ascii)
2539 self.assertTrue(astral >= latin)
2540 self.assertTrue(astral >= bmp2)
2541 self.assertFalse(astral >= astral2)
2542
Victor Stinner1c24bd02010-10-02 11:03:13 +00002543
Eric Smitha1eac722011-01-29 11:15:35 +00002544class StringModuleTest(unittest.TestCase):
2545 def test_formatter_parser(self):
2546 def parse(format):
2547 return list(_string.formatter_parser(format))
2548
2549 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2550 self.assertEqual(formatter, [
2551 ('prefix ', '2', '', 's'),
2552 ('xxx', '0', '^+10.3f', None),
2553 ('', 'obj.attr', '', 's'),
2554 (' ', 'z[0]', '10', 's'),
2555 ])
2556
2557 formatter = parse("prefix {} suffix")
2558 self.assertEqual(formatter, [
2559 ('prefix ', '', '', None),
2560 (' suffix', None, None, None),
2561 ])
2562
2563 formatter = parse("str")
2564 self.assertEqual(formatter, [
2565 ('str', None, None, None),
2566 ])
2567
2568 formatter = parse("")
2569 self.assertEqual(formatter, [])
2570
2571 formatter = parse("{0}")
2572 self.assertEqual(formatter, [
2573 ('', '0', '', None),
2574 ])
2575
2576 self.assertRaises(TypeError, _string.formatter_parser, 1)
2577
2578 def test_formatter_field_name_split(self):
2579 def split(name):
2580 items = list(_string.formatter_field_name_split(name))
2581 items[1] = list(items[1])
2582 return items
2583 self.assertEqual(split("obj"), ["obj", []])
2584 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
2585 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
2586 self.assertEqual(split("obj.arg[key1][key2]"), [
2587 "obj",
2588 [(True, 'arg'),
2589 (False, 'key1'),
2590 (False, 'key2'),
2591 ]])
2592 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
2593
2594
Walter Dörwald28256f22003-01-19 16:59:20 +00002595if __name__ == "__main__":
Ezio Melotti0dceb562013-01-10 07:43:26 +02002596 unittest.main()