blob: d6644657bab152ce4b2d2030603bdd276d068085 [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)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200183 # test mixed kinds
184 self.checkequal(10, '\u0102' + 'a' * 10, 'count', 'a')
185 self.checkequal(10, '\U00100304' + 'a' * 10, 'count', 'a')
186 self.checkequal(10, '\U00100304' + '\u0102' * 10, 'count', '\u0102')
187 self.checkequal(0, 'a' * 10, 'count', '\u0102')
188 self.checkequal(0, 'a' * 10, 'count', '\U00100304')
189 self.checkequal(0, '\u0102' * 10, 'count', '\U00100304')
190 self.checkequal(10, '\u0102' + 'a_' * 10, 'count', 'a_')
191 self.checkequal(10, '\U00100304' + 'a_' * 10, 'count', 'a_')
192 self.checkequal(10, '\U00100304' + '\u0102_' * 10, 'count', '\u0102_')
193 self.checkequal(0, 'a' * 10, 'count', 'a\u0102')
194 self.checkequal(0, 'a' * 10, 'count', 'a\U00100304')
195 self.checkequal(0, '\u0102' * 10, 'count', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000196
Walter Dörwald28256f22003-01-19 16:59:20 +0000197 def test_find(self):
Antoine Pitrouc0bbe7d2011-10-08 22:41:35 +0200198 string_tests.CommonTest.test_find(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200199 # test implementation details of the memchr fast path
200 self.checkequal(100, 'a' * 100 + '\u0102', 'find', '\u0102')
201 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0201')
202 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0120')
203 self.checkequal(-1, 'a' * 100 + '\u0102', 'find', '\u0220')
204 self.checkequal(100, 'a' * 100 + '\U00100304', 'find', '\U00100304')
205 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00100204')
206 self.checkequal(-1, 'a' * 100 + '\U00100304', 'find', '\U00102004')
207 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000208 self.checkequalnofix(0, 'abcdefghiabc', 'find', 'abc')
209 self.checkequalnofix(9, 'abcdefghiabc', 'find', 'abc', 1)
210 self.checkequalnofix(-1, 'abcdefghiabc', 'find', 'def', 4)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000211
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000212 self.assertRaises(TypeError, 'hello'.find)
213 self.assertRaises(TypeError, 'hello'.find, 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200214 # test mixed kinds
215 self.checkequal(100, '\u0102' * 100 + 'a', 'find', 'a')
216 self.checkequal(100, '\U00100304' * 100 + 'a', 'find', 'a')
217 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'find', '\u0102')
218 self.checkequal(-1, 'a' * 100, 'find', '\u0102')
219 self.checkequal(-1, 'a' * 100, 'find', '\U00100304')
220 self.checkequal(-1, '\u0102' * 100, 'find', '\U00100304')
221 self.checkequal(100, '\u0102' * 100 + 'a_', 'find', 'a_')
222 self.checkequal(100, '\U00100304' * 100 + 'a_', 'find', 'a_')
223 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'find', '\u0102_')
224 self.checkequal(-1, 'a' * 100, 'find', 'a\u0102')
225 self.checkequal(-1, 'a' * 100, 'find', 'a\U00100304')
226 self.checkequal(-1, '\u0102' * 100, 'find', '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000227
Walter Dörwald28256f22003-01-19 16:59:20 +0000228 def test_rfind(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000229 string_tests.CommonTest.test_rfind(self)
Antoine Pitrou2c3b2302011-10-11 20:29:21 +0200230 # test implementation details of the memrchr fast path
231 self.checkequal(0, '\u0102' + 'a' * 100 , 'rfind', '\u0102')
232 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0201')
233 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0120')
234 self.checkequal(-1, '\u0102' + 'a' * 100 , 'rfind', '\u0220')
235 self.checkequal(0, '\U00100304' + 'a' * 100, 'rfind', '\U00100304')
236 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00100204')
237 self.checkequal(-1, '\U00100304' + 'a' * 100, 'rfind', '\U00102004')
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000238 # check mixed argument types
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000239 self.checkequalnofix(9, 'abcdefghiabc', 'rfind', 'abc')
240 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
241 self.checkequalnofix(12, 'abcdefghiabc', 'rfind', '')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200242 # test mixed kinds
243 self.checkequal(0, 'a' + '\u0102' * 100, 'rfind', 'a')
244 self.checkequal(0, 'a' + '\U00100304' * 100, 'rfind', 'a')
245 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rfind', '\u0102')
246 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102')
247 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304')
248 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304')
249 self.checkequal(0, '_a' + '\u0102' * 100, 'rfind', '_a')
250 self.checkequal(0, '_a' + '\U00100304' * 100, 'rfind', '_a')
251 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rfind', '_\u0102')
252 self.checkequal(-1, 'a' * 100, 'rfind', '\u0102a')
253 self.checkequal(-1, 'a' * 100, 'rfind', '\U00100304a')
254 self.checkequal(-1, '\u0102' * 100, 'rfind', '\U00100304\u0102')
Guido van Rossum8b264542000-12-19 02:22:31 +0000255
Walter Dörwald28256f22003-01-19 16:59:20 +0000256 def test_index(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000257 string_tests.CommonTest.test_index(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000258 self.checkequalnofix(0, 'abcdefghiabc', 'index', '')
259 self.checkequalnofix(3, 'abcdefghiabc', 'index', 'def')
260 self.checkequalnofix(0, 'abcdefghiabc', 'index', 'abc')
261 self.checkequalnofix(9, 'abcdefghiabc', 'index', 'abc', 1)
262 self.assertRaises(ValueError, 'abcdefghiabc'.index, 'hib')
263 self.assertRaises(ValueError, 'abcdefghiab'.index, 'abc', 1)
264 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', 8)
265 self.assertRaises(ValueError, 'abcdefghi'.index, 'ghi', -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200266 # test mixed kinds
267 self.checkequal(100, '\u0102' * 100 + 'a', 'index', 'a')
268 self.checkequal(100, '\U00100304' * 100 + 'a', 'index', 'a')
269 self.checkequal(100, '\U00100304' * 100 + '\u0102', 'index', '\u0102')
270 self.assertRaises(ValueError, ('a' * 100).index, '\u0102')
271 self.assertRaises(ValueError, ('a' * 100).index, '\U00100304')
272 self.assertRaises(ValueError, ('\u0102' * 100).index, '\U00100304')
273 self.checkequal(100, '\u0102' * 100 + 'a_', 'index', 'a_')
274 self.checkequal(100, '\U00100304' * 100 + 'a_', 'index', 'a_')
275 self.checkequal(100, '\U00100304' * 100 + '\u0102_', 'index', '\u0102_')
276 self.assertRaises(ValueError, ('a' * 100).index, 'a\u0102')
277 self.assertRaises(ValueError, ('a' * 100).index, 'a\U00100304')
278 self.assertRaises(ValueError, ('\u0102' * 100).index, '\u0102\U00100304')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000279
Walter Dörwald28256f22003-01-19 16:59:20 +0000280 def test_rindex(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000281 string_tests.CommonTest.test_rindex(self)
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000282 self.checkequalnofix(12, 'abcdefghiabc', 'rindex', '')
283 self.checkequalnofix(3, 'abcdefghiabc', 'rindex', 'def')
284 self.checkequalnofix(9, 'abcdefghiabc', 'rindex', 'abc')
285 self.checkequalnofix(0, 'abcdefghiabc', 'rindex', 'abc', 0, -1)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000286
Walter Dörwaldaa97f042007-05-03 21:05:51 +0000287 self.assertRaises(ValueError, 'abcdefghiabc'.rindex, 'hib')
288 self.assertRaises(ValueError, 'defghiabc'.rindex, 'def', 1)
289 self.assertRaises(ValueError, 'defghiabc'.rindex, 'abc', 0, -1)
290 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, 8)
291 self.assertRaises(ValueError, 'abcdefghi'.rindex, 'ghi', 0, -1)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200292 # test mixed kinds
293 self.checkequal(0, 'a' + '\u0102' * 100, 'rindex', 'a')
294 self.checkequal(0, 'a' + '\U00100304' * 100, 'rindex', 'a')
295 self.checkequal(0, '\u0102' + '\U00100304' * 100, 'rindex', '\u0102')
296 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102')
297 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304')
298 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304')
299 self.checkequal(0, '_a' + '\u0102' * 100, 'rindex', '_a')
300 self.checkequal(0, '_a' + '\U00100304' * 100, 'rindex', '_a')
301 self.checkequal(0, '_\u0102' + '\U00100304' * 100, 'rindex', '_\u0102')
302 self.assertRaises(ValueError, ('a' * 100).rindex, '\u0102a')
303 self.assertRaises(ValueError, ('a' * 100).rindex, '\U00100304a')
304 self.assertRaises(ValueError, ('\u0102' * 100).rindex, '\U00100304\u0102')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000305
Georg Brandlceee0772007-11-27 23:48:05 +0000306 def test_maketrans_translate(self):
307 # these work with plain translate()
308 self.checkequalnofix('bbbc', 'abababc', 'translate',
309 {ord('a'): None})
310 self.checkequalnofix('iiic', 'abababc', 'translate',
311 {ord('a'): None, ord('b'): ord('i')})
312 self.checkequalnofix('iiix', 'abababc', 'translate',
313 {ord('a'): None, ord('b'): ord('i'), ord('c'): 'x'})
314 self.checkequalnofix('c', 'abababc', 'translate',
315 {ord('a'): None, ord('b'): ''})
316 self.checkequalnofix('xyyx', 'xzx', 'translate',
317 {ord('z'): 'yy'})
318 # this needs maketrans()
319 self.checkequalnofix('abababc', 'abababc', 'translate',
320 {'b': '<i>'})
321 tbl = self.type2test.maketrans({'a': None, 'b': '<i>'})
322 self.checkequalnofix('<i><i><i>c', 'abababc', 'translate', tbl)
323 # test alternative way of calling maketrans()
324 tbl = self.type2test.maketrans('abc', 'xyz', 'd')
325 self.checkequalnofix('xyzzy', 'abdcdcbdddd', 'translate', tbl)
326
327 self.assertRaises(TypeError, self.type2test.maketrans)
328 self.assertRaises(ValueError, self.type2test.maketrans, 'abc', 'defg')
329 self.assertRaises(TypeError, self.type2test.maketrans, 2, 'def')
330 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 2)
331 self.assertRaises(TypeError, self.type2test.maketrans, 'abc', 'def', 2)
332 self.assertRaises(ValueError, self.type2test.maketrans, {'xy': 2})
333 self.assertRaises(TypeError, self.type2test.maketrans, {(1,): 2})
Guido van Rossuma831cac2000-03-10 23:23:21 +0000334
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000335 self.assertRaises(TypeError, 'hello'.translate)
Walter Dörwald67e83882007-05-05 12:26:27 +0000336 self.assertRaises(TypeError, 'abababc'.translate, 'abc', 'xyz')
Guido van Rossuma831cac2000-03-10 23:23:21 +0000337
Walter Dörwald28256f22003-01-19 16:59:20 +0000338 def test_split(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000339 string_tests.CommonTest.test_split(self)
Andrew M. Kuchlingeddd68d2002-03-29 16:21:44 +0000340
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000341 # Mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000342 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
343 self.checkequalnofix(['a', 'b', 'c', 'd'], 'a//b//c//d', 'split', '//')
344 self.checkequalnofix(['endcase ', ''], 'endcase test', 'split', 'test')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200345 # test mixed kinds
346 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
347 left *= 9
348 right *= 9
349 for delim in ('c', '\u0102', '\U00010302'):
350 self.checkequal([left + right],
351 left + right, 'split', delim)
352 self.checkequal([left, right],
353 left + delim + right, 'split', delim)
354 self.checkequal([left + right],
355 left + right, 'split', delim * 2)
356 self.checkequal([left, right],
357 left + delim * 2 + right, 'split', delim *2)
358
359 def test_rsplit(self):
360 string_tests.CommonTest.test_rsplit(self)
361 # test mixed kinds
362 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
363 left *= 9
364 right *= 9
365 for delim in ('c', '\u0102', '\U00010302'):
366 self.checkequal([left + right],
367 left + right, 'rsplit', delim)
368 self.checkequal([left, right],
369 left + delim + right, 'rsplit', delim)
370 self.checkequal([left + right],
371 left + right, 'rsplit', delim * 2)
372 self.checkequal([left, right],
373 left + delim * 2 + right, 'rsplit', delim *2)
374
375 def test_partition(self):
376 string_tests.MixinStrUnicodeUserStringTest.test_partition(self)
377 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300378 self.checkequal(('ABCDEFGH', '', ''), 'ABCDEFGH', 'partition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200379 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
380 left *= 9
381 right *= 9
382 for delim in ('c', '\u0102', '\U00010302'):
383 self.checkequal((left + right, '', ''),
384 left + right, 'partition', delim)
385 self.checkequal((left, delim, right),
386 left + delim + right, 'partition', delim)
387 self.checkequal((left + right, '', ''),
388 left + right, 'partition', delim * 2)
389 self.checkequal((left, delim * 2, right),
390 left + delim * 2 + right, 'partition', delim * 2)
391
392 def test_rpartition(self):
393 string_tests.MixinStrUnicodeUserStringTest.test_rpartition(self)
394 # test mixed kinds
Serhiy Storchaka48070c12015-03-29 19:21:02 +0300395 self.checkequal(('', '', 'ABCDEFGH'), 'ABCDEFGH', 'rpartition', '\u4200')
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200396 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
397 left *= 9
398 right *= 9
399 for delim in ('c', '\u0102', '\U00010302'):
400 self.checkequal(('', '', left + right),
401 left + right, 'rpartition', delim)
402 self.checkequal((left, delim, right),
403 left + delim + right, 'rpartition', delim)
404 self.checkequal(('', '', left + right),
405 left + right, 'rpartition', delim * 2)
406 self.checkequal((left, delim * 2, right),
407 left + delim * 2 + right, 'rpartition', delim * 2)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000408
Walter Dörwald28256f22003-01-19 16:59:20 +0000409 def test_join(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000410 string_tests.MixinStrUnicodeUserStringTest.test_join(self)
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +0000411
Guido van Rossumf1044292007-09-27 18:01:22 +0000412 class MyWrapper:
413 def __init__(self, sval): self.sval = sval
414 def __str__(self): return self.sval
415
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000416 # mixed arguments
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000417 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
418 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
419 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
420 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
421 self.checkequalnofix('a b c d', ' ', 'join', ['a', 'b', 'c', 'd'])
422 self.checkequalnofix('abcd', '', 'join', ('a', 'b', 'c', 'd'))
423 self.checkequalnofix('w x y z', ' ', 'join', string_tests.Sequence('wxyz'))
Guido van Rossum98297ee2007-11-06 21:34:58 +0000424 self.checkraises(TypeError, ' ', 'join', ['1', '2', MyWrapper('foo')])
425 self.checkraises(TypeError, ' ', 'join', ['1', '2', '3', bytes()])
426 self.checkraises(TypeError, ' ', 'join', [1, 2, 3])
427 self.checkraises(TypeError, ' ', 'join', ['1', '2', 3])
Marc-André Lemburge5034372000-08-08 08:04:29 +0000428
Walter Dörwald28256f22003-01-19 16:59:20 +0000429 def test_replace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000430 string_tests.CommonTest.test_replace(self)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000431
Walter Dörwald28256f22003-01-19 16:59:20 +0000432 # method call forwarded from str implementation because of unicode argument
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000433 self.checkequalnofix('one@two!three!', 'one!two!three!', 'replace', '!', '@', 1)
434 self.assertRaises(TypeError, 'replace'.replace, "r", 42)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200435 # test mixed kinds
436 for left, right in ('ba', '\u0101\u0100', '\U00010301\U00010300'):
437 left *= 9
438 right *= 9
439 for delim in ('c', '\u0102', '\U00010302'):
440 for repl in ('d', '\u0103', '\U00010303'):
441 self.checkequal(left + right,
442 left + right, 'replace', delim, repl)
443 self.checkequal(left + repl + right,
444 left + delim + right,
445 'replace', delim, repl)
446 self.checkequal(left + right,
447 left + right, 'replace', delim * 2, repl)
448 self.checkequal(left + repl + right,
449 left + delim * 2 + right,
450 'replace', delim * 2, repl)
Guido van Rossuma831cac2000-03-10 23:23:21 +0000451
Victor Stinner59de0ee2011-10-07 10:01:28 +0200452 @support.cpython_only
453 def test_replace_id(self):
Victor Stinner1d972ad2011-10-07 13:31:46 +0200454 pattern = 'abc'
455 text = 'abc def'
456 self.assertIs(text.replace(pattern, pattern), text)
Victor Stinner59de0ee2011-10-07 10:01:28 +0200457
Guido van Rossum98297ee2007-11-06 21:34:58 +0000458 def test_bytes_comparison(self):
Brett Cannon226b2302010-03-20 22:22:22 +0000459 with support.check_warnings():
460 warnings.simplefilter('ignore', BytesWarning)
461 self.assertEqual('abc' == b'abc', False)
462 self.assertEqual('abc' != b'abc', True)
463 self.assertEqual('abc' == bytearray(b'abc'), False)
464 self.assertEqual('abc' != bytearray(b'abc'), True)
Brett Cannon40430012007-10-22 20:24:51 +0000465
Walter Dörwald28256f22003-01-19 16:59:20 +0000466 def test_comparison(self):
467 # Comparisons:
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000468 self.assertEqual('abc', 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000469 self.assertTrue('abcd' > 'abc')
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000470 self.assertTrue('abc' < 'abcd')
Walter Dörwald28256f22003-01-19 16:59:20 +0000471
472 if 0:
473 # Move these tests to a Unicode collation module test...
474 # Testing UTF-16 code point order comparisons...
475
476 # No surrogates, no fixup required.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000477 self.assertTrue('\u0061' < '\u20ac')
Walter Dörwald28256f22003-01-19 16:59:20 +0000478 # Non surrogate below surrogate value, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000479 self.assertTrue('\u0061' < '\ud800\udc02')
Walter Dörwald28256f22003-01-19 16:59:20 +0000480
481 # Non surrogate above surrogate value, fixup required
482 def test_lecmp(s, s2):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000483 self.assertTrue(s < s2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000484
485 def test_fixup(s):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000486 s2 = '\ud800\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000487 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000488 s2 = '\ud900\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000489 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000490 s2 = '\uda00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000491 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000492 s2 = '\udb00\udc01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000493 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000494 s2 = '\ud800\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000495 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000496 s2 = '\ud900\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000497 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000498 s2 = '\uda00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000499 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000500 s2 = '\udb00\udd01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000501 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000502 s2 = '\ud800\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000503 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000504 s2 = '\ud900\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000505 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000506 s2 = '\uda00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000507 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000508 s2 = '\udb00\ude01'
Walter Dörwald28256f22003-01-19 16:59:20 +0000509 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000510 s2 = '\ud800\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000511 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000512 s2 = '\ud900\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000513 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000514 s2 = '\uda00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000515 test_lecmp(s, s2)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000516 s2 = '\udb00\udfff'
Walter Dörwald28256f22003-01-19 16:59:20 +0000517 test_lecmp(s, s2)
518
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000519 test_fixup('\ue000')
520 test_fixup('\uff61')
Walter Dörwald28256f22003-01-19 16:59:20 +0000521
522 # Surrogates on both sides, no fixup required
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000523 self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
Walter Dörwald28256f22003-01-19 16:59:20 +0000524
Walter Dörwald28256f22003-01-19 16:59:20 +0000525 def test_islower(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000526 string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000527 self.checkequalnofix(False, '\u1FFc', 'islower')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500528 self.assertFalse('\u2167'.islower())
529 self.assertTrue('\u2177'.islower())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300530 # non-BMP, uppercase
531 self.assertFalse('\U00010401'.islower())
532 self.assertFalse('\U00010427'.islower())
533 # non-BMP, lowercase
534 self.assertTrue('\U00010429'.islower())
535 self.assertTrue('\U0001044E'.islower())
536 # non-BMP, non-cased
537 self.assertFalse('\U0001F40D'.islower())
538 self.assertFalse('\U0001F46F'.islower())
Walter Dörwald28256f22003-01-19 16:59:20 +0000539
540 def test_isupper(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000541 string_tests.MixinStrUnicodeUserStringTest.test_isupper(self)
542 if not sys.platform.startswith('java'):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000543 self.checkequalnofix(False, '\u1FFc', 'isupper')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500544 self.assertTrue('\u2167'.isupper())
545 self.assertFalse('\u2177'.isupper())
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300546 # non-BMP, uppercase
547 self.assertTrue('\U00010401'.isupper())
548 self.assertTrue('\U00010427'.isupper())
549 # non-BMP, lowercase
550 self.assertFalse('\U00010429'.isupper())
551 self.assertFalse('\U0001044E'.isupper())
552 # non-BMP, non-cased
553 self.assertFalse('\U0001F40D'.isupper())
554 self.assertFalse('\U0001F46F'.isupper())
Walter Dörwald28256f22003-01-19 16:59:20 +0000555
556 def test_istitle(self):
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300557 string_tests.MixinStrUnicodeUserStringTest.test_istitle(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000558 self.checkequalnofix(True, '\u1FFc', 'istitle')
559 self.checkequalnofix(True, 'Greek \u1FFcitlecases ...', 'istitle')
Walter Dörwald28256f22003-01-19 16:59:20 +0000560
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300561 # non-BMP, uppercase + lowercase
562 self.assertTrue('\U00010401\U00010429'.istitle())
563 self.assertTrue('\U00010427\U0001044E'.istitle())
564 # apparently there are no titlecased (Lt) non-BMP chars in Unicode 6
565 for ch in ['\U00010429', '\U0001044E', '\U0001F40D', '\U0001F46F']:
566 self.assertFalse(ch.istitle(), '{!a} is not title'.format(ch))
567
Walter Dörwald28256f22003-01-19 16:59:20 +0000568 def test_isspace(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000569 string_tests.MixinStrUnicodeUserStringTest.test_isspace(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000570 self.checkequalnofix(True, '\u2000', 'isspace')
571 self.checkequalnofix(True, '\u200a', 'isspace')
572 self.checkequalnofix(False, '\u2014', 'isspace')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300573 # apparently there are no non-BMP spaces chars in Unicode 6
574 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
575 '\U0001F40D', '\U0001F46F']:
576 self.assertFalse(ch.isspace(), '{!a} is not space.'.format(ch))
577
578 def test_isalnum(self):
579 string_tests.MixinStrUnicodeUserStringTest.test_isalnum(self)
580 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
581 '\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
582 self.assertTrue(ch.isalnum(), '{!a} is alnum.'.format(ch))
Walter Dörwald28256f22003-01-19 16:59:20 +0000583
584 def test_isalpha(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000585 string_tests.MixinStrUnicodeUserStringTest.test_isalpha(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000586 self.checkequalnofix(True, '\u1FFc', 'isalpha')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300587 # non-BMP, cased
588 self.assertTrue('\U00010401'.isalpha())
589 self.assertTrue('\U00010427'.isalpha())
590 self.assertTrue('\U00010429'.isalpha())
591 self.assertTrue('\U0001044E'.isalpha())
592 # non-BMP, non-cased
593 self.assertFalse('\U0001F40D'.isalpha())
594 self.assertFalse('\U0001F46F'.isalpha())
Walter Dörwald28256f22003-01-19 16:59:20 +0000595
596 def test_isdecimal(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000597 self.checkequalnofix(False, '', 'isdecimal')
598 self.checkequalnofix(False, 'a', 'isdecimal')
599 self.checkequalnofix(True, '0', 'isdecimal')
600 self.checkequalnofix(False, '\u2460', 'isdecimal') # CIRCLED DIGIT ONE
601 self.checkequalnofix(False, '\xbc', 'isdecimal') # VULGAR FRACTION ONE QUARTER
602 self.checkequalnofix(True, '\u0660', 'isdecimal') # ARABIC-INDIC DIGIT ZERO
603 self.checkequalnofix(True, '0123456789', 'isdecimal')
604 self.checkequalnofix(False, '0123456789a', 'isdecimal')
Walter Dörwald28256f22003-01-19 16:59:20 +0000605
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000606 self.checkraises(TypeError, 'abc', 'isdecimal', 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000607
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300608 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
609 '\U0001F40D', '\U0001F46F', '\U00011065', '\U0001F107']:
610 self.assertFalse(ch.isdecimal(), '{!a} is not decimal.'.format(ch))
611 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0']:
612 self.assertTrue(ch.isdecimal(), '{!a} is decimal.'.format(ch))
613
Walter Dörwald28256f22003-01-19 16:59:20 +0000614 def test_isdigit(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +0000615 string_tests.MixinStrUnicodeUserStringTest.test_isdigit(self)
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000616 self.checkequalnofix(True, '\u2460', 'isdigit')
617 self.checkequalnofix(False, '\xbc', 'isdigit')
618 self.checkequalnofix(True, '\u0660', 'isdigit')
Walter Dörwald28256f22003-01-19 16:59:20 +0000619
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300620 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
621 '\U0001F40D', '\U0001F46F', '\U00011065']:
622 self.assertFalse(ch.isdigit(), '{!a} is not a digit.'.format(ch))
623 for ch in ['\U0001D7F6', '\U00011066', '\U000104A0', '\U0001F107']:
624 self.assertTrue(ch.isdigit(), '{!a} is a digit.'.format(ch))
625
Walter Dörwald28256f22003-01-19 16:59:20 +0000626 def test_isnumeric(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000627 self.checkequalnofix(False, '', 'isnumeric')
628 self.checkequalnofix(False, 'a', 'isnumeric')
629 self.checkequalnofix(True, '0', 'isnumeric')
630 self.checkequalnofix(True, '\u2460', 'isnumeric')
631 self.checkequalnofix(True, '\xbc', 'isnumeric')
632 self.checkequalnofix(True, '\u0660', 'isnumeric')
633 self.checkequalnofix(True, '0123456789', 'isnumeric')
634 self.checkequalnofix(False, '0123456789a', 'isnumeric')
Walter Dörwald28256f22003-01-19 16:59:20 +0000635
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000636 self.assertRaises(TypeError, "abc".isnumeric, 42)
Walter Dörwald28256f22003-01-19 16:59:20 +0000637
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300638 for ch in ['\U00010401', '\U00010427', '\U00010429', '\U0001044E',
639 '\U0001F40D', '\U0001F46F']:
640 self.assertFalse(ch.isnumeric(), '{!a} is not numeric.'.format(ch))
641 for ch in ['\U00011065', '\U0001D7F6', '\U00011066',
642 '\U000104A0', '\U0001F107']:
643 self.assertTrue(ch.isnumeric(), '{!a} is numeric.'.format(ch))
644
Martin v. Löwis47383402007-08-15 07:32:56 +0000645 def test_isidentifier(self):
646 self.assertTrue("a".isidentifier())
647 self.assertTrue("Z".isidentifier())
648 self.assertTrue("_".isidentifier())
649 self.assertTrue("b0".isidentifier())
650 self.assertTrue("bc".isidentifier())
651 self.assertTrue("b_".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000652 self.assertTrue("µ".isidentifier())
Benjamin Petersonf413b802011-08-12 22:17:18 -0500653 self.assertTrue("𝔘𝔫𝔦𝔠𝔬𝔡𝔢".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000654
655 self.assertFalse(" ".isidentifier())
656 self.assertFalse("[".isidentifier())
Antoine Pitroud72402e2010-10-27 18:52:48 +0000657 self.assertFalse("©".isidentifier())
Georg Brandld52429f2008-07-04 15:55:02 +0000658 self.assertFalse("0".isidentifier())
Martin v. Löwis47383402007-08-15 07:32:56 +0000659
Georg Brandl559e5d72008-06-11 18:37:52 +0000660 def test_isprintable(self):
661 self.assertTrue("".isprintable())
Benjamin Peterson09832742009-03-26 17:15:46 +0000662 self.assertTrue(" ".isprintable())
Georg Brandl559e5d72008-06-11 18:37:52 +0000663 self.assertTrue("abcdefg".isprintable())
664 self.assertFalse("abcdefg\n".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000665 # some defined Unicode character
666 self.assertTrue("\u0374".isprintable())
667 # undefined character
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +0000668 self.assertFalse("\u0378".isprintable())
Georg Brandld52429f2008-07-04 15:55:02 +0000669 # single surrogate character
Georg Brandl559e5d72008-06-11 18:37:52 +0000670 self.assertFalse("\ud800".isprintable())
671
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300672 self.assertTrue('\U0001F46F'.isprintable())
673 self.assertFalse('\U000E0020'.isprintable())
674
675 def test_surrogates(self):
676 for s in ('a\uD800b\uDFFF', 'a\uDFFFb\uD800',
677 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
678 self.assertTrue(s.islower())
679 self.assertFalse(s.isupper())
680 self.assertFalse(s.istitle())
681 for s in ('A\uD800B\uDFFF', 'A\uDFFFB\uD800',
682 'A\uD800B\uDFFFA', 'A\uDFFFB\uD800A'):
683 self.assertFalse(s.islower())
684 self.assertTrue(s.isupper())
685 self.assertTrue(s.istitle())
686
687 for meth_name in ('islower', 'isupper', 'istitle'):
688 meth = getattr(str, meth_name)
689 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF'):
690 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
691
692 for meth_name in ('isalpha', 'isalnum', 'isdigit', 'isspace',
693 'isdecimal', 'isnumeric',
694 'isidentifier', 'isprintable'):
695 meth = getattr(str, meth_name)
696 for s in ('\uD800', '\uDFFF', '\uD800\uD800', '\uDFFF\uDFFF',
697 'a\uD800b\uDFFF', 'a\uDFFFb\uD800',
698 'a\uD800b\uDFFFa', 'a\uDFFFb\uD800a'):
699 self.assertFalse(meth(s), '%a.%s() is False' % (s, meth_name))
700
701
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300702 def test_lower(self):
703 string_tests.CommonTest.test_lower(self)
704 self.assertEqual('\U00010427'.lower(), '\U0001044F')
705 self.assertEqual('\U00010427\U00010427'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300706 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300707 self.assertEqual('\U00010427\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300708 '\U0001044F\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300709 self.assertEqual('X\U00010427x\U0001044F'.lower(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300710 'x\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500711 self.assertEqual('fi'.lower(), 'fi')
712 self.assertEqual('\u0130'.lower(), '\u0069\u0307')
713 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
714 self.assertEqual('\u03a3'.lower(), '\u03c3')
715 self.assertEqual('\u0345\u03a3'.lower(), '\u0345\u03c3')
716 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
717 self.assertEqual('A\u0345\u03a3a'.lower(), 'a\u0345\u03c3a')
718 self.assertEqual('A\u0345\u03a3'.lower(), 'a\u0345\u03c2')
719 self.assertEqual('A\u03a3\u0345'.lower(), 'a\u03c2\u0345')
720 self.assertEqual('\u03a3\u0345 '.lower(), '\u03c3\u0345 ')
721 self.assertEqual('\U0008fffe'.lower(), '\U0008fffe')
722 self.assertEqual('\u2177'.lower(), '\u2177')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300723
Benjamin Petersond5890c82012-01-14 13:23:30 -0500724 def test_casefold(self):
725 self.assertEqual('hello'.casefold(), 'hello')
726 self.assertEqual('hELlo'.casefold(), 'hello')
727 self.assertEqual('ß'.casefold(), 'ss')
728 self.assertEqual('fi'.casefold(), 'fi')
729 self.assertEqual('\u03a3'.casefold(), '\u03c3')
730 self.assertEqual('A\u0345\u03a3'.casefold(), 'a\u03b9\u03c3')
Benjamin Peterson4eda9372012-08-05 15:05:34 -0700731 self.assertEqual('\u00b5'.casefold(), '\u03bc')
Benjamin Petersond5890c82012-01-14 13:23:30 -0500732
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300733 def test_upper(self):
734 string_tests.CommonTest.test_upper(self)
735 self.assertEqual('\U0001044F'.upper(), '\U00010427')
736 self.assertEqual('\U0001044F\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300737 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300738 self.assertEqual('\U00010427\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300739 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300740 self.assertEqual('X\U00010427x\U0001044F'.upper(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300741 'X\U00010427X\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500742 self.assertEqual('fi'.upper(), 'FI')
743 self.assertEqual('\u0130'.upper(), '\u0130')
744 self.assertEqual('\u03a3'.upper(), '\u03a3')
745 self.assertEqual('ß'.upper(), 'SS')
746 self.assertEqual('\u1fd2'.upper(), '\u0399\u0308\u0300')
747 self.assertEqual('\U0008fffe'.upper(), '\U0008fffe')
748 self.assertEqual('\u2177'.upper(), '\u2167')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300749
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300750 def test_capitalize(self):
751 string_tests.CommonTest.test_capitalize(self)
752 self.assertEqual('\U0001044F'.capitalize(), '\U00010427')
753 self.assertEqual('\U0001044F\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300754 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300755 self.assertEqual('\U00010427\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300756 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300757 self.assertEqual('\U0001044F\U00010427'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300758 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300759 self.assertEqual('X\U00010427x\U0001044F'.capitalize(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300760 'X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500761 self.assertEqual('h\u0130'.capitalize(), 'H\u0069\u0307')
762 exp = '\u0399\u0308\u0300\u0069\u0307'
763 self.assertEqual('\u1fd2\u0130'.capitalize(), exp)
764 self.assertEqual('finnish'.capitalize(), 'FInnish')
765 self.assertEqual('A\u0345\u03a3'.capitalize(), 'A\u0345\u03c2')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300766
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300767 def test_title(self):
768 string_tests.MixinStrUnicodeUserStringTest.test_title(self)
769 self.assertEqual('\U0001044F'.title(), '\U00010427')
770 self.assertEqual('\U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300771 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300772 self.assertEqual('\U0001044F\U0001044F \U0001044F\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300773 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300774 self.assertEqual('\U00010427\U0001044F \U00010427\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300775 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300776 self.assertEqual('\U0001044F\U00010427 \U0001044F\U00010427'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300777 '\U00010427\U0001044F \U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300778 self.assertEqual('X\U00010427x\U0001044F X\U00010427x\U0001044F'.title(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300779 'X\U0001044Fx\U0001044F X\U0001044Fx\U0001044F')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500780 self.assertEqual('fiNNISH'.title(), 'Finnish')
781 self.assertEqual('A\u03a3 \u1fa1xy'.title(), 'A\u03c2 \u1fa9xy')
782 self.assertEqual('A\u03a3A'.title(), 'A\u03c3a')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300783
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300784 def test_swapcase(self):
785 string_tests.CommonTest.test_swapcase(self)
786 self.assertEqual('\U0001044F'.swapcase(), '\U00010427')
787 self.assertEqual('\U00010427'.swapcase(), '\U0001044F')
788 self.assertEqual('\U0001044F\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300789 '\U00010427\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300790 self.assertEqual('\U00010427\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300791 '\U0001044F\U00010427')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300792 self.assertEqual('\U0001044F\U00010427'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300793 '\U00010427\U0001044F')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300794 self.assertEqual('X\U00010427x\U0001044F'.swapcase(),
Ezio Melottia5c92b42011-08-23 00:37:08 +0300795 'x\U0001044FX\U00010427')
Benjamin Petersonb2bf01d2012-01-11 18:17:06 -0500796 self.assertEqual('fi'.swapcase(), 'FI')
797 self.assertEqual('\u0130'.swapcase(), '\u0069\u0307')
798 # Special case for GREEK CAPITAL LETTER SIGMA U+03A3
799 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
800 self.assertEqual('\u0345\u03a3'.swapcase(), '\u0399\u03c3')
801 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
802 self.assertEqual('A\u0345\u03a3a'.swapcase(), 'a\u0399\u03c3A')
803 self.assertEqual('A\u0345\u03a3'.swapcase(), 'a\u0399\u03c2')
804 self.assertEqual('A\u03a3\u0345'.swapcase(), 'a\u03c2\u0399')
805 self.assertEqual('\u03a3\u0345 '.swapcase(), '\u03c3\u0399 ')
806 self.assertEqual('\u03a3'.swapcase(), '\u03c3')
807 self.assertEqual('ß'.swapcase(), 'SS')
808 self.assertEqual('\u1fd2'.swapcase(), '\u0399\u0308\u0300')
Ezio Melotti93e7afc2011-08-22 14:08:38 +0300809
Ezio Melottif84e01d2013-07-08 17:48:29 +0200810 def test_center(self):
811 string_tests.CommonTest.test_center(self)
812 self.assertEqual('x'.center(2, '\U0010FFFF'),
813 'x\U0010FFFF')
814 self.assertEqual('x'.center(3, '\U0010FFFF'),
815 '\U0010FFFFx\U0010FFFF')
816 self.assertEqual('x'.center(4, '\U0010FFFF'),
817 '\U0010FFFFx\U0010FFFF\U0010FFFF')
818
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400819 @unittest.skipUnless(sys.maxsize == 2**31 - 1, "requires 32-bit system")
Benjamin Peterson4d856892014-10-15 13:39:46 -0400820 @support.cpython_only
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400821 def test_case_operation_overflow(self):
822 # Issue #22643
Serhiy Storchaka411dfd82015-11-07 16:54:48 +0200823 size = 2**32//12 + 1
824 try:
825 s = "ü" * size
826 except MemoryError:
827 self.skipTest('no enough memory (%.0f MiB required)' % (size / 2**20))
828 try:
829 self.assertRaises(OverflowError, s.upper)
830 finally:
831 del s
Benjamin Petersone1bd38c2014-10-15 11:47:36 -0400832
Walter Dörwald28256f22003-01-19 16:59:20 +0000833 def test_contains(self):
834 # Testing Unicode contains method
Benjamin Peterson577473f2010-01-19 00:09:57 +0000835 self.assertIn('a', 'abdb')
836 self.assertIn('a', 'bdab')
837 self.assertIn('a', 'bdaba')
838 self.assertIn('a', 'bdba')
839 self.assertNotIn('a', 'bdb')
840 self.assertIn('a', 'bdba')
841 self.assertIn('a', ('a',1,None))
842 self.assertIn('a', (1,None,'a'))
843 self.assertIn('a', ('a',1,None))
844 self.assertIn('a', (1,None,'a'))
845 self.assertNotIn('a', ('x',1,'y'))
846 self.assertNotIn('a', ('x',1,None))
847 self.assertNotIn('abcd', 'abcxxxx')
848 self.assertIn('ab', 'abcd')
849 self.assertIn('ab', 'abc')
850 self.assertIn('ab', (1,None,'ab'))
851 self.assertIn('', 'abc')
852 self.assertIn('', '')
853 self.assertIn('', 'abc')
854 self.assertNotIn('\0', 'abc')
855 self.assertIn('\0', '\0abc')
856 self.assertIn('\0', 'abc\0')
857 self.assertIn('a', '\0abc')
858 self.assertIn('asdf', 'asdf')
859 self.assertNotIn('asdf', 'asd')
860 self.assertNotIn('asdf', '')
Walter Dörwald28256f22003-01-19 16:59:20 +0000861
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000862 self.assertRaises(TypeError, "abc".__contains__)
Serhiy Storchakabe1eb142015-03-24 21:48:30 +0200863 # test mixed kinds
864 for fill in ('a', '\u0100', '\U00010300'):
865 fill *= 9
866 for delim in ('c', '\u0102', '\U00010302'):
867 self.assertNotIn(delim, fill)
868 self.assertIn(delim, fill + delim)
869 self.assertNotIn(delim * 2, fill)
870 self.assertIn(delim * 2, fill + delim * 2)
Walter Dörwald28256f22003-01-19 16:59:20 +0000871
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +0300872 def test_issue18183(self):
873 '\U00010000\U00100000'.lower()
874 '\U00010000\U00100000'.casefold()
875 '\U00010000\U00100000'.upper()
876 '\U00010000\U00100000'.capitalize()
877 '\U00010000\U00100000'.title()
878 '\U00010000\U00100000'.swapcase()
879 '\U00100000'.center(3, '\U00010000')
880 '\U00100000'.ljust(3, '\U00010000')
881 '\U00100000'.rjust(3, '\U00010000')
882
Eric Smith8c663262007-08-25 02:26:07 +0000883 def test_format(self):
884 self.assertEqual(''.format(), '')
885 self.assertEqual('a'.format(), 'a')
886 self.assertEqual('ab'.format(), 'ab')
887 self.assertEqual('a{{'.format(), 'a{')
888 self.assertEqual('a}}'.format(), 'a}')
889 self.assertEqual('{{b'.format(), '{b')
890 self.assertEqual('}}b'.format(), '}b')
891 self.assertEqual('a{{b'.format(), 'a{b')
892
893 # examples from the PEP:
894 import datetime
895 self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
896 self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
897 "My name is Fred")
898 self.assertEqual("My name is {0} :-{{}}".format('Fred'),
899 "My name is Fred :-{}")
900
901 d = datetime.date(2007, 8, 18)
902 self.assertEqual("The year is {0.year}".format(d),
903 "The year is 2007")
904
Eric Smith8c663262007-08-25 02:26:07 +0000905 # classes we'll use for testing
906 class C:
907 def __init__(self, x=100):
908 self._x = x
909 def __format__(self, spec):
910 return spec
911
912 class D:
913 def __init__(self, x):
914 self.x = x
915 def __format__(self, spec):
916 return str(self.x)
917
918 # class with __str__, but no __format__
919 class E:
920 def __init__(self, x):
921 self.x = x
922 def __str__(self):
923 return 'E(' + self.x + ')'
924
925 # class with __repr__, but no __format__ or __str__
926 class F:
927 def __init__(self, x):
928 self.x = x
929 def __repr__(self):
930 return 'F(' + self.x + ')'
931
932 # class with __format__ that forwards to string, for some format_spec's
933 class G:
934 def __init__(self, x):
935 self.x = x
936 def __str__(self):
937 return "string is " + self.x
938 def __format__(self, format_spec):
939 if format_spec == 'd':
940 return 'G(' + self.x + ')'
941 return object.__format__(self, format_spec)
942
Eric Smith739e2ad2007-08-27 19:07:22 +0000943 class I(datetime.date):
944 def __format__(self, format_spec):
945 return self.strftime(format_spec)
946
Eric Smith185e30c2007-08-30 22:23:08 +0000947 class J(int):
948 def __format__(self, format_spec):
949 return int.__format__(self * 2, format_spec)
950
Eric Smith8c663262007-08-25 02:26:07 +0000951
952 self.assertEqual(''.format(), '')
953 self.assertEqual('abc'.format(), 'abc')
954 self.assertEqual('{0}'.format('abc'), 'abc')
955 self.assertEqual('{0:}'.format('abc'), 'abc')
956# self.assertEqual('{ 0 }'.format('abc'), 'abc')
957 self.assertEqual('X{0}'.format('abc'), 'Xabc')
958 self.assertEqual('{0}X'.format('abc'), 'abcX')
959 self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
960 self.assertEqual('{1}'.format(1, 'abc'), 'abc')
961 self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
962 self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
963 self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
964 self.assertEqual('{0}'.format(-15), '-15')
965 self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
966 self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
967 self.assertEqual('{{'.format(), '{')
968 self.assertEqual('}}'.format(), '}')
969 self.assertEqual('{{}}'.format(), '{}')
970 self.assertEqual('{{x}}'.format(), '{x}')
971 self.assertEqual('{{{0}}}'.format(123), '{123}')
972 self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
973 self.assertEqual('}}{{'.format(), '}{')
974 self.assertEqual('}}x{{'.format(), '}x{')
975
Eric Smith7ade6482007-08-26 22:27:13 +0000976 # weird field names
977 self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
978 self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
Eric Smith4cb4e4e2007-09-03 08:40:29 +0000979 self.assertEqual("{0[ ]}".format({' ':3}), '3')
Eric Smith7ade6482007-08-26 22:27:13 +0000980
Eric Smith8c663262007-08-25 02:26:07 +0000981 self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
982 self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
983 self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
984 self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
985 self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
986 self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
987 self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
988
Eric Smith8c663262007-08-25 02:26:07 +0000989 # strings
990 self.assertEqual('{0:.3s}'.format('abc'), 'abc')
991 self.assertEqual('{0:.3s}'.format('ab'), 'ab')
992 self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
993 self.assertEqual('{0:.0s}'.format('abcdef'), '')
994 self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
995 self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
996 self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
997 self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
998 self.assertEqual('{0:x<0s}'.format('result'), 'result')
999 self.assertEqual('{0:x<5s}'.format('result'), 'result')
1000 self.assertEqual('{0:x<6s}'.format('result'), 'result')
1001 self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
1002 self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
1003 self.assertEqual('{0: <7s}'.format('result'), 'result ')
1004 self.assertEqual('{0:<7s}'.format('result'), 'result ')
1005 self.assertEqual('{0:>7s}'.format('result'), ' result')
1006 self.assertEqual('{0:>8s}'.format('result'), ' result')
1007 self.assertEqual('{0:^8s}'.format('result'), ' result ')
1008 self.assertEqual('{0:^9s}'.format('result'), ' result ')
1009 self.assertEqual('{0:^10s}'.format('result'), ' result ')
1010 self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
1011 self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
1012 self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
1013
Eric V. Smith2ea97122014-04-14 11:55:10 -04001014 # issue 12546: use \x00 as a fill character
1015 self.assertEqual('{0:\x00<6s}'.format('foo'), 'foo\x00\x00\x00')
1016 self.assertEqual('{0:\x01<6s}'.format('foo'), 'foo\x01\x01\x01')
1017 self.assertEqual('{0:\x00^6s}'.format('foo'), '\x00foo\x00\x00')
1018 self.assertEqual('{0:^6s}'.format('foo'), ' foo ')
1019
1020 self.assertEqual('{0:\x00<6}'.format(3), '3\x00\x00\x00\x00\x00')
1021 self.assertEqual('{0:\x01<6}'.format(3), '3\x01\x01\x01\x01\x01')
1022 self.assertEqual('{0:\x00^6}'.format(3), '\x00\x003\x00\x00\x00')
1023 self.assertEqual('{0:<6}'.format(3), '3 ')
1024
1025 self.assertEqual('{0:\x00<6}'.format(3.14), '3.14\x00\x00')
1026 self.assertEqual('{0:\x01<6}'.format(3.14), '3.14\x01\x01')
1027 self.assertEqual('{0:\x00^6}'.format(3.14), '\x003.14\x00')
1028 self.assertEqual('{0:^6}'.format(3.14), ' 3.14 ')
1029
1030 self.assertEqual('{0:\x00<12}'.format(3+2.0j), '(3+2j)\x00\x00\x00\x00\x00\x00')
1031 self.assertEqual('{0:\x01<12}'.format(3+2.0j), '(3+2j)\x01\x01\x01\x01\x01\x01')
1032 self.assertEqual('{0:\x00^12}'.format(3+2.0j), '\x00\x00\x00(3+2j)\x00\x00\x00')
1033 self.assertEqual('{0:^12}'.format(3+2.0j), ' (3+2j) ')
1034
Eric Smith8c663262007-08-25 02:26:07 +00001035 # format specifiers for user defined type
1036 self.assertEqual('{0:abc}'.format(C()), 'abc')
1037
Georg Brandld52429f2008-07-04 15:55:02 +00001038 # !r, !s and !a coercions
Eric Smith8c663262007-08-25 02:26:07 +00001039 self.assertEqual('{0!s}'.format('Hello'), 'Hello')
1040 self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
1041 self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
1042 self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
1043 self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
1044 self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
1045 self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001046 self.assertEqual('{0!r}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001047 self.assertEqual('{0!r}'.format('\u0374'), "'\u0374'") # printable
1048 self.assertEqual('{0!r}'.format(F('\u0374')), 'F(\u0374)')
Georg Brandl559e5d72008-06-11 18:37:52 +00001049 self.assertEqual('{0!a}'.format('Hello'), "'Hello'")
Amaury Forgeot d'Arca083f1e2008-09-10 23:51:42 +00001050 self.assertEqual('{0!a}'.format('\u0378'), "'\\u0378'") # nonprintable
Georg Brandld52429f2008-07-04 15:55:02 +00001051 self.assertEqual('{0!a}'.format('\u0374'), "'\\u0374'") # printable
Georg Brandl559e5d72008-06-11 18:37:52 +00001052 self.assertEqual('{0!a:}'.format('Hello'), "'Hello'")
1053 self.assertEqual('{0!a}'.format(F('Hello')), 'F(Hello)')
Georg Brandld52429f2008-07-04 15:55:02 +00001054 self.assertEqual('{0!a}'.format(F('\u0374')), 'F(\\u0374)')
Eric Smith8c663262007-08-25 02:26:07 +00001055
Eric Smith8c663262007-08-25 02:26:07 +00001056 # test fallback to object.__format__
1057 self.assertEqual('{0}'.format({}), '{}')
1058 self.assertEqual('{0}'.format([]), '[]')
1059 self.assertEqual('{0}'.format([1]), '[1]')
Eric Smithe4d63172010-09-13 20:48:43 +00001060
Eric Smith8c663262007-08-25 02:26:07 +00001061 self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
Eric Smith8c663262007-08-25 02:26:07 +00001062 self.assertEqual('{0!s}'.format(G('data')), 'string is data')
1063
Andrew Svetlov2cd8ce42012-12-23 14:27:17 +02001064 self.assertRaises(TypeError, '{0:^10}'.format, E('data'))
1065 self.assertRaises(TypeError, '{0:^10s}'.format, E('data'))
1066 self.assertRaises(TypeError, '{0:>15s}'.format, G('data'))
Eric Smithe4d63172010-09-13 20:48:43 +00001067
Eric Smith739e2ad2007-08-27 19:07:22 +00001068 self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
1069 month=8,
1070 day=27)),
1071 "date: 2007-08-27")
1072
Eric Smith185e30c2007-08-30 22:23:08 +00001073 # test deriving from a builtin type and overriding __format__
1074 self.assertEqual("{0}".format(J(10)), "20")
1075
1076
Eric Smith8c663262007-08-25 02:26:07 +00001077 # string format specifiers
1078 self.assertEqual('{0:}'.format('a'), 'a')
1079
1080 # computed format specifiers
1081 self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
1082 self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
1083 self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
1084 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
1085 self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
1086
1087 # test various errors
1088 self.assertRaises(ValueError, '{'.format)
1089 self.assertRaises(ValueError, '}'.format)
1090 self.assertRaises(ValueError, 'a{'.format)
1091 self.assertRaises(ValueError, 'a}'.format)
1092 self.assertRaises(ValueError, '{a'.format)
1093 self.assertRaises(ValueError, '}a'.format)
Eric Smith11529192007-09-04 23:04:22 +00001094 self.assertRaises(IndexError, '{0}'.format)
1095 self.assertRaises(IndexError, '{1}'.format, 'abc')
1096 self.assertRaises(KeyError, '{x}'.format)
Eric Smith8c663262007-08-25 02:26:07 +00001097 self.assertRaises(ValueError, "}{".format)
Eric Smith8c663262007-08-25 02:26:07 +00001098 self.assertRaises(ValueError, "abc{0:{}".format)
1099 self.assertRaises(ValueError, "{0".format)
Eric Smith11529192007-09-04 23:04:22 +00001100 self.assertRaises(IndexError, "{0.}".format)
1101 self.assertRaises(ValueError, "{0.}".format, 0)
Benjamin Peterson4d944742013-05-17 18:22:31 -05001102 self.assertRaises(ValueError, "{0[}".format)
Eric Smith4cb4e4e2007-09-03 08:40:29 +00001103 self.assertRaises(ValueError, "{0[}".format, [])
Eric Smith11529192007-09-04 23:04:22 +00001104 self.assertRaises(KeyError, "{0]}".format)
1105 self.assertRaises(ValueError, "{0.[]}".format, 0)
Eric Smith7ade6482007-08-26 22:27:13 +00001106 self.assertRaises(ValueError, "{0..foo}".format, 0)
Eric Smith11529192007-09-04 23:04:22 +00001107 self.assertRaises(ValueError, "{0[0}".format, 0)
1108 self.assertRaises(ValueError, "{0[0:foo}".format, 0)
1109 self.assertRaises(KeyError, "{c]}".format)
1110 self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
1111 self.assertRaises(ValueError, "{0}}".format, 0)
1112 self.assertRaises(KeyError, "{foo}".format, bar=3)
Eric Smith8c663262007-08-25 02:26:07 +00001113 self.assertRaises(ValueError, "{0!x}".format, 3)
Eric Smith11529192007-09-04 23:04:22 +00001114 self.assertRaises(ValueError, "{0!}".format, 0)
1115 self.assertRaises(ValueError, "{0!rs}".format, 0)
Eric Smith8c663262007-08-25 02:26:07 +00001116 self.assertRaises(ValueError, "{!}".format)
Eric Smith8ec90442009-03-14 12:29:34 +00001117 self.assertRaises(IndexError, "{:}".format)
1118 self.assertRaises(IndexError, "{:s}".format)
1119 self.assertRaises(IndexError, "{}".format)
Benjamin Peterson59a1b2f2010-06-07 22:31:26 +00001120 big = "23098475029384702983476098230754973209482573"
1121 self.assertRaises(ValueError, ("{" + big + "}").format)
1122 self.assertRaises(ValueError, ("{[" + big + "]}").format, [0])
Eric Smith8c663262007-08-25 02:26:07 +00001123
Eric Smith41669ca2009-05-23 14:23:22 +00001124 # issue 6089
1125 self.assertRaises(ValueError, "{0[0]x}".format, [None])
1126 self.assertRaises(ValueError, "{0[0](10)}".format, [None])
1127
Eric Smith8c663262007-08-25 02:26:07 +00001128 # can't have a replacement on the field name portion
1129 self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
1130
1131 # exceed maximum recursion depth
1132 self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
1133 self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
1134 0, 1, 2, 3, 4, 5, 6, 7)
1135
1136 # string format spec errors
1137 self.assertRaises(ValueError, "{0:-s}".format, '')
1138 self.assertRaises(ValueError, format, "", "-")
1139 self.assertRaises(ValueError, "{0:=s}".format, '')
1140
Eric Smithb1ebcc62008-07-15 13:02:41 +00001141 # Alternate formatting is not supported
1142 self.assertRaises(ValueError, format, '', '#')
1143 self.assertRaises(ValueError, format, '', '#20')
1144
Victor Stinnerece58de2012-04-23 23:36:38 +02001145 # Non-ASCII
1146 self.assertEqual("{0:s}{1:s}".format("ABC", "\u0410\u0411\u0412"),
1147 'ABC\u0410\u0411\u0412')
1148 self.assertEqual("{0:.3s}".format("ABC\u0410\u0411\u0412"),
1149 'ABC')
1150 self.assertEqual("{0:.0s}".format("ABC\u0410\u0411\u0412"),
1151 '')
1152
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001153 self.assertEqual("{[{}]}".format({"{}": 5}), "5")
Benjamin Peterson4d944742013-05-17 18:22:31 -05001154 self.assertEqual("{[{}]}".format({"{}" : "a"}), "a")
1155 self.assertEqual("{[{]}".format({"{" : "a"}), "a")
1156 self.assertEqual("{[}]}".format({"}" : "a"}), "a")
1157 self.assertEqual("{[[]}".format({"[" : "a"}), "a")
1158 self.assertEqual("{[!]}".format({"!" : "a"}), "a")
1159 self.assertRaises(ValueError, "{a{}b}".format, 42)
1160 self.assertRaises(ValueError, "{a{b}".format, 42)
1161 self.assertRaises(ValueError, "{[}".format, 42)
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001162
Benjamin Peterson0ee22bf2013-11-26 19:22:36 -06001163 self.assertEqual("0x{:0{:d}X}".format(0x0,16), "0x0000000000000000")
Benjamin Petersond2b58a92013-05-17 17:34:30 -05001164
Eric Smith27bbca62010-11-04 17:06:58 +00001165 def test_format_map(self):
1166 self.assertEqual(''.format_map({}), '')
1167 self.assertEqual('a'.format_map({}), 'a')
1168 self.assertEqual('ab'.format_map({}), 'ab')
1169 self.assertEqual('a{{'.format_map({}), 'a{')
1170 self.assertEqual('a}}'.format_map({}), 'a}')
1171 self.assertEqual('{{b'.format_map({}), '{b')
1172 self.assertEqual('}}b'.format_map({}), '}b')
1173 self.assertEqual('a{{b'.format_map({}), 'a{b')
1174
1175 # using mappings
1176 class Mapping(dict):
1177 def __missing__(self, key):
1178 return key
1179 self.assertEqual('{hello}'.format_map(Mapping()), 'hello')
1180 self.assertEqual('{a} {world}'.format_map(Mapping(a='hello')), 'hello world')
1181
1182 class InternalMapping:
1183 def __init__(self):
1184 self.mapping = {'a': 'hello'}
1185 def __getitem__(self, key):
1186 return self.mapping[key]
1187 self.assertEqual('{a}'.format_map(InternalMapping()), 'hello')
1188
1189
Eric Smith27bbca62010-11-04 17:06:58 +00001190 class C:
1191 def __init__(self, x=100):
1192 self._x = x
1193 def __format__(self, spec):
1194 return spec
Eric Smith27bbca62010-11-04 17:06:58 +00001195 self.assertEqual('{foo._x}'.format_map({'foo': C(20)}), '20')
1196
1197 # test various errors
Eric V. Smithedbb6ca2012-03-12 15:16:22 -07001198 self.assertRaises(TypeError, ''.format_map)
1199 self.assertRaises(TypeError, 'a'.format_map)
1200
1201 self.assertRaises(ValueError, '{'.format_map, {})
1202 self.assertRaises(ValueError, '}'.format_map, {})
1203 self.assertRaises(ValueError, 'a{'.format_map, {})
1204 self.assertRaises(ValueError, 'a}'.format_map, {})
1205 self.assertRaises(ValueError, '{a'.format_map, {})
1206 self.assertRaises(ValueError, '}a'.format_map, {})
Eric Smith27bbca62010-11-04 17:06:58 +00001207
Eric V. Smith12ebefc2011-07-18 14:03:41 -04001208 # issue #12579: can't supply positional params to format_map
1209 self.assertRaises(ValueError, '{}'.format_map, {'a' : 2})
1210 self.assertRaises(ValueError, '{}'.format_map, 'a')
1211 self.assertRaises(ValueError, '{a} {}'.format_map, {"a" : 2, "b" : 1})
1212
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001213 def test_format_huge_precision(self):
1214 format_string = ".{}f".format(sys.maxsize + 1)
1215 with self.assertRaises(ValueError):
1216 result = format(2.34, format_string)
1217
1218 def test_format_huge_width(self):
1219 format_string = "{}f".format(sys.maxsize + 1)
1220 with self.assertRaises(ValueError):
1221 result = format(2.34, format_string)
1222
1223 def test_format_huge_item_number(self):
1224 format_string = "{{{}:.6f}}".format(sys.maxsize + 1)
1225 with self.assertRaises(ValueError):
1226 result = format_string.format(2.34)
1227
Eric Smith8ec90442009-03-14 12:29:34 +00001228 def test_format_auto_numbering(self):
1229 class C:
1230 def __init__(self, x=100):
1231 self._x = x
1232 def __format__(self, spec):
1233 return spec
1234
1235 self.assertEqual('{}'.format(10), '10')
1236 self.assertEqual('{:5}'.format('s'), 's ')
1237 self.assertEqual('{!r}'.format('s'), "'s'")
1238 self.assertEqual('{._x}'.format(C(10)), '10')
1239 self.assertEqual('{[1]}'.format([1, 2]), '2')
1240 self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
1241 self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')
1242
1243 self.assertEqual('a{:{}}b'.format('x', '^10'), 'a x b')
1244 self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')
1245
1246 # can't mix and match numbering and auto-numbering
1247 self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
1248 self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
1249 self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
1250 self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)
1251
1252 # can mix and match auto-numbering and named
1253 self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
1254 self.assertEqual('{}{f}'.format(4, f='test'), '4test')
1255 self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
1256 self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
1257
Walter Dörwald28256f22003-01-19 16:59:20 +00001258 def test_formatting(self):
Walter Dörwald0fd583c2003-02-21 12:53:50 +00001259 string_tests.MixinStrUnicodeUserStringTest.test_formatting(self)
Walter Dörwald28256f22003-01-19 16:59:20 +00001260 # Testing Unicode formatting strings...
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001261 self.assertEqual("%s, %s" % ("abc", "abc"), 'abc, abc')
1262 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, 2, 3), 'abc, abc, 1, 2.000000, 3.00')
1263 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", 1, -2, 3), 'abc, abc, 1, -2.000000, 3.00')
1264 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.5), 'abc, abc, -1, -2.000000, 3.50')
1265 self.assertEqual("%s, %s, %i, %f, %5.2f" % ("abc", "abc", -1, -2, 3.57), 'abc, abc, -1, -2.000000, 3.57')
1266 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 +00001267 if not sys.platform.startswith('java'):
Walter Dörwald67e83882007-05-05 12:26:27 +00001268 self.assertEqual("%r, %r" % (b"abc", "abc"), "b'abc', 'abc'")
Georg Brandl559e5d72008-06-11 18:37:52 +00001269 self.assertEqual("%r" % ("\u1234",), "'\u1234'")
1270 self.assertEqual("%a" % ("\u1234",), "'\\u1234'")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001271 self.assertEqual("%(x)s, %(y)s" % {'x':"abc", 'y':"def"}, 'abc, def')
1272 self.assertEqual("%(x)s, %(\xfc)s" % {'x':"abc", '\xfc':"def"}, 'abc, def')
Walter Dörwald56fbcb52003-03-31 18:18:41 +00001273
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001274 self.assertEqual('%c' % 0x1234, '\u1234')
Amaury Forgeot d'Arca4db6862008-07-04 21:26:43 +00001275 self.assertEqual('%c' % 0x21483, '\U00021483')
1276 self.assertRaises(OverflowError, "%c".__mod__, (0x110000,))
1277 self.assertEqual('%c' % '\U00021483', '\U00021483')
1278 self.assertRaises(TypeError, "%c".__mod__, "aa")
Stefan Krah99212f62010-07-19 17:58:26 +00001279 self.assertRaises(ValueError, "%.1\u1032f".__mod__, (1.0/3))
Senthil Kumaran9ebe08d2011-07-03 21:03:16 -07001280 self.assertRaises(TypeError, "%i".__mod__, "aa")
Walter Dörwald28256f22003-01-19 16:59:20 +00001281
1282 # formatting jobs delegated from the string implementation:
Walter Dörwald28256f22003-01-19 16:59:20 +00001283 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001284 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1285 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1286 self.assertEqual('...%(foo)s...' % {'foo':"abc"}, '...abc...')
1287 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1288 self.assertEqual('...%(foo)s...' % {'foo':"abc",'def':123}, '...abc...')
1289 self.assertEqual('...%s...%s...%s...%s...' % (1,2,3,"abc"), '...1...2...3...abc...')
1290 self.assertEqual('...%%...%%s...%s...%s...%s...%s...' % (1,2,3,"abc"), '...%...%s...1...2...3...abc...')
1291 self.assertEqual('...%s...' % "abc", '...abc...')
1292 self.assertEqual('%*s' % (5,'abc',), ' abc')
1293 self.assertEqual('%*s' % (-5,'abc',), 'abc ')
1294 self.assertEqual('%*.*s' % (5,2,'abc',), ' ab')
1295 self.assertEqual('%*.*s' % (5,3,'abc',), ' abc')
1296 self.assertEqual('%i %*.*s' % (10, 5,3,'abc',), '10 abc')
1297 self.assertEqual('%i%s %*.*s' % (10, 3, 5, 3, 'abc',), '103 abc')
1298 self.assertEqual('%c' % 'a', 'a')
Neil Schemenauercf52c072005-08-12 17:34:58 +00001299 class Wrapper:
1300 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001301 return '\u1234'
1302 self.assertEqual('%s' % Wrapper(), '\u1234')
Walter Dörwald28256f22003-01-19 16:59:20 +00001303
Eric Smith741191f2009-05-06 13:08:15 +00001304 # issue 3382
1305 NAN = float('nan')
1306 INF = float('inf')
1307 self.assertEqual('%f' % NAN, 'nan')
1308 self.assertEqual('%F' % NAN, 'NAN')
1309 self.assertEqual('%f' % INF, 'inf')
1310 self.assertEqual('%F' % INF, 'INF')
1311
Victor Stinnerf59c28c2012-05-09 03:24:14 +02001312 # PEP 393
1313 self.assertEqual('%.1s' % "a\xe9\u20ac", 'a')
1314 self.assertEqual('%.2s' % "a\xe9\u20ac", 'a\xe9')
1315
Ethan Furmandf3ed242014-01-05 06:50:30 -08001316 #issue 19995
1317 class PsuedoInt:
1318 def __init__(self, value):
1319 self.value = int(value)
1320 def __int__(self):
1321 return self.value
1322 def __index__(self):
1323 return self.value
1324 class PsuedoFloat:
1325 def __init__(self, value):
1326 self.value = float(value)
1327 def __int__(self):
1328 return int(self.value)
1329 pi = PsuedoFloat(3.1415)
1330 letter_m = PsuedoInt(109)
Antoine Pitroueb168042014-01-10 00:02:38 +01001331 self.assertEqual('%x' % 42, '2a')
1332 self.assertEqual('%X' % 15, 'F')
1333 self.assertEqual('%o' % 9, '11')
1334 self.assertEqual('%c' % 109, 'm')
1335 self.assertEqual('%x' % letter_m, '6d')
1336 self.assertEqual('%X' % letter_m, '6D')
1337 self.assertEqual('%o' % letter_m, '155')
1338 self.assertEqual('%c' % letter_m, 'm')
Ethan Furmana70805e2014-01-12 08:42:35 -08001339 self.assertWarns(DeprecationWarning, '%x'.__mod__, pi),
1340 self.assertWarns(DeprecationWarning, '%x'.__mod__, 3.14),
1341 self.assertWarns(DeprecationWarning, '%X'.__mod__, 2.11),
1342 self.assertWarns(DeprecationWarning, '%o'.__mod__, 1.79),
1343 self.assertWarns(DeprecationWarning, '%c'.__mod__, pi),
Ethan Furmandf3ed242014-01-05 06:50:30 -08001344
Ethan Furmanfb137212013-08-31 10:18:55 -07001345 def test_formatting_with_enum(self):
1346 # issue18780
1347 import enum
1348 class Float(float, enum.Enum):
1349 PI = 3.1415926
1350 class Int(enum.IntEnum):
1351 IDES = 15
1352 class Str(str, enum.Enum):
1353 ABC = 'abc'
1354 # Testing Unicode formatting strings...
Ethan Furman13bdfa72013-08-31 12:48:51 -07001355 self.assertEqual("%s, %s" % (Str.ABC, Str.ABC),
1356 'Str.ABC, Str.ABC')
1357 self.assertEqual("%s, %s, %d, %i, %u, %f, %5.2f" %
1358 (Str.ABC, Str.ABC,
1359 Int.IDES, Int.IDES, Int.IDES,
1360 Float.PI, Float.PI),
1361 'Str.ABC, Str.ABC, 15, 15, 15, 3.141593, 3.14')
Ethan Furmanfb137212013-08-31 10:18:55 -07001362
1363 # formatting jobs delegated from the string implementation:
Ethan Furman13bdfa72013-08-31 12:48:51 -07001364 self.assertEqual('...%(foo)s...' % {'foo':Str.ABC},
1365 '...Str.ABC...')
1366 self.assertEqual('...%(foo)s...' % {'foo':Int.IDES},
1367 '...Int.IDES...')
1368 self.assertEqual('...%(foo)i...' % {'foo':Int.IDES},
1369 '...15...')
1370 self.assertEqual('...%(foo)d...' % {'foo':Int.IDES},
1371 '...15...')
1372 self.assertEqual('...%(foo)u...' % {'foo':Int.IDES, 'def':Float.PI},
1373 '...15...')
1374 self.assertEqual('...%(foo)f...' % {'foo':Float.PI,'def':123},
1375 '...3.141593...')
Ethan Furmanfb137212013-08-31 10:18:55 -07001376
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001377 def test_formatting_huge_precision(self):
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001378 format_string = "%.{}f".format(sys.maxsize + 1)
1379 with self.assertRaises(ValueError):
1380 result = format_string % 2.34
1381
1382 @support.cpython_only
1383 def test_formatting_huge_precision_c_limits(self):
Mark Dickinsonfb90c092012-10-28 10:18:03 +00001384 from _testcapi import INT_MAX
1385 format_string = "%.{}f".format(INT_MAX + 1)
1386 with self.assertRaises(ValueError):
1387 result = format_string % 2.34
1388
1389 def test_formatting_huge_width(self):
1390 format_string = "%{}f".format(sys.maxsize + 1)
1391 with self.assertRaises(ValueError):
1392 result = format_string % 2.34
1393
Ezio Melottiba42fd52011-04-26 06:09:45 +03001394 def test_startswith_endswith_errors(self):
1395 for meth in ('foo'.startswith, 'foo'.endswith):
Ezio Melottif2b3f782011-04-26 06:40:59 +03001396 with self.assertRaises(TypeError) as cm:
Ezio Melottiba42fd52011-04-26 06:09:45 +03001397 meth(['f'])
Ezio Melottif2b3f782011-04-26 06:40:59 +03001398 exc = str(cm.exception)
Ezio Melottiba42fd52011-04-26 06:09:45 +03001399 self.assertIn('str', exc)
1400 self.assertIn('tuple', exc)
1401
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001402 @support.run_with_locale('LC_ALL', 'de_DE', 'fr_FR')
Georg Brandlda6b1072006-01-20 17:48:54 +00001403 def test_format_float(self):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001404 # should not format with a comma, but always with C locale
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001405 self.assertEqual('1.0', '%.1f' % 1.0)
Georg Brandlda6b1072006-01-20 17:48:54 +00001406
Walter Dörwald28256f22003-01-19 16:59:20 +00001407 def test_constructor(self):
1408 # unicode(obj) tests (this maps to PyObject_Unicode() at C level)
1409
1410 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001411 str('unicode remains unicode'),
1412 'unicode remains unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001413 )
1414
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001415 class UnicodeSubclass(str):
Marc-André Lemburg79f57832002-12-29 19:44:06 +00001416 pass
Guido van Rossuma831cac2000-03-10 23:23:21 +00001417
Victor Stinner07ac3eb2011-10-01 16:16:43 +02001418 for text in ('ascii', '\xe9', '\u20ac', '\U0010FFFF'):
1419 subclass = UnicodeSubclass(text)
1420 self.assertEqual(str(subclass), text)
1421 self.assertEqual(len(subclass), len(text))
1422 if text == 'ascii':
1423 self.assertEqual(subclass.encode('ascii'), b'ascii')
1424 self.assertEqual(subclass.encode('utf-8'), b'ascii')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001425
Walter Dörwald28256f22003-01-19 16:59:20 +00001426 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001427 str('strings are converted to unicode'),
1428 'strings are converted to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001429 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001430
Walter Dörwald28256f22003-01-19 16:59:20 +00001431 class StringCompat:
1432 def __init__(self, x):
1433 self.x = x
1434 def __str__(self):
1435 return self.x
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001436
Walter Dörwald28256f22003-01-19 16:59:20 +00001437 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001438 str(StringCompat('__str__ compatible objects are recognized')),
1439 '__str__ compatible objects are recognized'
Walter Dörwald28256f22003-01-19 16:59:20 +00001440 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001441
Walter Dörwald28256f22003-01-19 16:59:20 +00001442 # unicode(obj) is compatible to str():
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001443
Walter Dörwald28256f22003-01-19 16:59:20 +00001444 o = StringCompat('unicode(obj) is compatible to str()')
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001445 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Walter Dörwald28256f22003-01-19 16:59:20 +00001446 self.assertEqual(str(o), 'unicode(obj) is compatible to str()')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001447
Guido van Rossume2a383d2007-01-15 16:59:06 +00001448 for obj in (123, 123.45, 123):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001449 self.assertEqual(str(obj), str(str(obj)))
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001450
Walter Dörwald28256f22003-01-19 16:59:20 +00001451 # unicode(obj, encoding, error) tests (this maps to
1452 # PyUnicode_FromEncodedObject() at C level)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001453
Walter Dörwald28256f22003-01-19 16:59:20 +00001454 if not sys.platform.startswith('java'):
1455 self.assertRaises(
1456 TypeError,
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001457 str,
1458 'decoding unicode is not supported',
Walter Dörwald28256f22003-01-19 16:59:20 +00001459 'utf-8',
1460 'strict'
1461 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001462
Walter Dörwald28256f22003-01-19 16:59:20 +00001463 self.assertEqual(
Walter Dörwald67e83882007-05-05 12:26:27 +00001464 str(b'strings are decoded to unicode', 'utf-8', 'strict'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001465 'strings are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001466 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001467
Walter Dörwald28256f22003-01-19 16:59:20 +00001468 if not sys.platform.startswith('java'):
1469 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001470 str(
Guido van Rossumbae07c92007-10-08 02:46:15 +00001471 memoryview(b'character buffers are decoded to unicode'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001472 'utf-8',
1473 'strict'
1474 ),
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001475 'character buffers are decoded to unicode'
Walter Dörwald28256f22003-01-19 16:59:20 +00001476 )
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001477
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001478 self.assertRaises(TypeError, str, 42, 42, 42)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001479
Chris Jerdonek5fae0e52012-11-20 17:45:51 -08001480 def test_constructor_keyword_args(self):
1481 """Pass various keyword argument combinations to the constructor."""
1482 # The object argument can be passed as a keyword.
1483 self.assertEqual(str(object='foo'), 'foo')
1484 self.assertEqual(str(object=b'foo', encoding='utf-8'), 'foo')
1485 # The errors argument without encoding triggers "decode" mode.
1486 self.assertEqual(str(b'foo', errors='strict'), 'foo') # not "b'foo'"
1487 self.assertEqual(str(object=b'foo', errors='strict'), 'foo')
1488
1489 def test_constructor_defaults(self):
1490 """Check the constructor argument defaults."""
1491 # The object argument defaults to '' or b''.
1492 self.assertEqual(str(), '')
1493 self.assertEqual(str(errors='strict'), '')
1494 utf8_cent = '¢'.encode('utf-8')
1495 # The encoding argument defaults to utf-8.
1496 self.assertEqual(str(utf8_cent, errors='strict'), '¢')
1497 # The errors argument defaults to strict.
1498 self.assertRaises(UnicodeDecodeError, str, utf8_cent, encoding='ascii')
1499
Walter Dörwald28256f22003-01-19 16:59:20 +00001500 def test_codecs_utf7(self):
1501 utfTests = [
Walter Dörwald67e83882007-05-05 12:26:27 +00001502 ('A\u2262\u0391.', b'A+ImIDkQ.'), # RFC2152 example
1503 ('Hi Mom -\u263a-!', b'Hi Mom -+Jjo--!'), # RFC2152 example
1504 ('\u65E5\u672C\u8A9E', b'+ZeVnLIqe-'), # RFC2152 example
1505 ('Item 3 is \u00a31.', b'Item 3 is +AKM-1.'), # RFC2152 example
1506 ('+', b'+-'),
1507 ('+-', b'+--'),
1508 ('+?', b'+-?'),
1509 ('\?', b'+AFw?'),
1510 ('+?', b'+-?'),
1511 (r'\\?', b'+AFwAXA?'),
1512 (r'\\\?', b'+AFwAXABc?'),
Antoine Pitrou244651a2009-05-04 18:56:13 +00001513 (r'++--', b'+-+---'),
1514 ('\U000abcde', b'+2m/c3g-'), # surrogate pairs
1515 ('/', b'/'),
Walter Dörwald28256f22003-01-19 16:59:20 +00001516 ]
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001517
Walter Dörwald28256f22003-01-19 16:59:20 +00001518 for (x, y) in utfTests:
1519 self.assertEqual(x.encode('utf-7'), y)
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001520
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001521 # Unpaired surrogates are passed through
1522 self.assertEqual('\uD801'.encode('utf-7'), b'+2AE-')
1523 self.assertEqual('\uD801x'.encode('utf-7'), b'+2AE-x')
1524 self.assertEqual('\uDC01'.encode('utf-7'), b'+3AE-')
1525 self.assertEqual('\uDC01x'.encode('utf-7'), b'+3AE-x')
1526 self.assertEqual(b'+2AE-'.decode('utf-7'), '\uD801')
1527 self.assertEqual(b'+2AE-x'.decode('utf-7'), '\uD801x')
1528 self.assertEqual(b'+3AE-'.decode('utf-7'), '\uDC01')
1529 self.assertEqual(b'+3AE-x'.decode('utf-7'), '\uDC01x')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001530
Antoine Pitrou5418ee02011-11-15 01:42:21 +01001531 self.assertEqual('\uD801\U000abcde'.encode('utf-7'), b'+2AHab9ze-')
1532 self.assertEqual(b'+2AHab9ze-'.decode('utf-7'), '\uD801\U000abcde')
Marc-André Lemburgb5507ec2001-10-19 12:02:29 +00001533
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001534 # Issue #2242: crash on some Windows/MSVC versions
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03001535 self.assertEqual(b'+\xc1'.decode('utf-7', 'ignore'), '')
Antoine Pitrou244651a2009-05-04 18:56:13 +00001536
1537 # Direct encoded characters
1538 set_d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'(),-./:?"
1539 # Optional direct characters
1540 set_o = '!"#$%&*;<=>@[]^_`{|}'
1541 for c in set_d:
1542 self.assertEqual(c.encode('utf7'), c.encode('ascii'))
1543 self.assertEqual(c.encode('ascii').decode('utf7'), c)
1544 for c in set_o:
1545 self.assertEqual(c.encode('ascii').decode('utf7'), c)
Antoine Pitrou5ffd9e92008-07-25 18:05:24 +00001546
Walter Dörwald28256f22003-01-19 16:59:20 +00001547 def test_codecs_utf8(self):
Walter Dörwald67e83882007-05-05 12:26:27 +00001548 self.assertEqual(''.encode('utf-8'), b'')
1549 self.assertEqual('\u20ac'.encode('utf-8'), b'\xe2\x82\xac')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001550 self.assertEqual('\U00010002'.encode('utf-8'), b'\xf0\x90\x80\x82')
1551 self.assertEqual('\U00023456'.encode('utf-8'), b'\xf0\xa3\x91\x96')
Martin v. Löwise0a2b722009-05-10 08:08:56 +00001552 self.assertEqual('\ud800'.encode('utf-8', 'surrogatepass'), b'\xed\xa0\x80')
1553 self.assertEqual('\udc00'.encode('utf-8', 'surrogatepass'), b'\xed\xb0\x80')
Ezio Melottia9860ae2011-10-04 19:06:00 +03001554 self.assertEqual(('\U00010002'*10).encode('utf-8'),
1555 b'\xf0\x90\x80\x82'*10)
Walter Dörwald28256f22003-01-19 16:59:20 +00001556 self.assertEqual(
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001557 '\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f'
1558 '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00'
1559 '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c'
1560 '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067'
1561 '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das'
1562 ' Nunstuck git und'.encode('utf-8'),
Walter Dörwald67e83882007-05-05 12:26:27 +00001563 b'\xe6\xad\xa3\xe7\xa2\xba\xe3\x81\xab\xe8\xa8\x80\xe3\x81'
1564 b'\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3\xe3\x81\xaf\xe3'
1565 b'\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x81\xbe'
1566 b'\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83'
1567 b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8'
1568 b'\xaa\x9e\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81'
1569 b'\xe3\x81\x82\xe3\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81'
1570 b'\x9f\xe3\x82\x89\xe3\x82\x81\xe3\x81\xa7\xe3\x81\x99\xe3'
1571 b'\x80\x82\xe5\xae\x9f\xe9\x9a\x9b\xe3\x81\xab\xe3\x81\xaf'
1572 b'\xe3\x80\x8cWenn ist das Nunstuck git und'
Walter Dörwald28256f22003-01-19 16:59:20 +00001573 )
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001574
Walter Dörwald28256f22003-01-19 16:59:20 +00001575 # UTF-8 specific decoding tests
Walter Dörwald67e83882007-05-05 12:26:27 +00001576 self.assertEqual(str(b'\xf0\xa3\x91\x96', 'utf-8'), '\U00023456' )
1577 self.assertEqual(str(b'\xf0\x90\x80\x82', 'utf-8'), '\U00010002' )
1578 self.assertEqual(str(b'\xe2\x82\xac', 'utf-8'), '\u20ac' )
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001579
Walter Dörwald28256f22003-01-19 16:59:20 +00001580 # Other possible utf-8 test cases:
1581 # * strict decoding testing for all of the
1582 # UTF8_ERROR cases in PyUnicode_DecodeUTF8
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001583
Ezio Melotti57221d02010-07-01 07:32:02 +00001584 def test_utf8_decode_valid_sequences(self):
1585 sequences = [
1586 # single byte
1587 (b'\x00', '\x00'), (b'a', 'a'), (b'\x7f', '\x7f'),
1588 # 2 bytes
1589 (b'\xc2\x80', '\x80'), (b'\xdf\xbf', '\u07ff'),
1590 # 3 bytes
1591 (b'\xe0\xa0\x80', '\u0800'), (b'\xed\x9f\xbf', '\ud7ff'),
1592 (b'\xee\x80\x80', '\uE000'), (b'\xef\xbf\xbf', '\uffff'),
1593 # 4 bytes
1594 (b'\xF0\x90\x80\x80', '\U00010000'),
1595 (b'\xf4\x8f\xbf\xbf', '\U0010FFFF')
1596 ]
1597 for seq, res in sequences:
1598 self.assertEqual(seq.decode('utf-8'), res)
1599
1600
1601 def test_utf8_decode_invalid_sequences(self):
1602 # continuation bytes in a sequence of 2, 3, or 4 bytes
1603 continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001604 # start bytes of a 2-byte sequence equivalent to code points < 0x7F
Ezio Melotti57221d02010-07-01 07:32:02 +00001605 invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)]
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001606 # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF
Ezio Melotti57221d02010-07-01 07:32:02 +00001607 invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)]
1608 invalid_start_bytes = (
1609 continuation_bytes + invalid_2B_seq_start_bytes +
1610 invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)]
1611 )
1612
1613 for byte in invalid_start_bytes:
1614 self.assertRaises(UnicodeDecodeError, byte.decode, 'utf-8')
1615
1616 for sb in invalid_2B_seq_start_bytes:
1617 for cb in continuation_bytes:
1618 self.assertRaises(UnicodeDecodeError, (sb+cb).decode, 'utf-8')
1619
1620 for sb in invalid_4B_seq_start_bytes:
1621 for cb1 in continuation_bytes[:3]:
1622 for cb3 in continuation_bytes[:3]:
1623 self.assertRaises(UnicodeDecodeError,
1624 (sb+cb1+b'\x80'+cb3).decode, 'utf-8')
1625
1626 for cb in [bytes([x]) for x in range(0x80, 0xA0)]:
1627 self.assertRaises(UnicodeDecodeError,
1628 (b'\xE0'+cb+b'\x80').decode, 'utf-8')
1629 self.assertRaises(UnicodeDecodeError,
1630 (b'\xE0'+cb+b'\xBF').decode, 'utf-8')
1631 # surrogates
1632 for cb in [bytes([x]) for x in range(0xA0, 0xC0)]:
1633 self.assertRaises(UnicodeDecodeError,
1634 (b'\xED'+cb+b'\x80').decode, 'utf-8')
1635 self.assertRaises(UnicodeDecodeError,
1636 (b'\xED'+cb+b'\xBF').decode, 'utf-8')
1637 for cb in [bytes([x]) for x in range(0x80, 0x90)]:
1638 self.assertRaises(UnicodeDecodeError,
1639 (b'\xF0'+cb+b'\x80\x80').decode, 'utf-8')
1640 self.assertRaises(UnicodeDecodeError,
1641 (b'\xF0'+cb+b'\xBF\xBF').decode, 'utf-8')
1642 for cb in [bytes([x]) for x in range(0x90, 0xC0)]:
1643 self.assertRaises(UnicodeDecodeError,
1644 (b'\xF4'+cb+b'\x80\x80').decode, 'utf-8')
1645 self.assertRaises(UnicodeDecodeError,
1646 (b'\xF4'+cb+b'\xBF\xBF').decode, 'utf-8')
1647
1648 def test_issue8271(self):
1649 # Issue #8271: during the decoding of an invalid UTF-8 byte sequence,
1650 # only the start byte and the continuation byte(s) are now considered
1651 # invalid, instead of the number of bytes specified by the start byte.
1652 # See http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf (page 95,
1653 # table 3-8, Row 2) for more information about the algorithm used.
1654 FFFD = '\ufffd'
1655 sequences = [
1656 # invalid start bytes
1657 (b'\x80', FFFD), # continuation byte
1658 (b'\x80\x80', FFFD*2), # 2 continuation bytes
1659 (b'\xc0', FFFD),
1660 (b'\xc0\xc0', FFFD*2),
1661 (b'\xc1', FFFD),
1662 (b'\xc1\xc0', FFFD*2),
1663 (b'\xc0\xc1', FFFD*2),
1664 # with start byte of a 2-byte sequence
1665 (b'\xc2', FFFD), # only the start byte
1666 (b'\xc2\xc2', FFFD*2), # 2 start bytes
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001667 (b'\xc2\xc2\xc2', FFFD*3), # 3 start bytes
Ezio Melotti57221d02010-07-01 07:32:02 +00001668 (b'\xc2\x41', FFFD+'A'), # invalid continuation byte
1669 # with start byte of a 3-byte sequence
1670 (b'\xe1', FFFD), # only the start byte
1671 (b'\xe1\xe1', FFFD*2), # 2 start bytes
1672 (b'\xe1\xe1\xe1', FFFD*3), # 3 start bytes
1673 (b'\xe1\xe1\xe1\xe1', FFFD*4), # 4 start bytes
1674 (b'\xe1\x80', FFFD), # only 1 continuation byte
1675 (b'\xe1\x41', FFFD+'A'), # invalid continuation byte
1676 (b'\xe1\x41\x80', FFFD+'A'+FFFD), # invalid cb followed by valid cb
1677 (b'\xe1\x41\x41', FFFD+'AA'), # 2 invalid continuation bytes
1678 (b'\xe1\x80\x41', FFFD+'A'), # only 1 valid continuation byte
1679 (b'\xe1\x80\xe1\x41', FFFD*2+'A'), # 1 valid and the other invalid
1680 (b'\xe1\x41\xe1\x80', FFFD+'A'+FFFD), # 1 invalid and the other valid
1681 # with start byte of a 4-byte sequence
1682 (b'\xf1', FFFD), # only the start byte
1683 (b'\xf1\xf1', FFFD*2), # 2 start bytes
1684 (b'\xf1\xf1\xf1', FFFD*3), # 3 start bytes
1685 (b'\xf1\xf1\xf1\xf1', FFFD*4), # 4 start bytes
1686 (b'\xf1\xf1\xf1\xf1\xf1', FFFD*5), # 5 start bytes
1687 (b'\xf1\x80', FFFD), # only 1 continuation bytes
1688 (b'\xf1\x80\x80', FFFD), # only 2 continuation bytes
1689 (b'\xf1\x80\x41', FFFD+'A'), # 1 valid cb and 1 invalid
1690 (b'\xf1\x80\x41\x41', FFFD+'AA'), # 1 valid cb and 1 invalid
1691 (b'\xf1\x80\x80\x41', FFFD+'A'), # 2 valid cb and 1 invalid
1692 (b'\xf1\x41\x80', FFFD+'A'+FFFD), # 1 invalid cv and 1 valid
1693 (b'\xf1\x41\x80\x80', FFFD+'A'+FFFD*2), # 1 invalid cb and 2 invalid
1694 (b'\xf1\x41\x80\x41', FFFD+'A'+FFFD+'A'), # 2 invalid cb and 1 invalid
1695 (b'\xf1\x41\x41\x80', FFFD+'AA'+FFFD), # 1 valid cb and 1 invalid
1696 (b'\xf1\x41\xf1\x80', FFFD+'A'+FFFD),
1697 (b'\xf1\x41\x80\xf1', FFFD+'A'+FFFD*2),
1698 (b'\xf1\xf1\x80\x41', FFFD*2+'A'),
1699 (b'\xf1\x41\xf1\xf1', FFFD+'A'+FFFD*2),
1700 # with invalid start byte of a 4-byte sequence (rfc2279)
1701 (b'\xf5', FFFD), # only the start byte
1702 (b'\xf5\xf5', FFFD*2), # 2 start bytes
1703 (b'\xf5\x80', FFFD*2), # only 1 continuation byte
1704 (b'\xf5\x80\x80', FFFD*3), # only 2 continuation byte
1705 (b'\xf5\x80\x80\x80', FFFD*4), # 3 continuation bytes
1706 (b'\xf5\x80\x41', FFFD*2+'A'), # 1 valid cb and 1 invalid
1707 (b'\xf5\x80\x41\xf5', FFFD*2+'A'+FFFD),
1708 (b'\xf5\x41\x80\x80\x41', FFFD+'A'+FFFD*2+'A'),
1709 # with invalid start byte of a 5-byte sequence (rfc2279)
1710 (b'\xf8', FFFD), # only the start byte
1711 (b'\xf8\xf8', FFFD*2), # 2 start bytes
1712 (b'\xf8\x80', FFFD*2), # only one continuation byte
1713 (b'\xf8\x80\x41', FFFD*2 + 'A'), # 1 valid cb and 1 invalid
1714 (b'\xf8\x80\x80\x80\x80', FFFD*5), # invalid 5 bytes seq with 5 bytes
1715 # with invalid start byte of a 6-byte sequence (rfc2279)
1716 (b'\xfc', FFFD), # only the start byte
1717 (b'\xfc\xfc', FFFD*2), # 2 start bytes
1718 (b'\xfc\x80\x80', FFFD*3), # only 2 continuation bytes
1719 (b'\xfc\x80\x80\x80\x80\x80', FFFD*6), # 6 continuation bytes
1720 # invalid start byte
1721 (b'\xfe', FFFD),
1722 (b'\xfe\x80\x80', FFFD*3),
1723 # other sequences
1724 (b'\xf1\x80\x41\x42\x43', '\ufffd\x41\x42\x43'),
1725 (b'\xf1\x80\xff\x42\x43', '\ufffd\ufffd\x42\x43'),
1726 (b'\xf1\x80\xc2\x81\x43', '\ufffd\x81\x43'),
1727 (b'\x61\xF1\x80\x80\xE1\x80\xC2\x62\x80\x63\x80\xBF\x64',
1728 '\x61\uFFFD\uFFFD\uFFFD\x62\uFFFD\x63\uFFFD\uFFFD\x64'),
1729 ]
1730 for n, (seq, res) in enumerate(sequences):
1731 self.assertRaises(UnicodeDecodeError, seq.decode, 'utf-8', 'strict')
1732 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1733 self.assertEqual((seq+b'b').decode('utf-8', 'replace'), res+'b')
1734 self.assertEqual(seq.decode('utf-8', 'ignore'),
1735 res.replace('\uFFFD', ''))
1736
Ezio Melottif7ed5d12012-11-04 23:21:38 +02001737 def to_bytestring(self, seq):
1738 return bytes(int(c, 16) for c in seq.split())
1739
1740 def assertCorrectUTF8Decoding(self, seq, res, err):
1741 """
1742 Check that an invalid UTF-8 sequence raises an UnicodeDecodeError when
1743 'strict' is used, returns res when 'replace' is used, and that doesn't
1744 return anything when 'ignore' is used.
1745 """
1746 with self.assertRaises(UnicodeDecodeError) as cm:
1747 seq.decode('utf-8')
1748 exc = cm.exception
1749
1750 self.assertIn(err, str(exc))
1751 self.assertEqual(seq.decode('utf-8', 'replace'), res)
1752 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'replace'),
1753 'aaaa' + res + 'bbbb')
1754 res = res.replace('\ufffd', '')
1755 self.assertEqual(seq.decode('utf-8', 'ignore'), res)
1756 self.assertEqual((b'aaaa' + seq + b'bbbb').decode('utf-8', 'ignore'),
1757 'aaaa' + res + 'bbbb')
1758
1759 def test_invalid_start_byte(self):
1760 """
1761 Test that an 'invalid start byte' error is raised when the first byte
1762 is not in the ASCII range or is not a valid start byte of a 2-, 3-, or
1763 4-bytes sequence. The invalid start byte is replaced with a single
1764 U+FFFD when errors='replace'.
1765 E.g. <80> is a continuation byte and can appear only after a start byte.
1766 """
1767 FFFD = '\ufffd'
1768 for byte in b'\x80\xA0\x9F\xBF\xC0\xC1\xF5\xFF':
1769 self.assertCorrectUTF8Decoding(bytes([byte]), '\ufffd',
1770 'invalid start byte')
1771
1772 def test_unexpected_end_of_data(self):
1773 """
1774 Test that an 'unexpected end of data' error is raised when the string
1775 ends after a start byte of a 2-, 3-, or 4-bytes sequence without having
1776 enough continuation bytes. The incomplete sequence is replaced with a
1777 single U+FFFD when errors='replace'.
1778 E.g. in the sequence <F3 80 80>, F3 is the start byte of a 4-bytes
1779 sequence, but it's followed by only 2 valid continuation bytes and the
1780 last continuation bytes is missing.
1781 Note: the continuation bytes must be all valid, if one of them is
1782 invalid another error will be raised.
1783 """
1784 sequences = [
1785 'C2', 'DF',
1786 'E0 A0', 'E0 BF', 'E1 80', 'E1 BF', 'EC 80', 'EC BF',
1787 'ED 80', 'ED 9F', 'EE 80', 'EE BF', 'EF 80', 'EF BF',
1788 'F0 90', 'F0 BF', 'F0 90 80', 'F0 90 BF', 'F0 BF 80', 'F0 BF BF',
1789 'F1 80', 'F1 BF', 'F1 80 80', 'F1 80 BF', 'F1 BF 80', 'F1 BF BF',
1790 'F3 80', 'F3 BF', 'F3 80 80', 'F3 80 BF', 'F3 BF 80', 'F3 BF BF',
1791 'F4 80', 'F4 8F', 'F4 80 80', 'F4 80 BF', 'F4 8F 80', 'F4 8F BF'
1792 ]
1793 FFFD = '\ufffd'
1794 for seq in sequences:
1795 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), '\ufffd',
1796 'unexpected end of data')
1797
1798 def test_invalid_cb_for_2bytes_seq(self):
1799 """
1800 Test that an 'invalid continuation byte' error is raised when the
1801 continuation byte of a 2-bytes sequence is invalid. The start byte
1802 is replaced by a single U+FFFD and the second byte is handled
1803 separately when errors='replace'.
1804 E.g. in the sequence <C2 41>, C2 is the start byte of a 2-bytes
1805 sequence, but 41 is not a valid continuation byte because it's the
1806 ASCII letter 'A'.
1807 """
1808 FFFD = '\ufffd'
1809 FFFDx2 = FFFD * 2
1810 sequences = [
1811 ('C2 00', FFFD+'\x00'), ('C2 7F', FFFD+'\x7f'),
1812 ('C2 C0', FFFDx2), ('C2 FF', FFFDx2),
1813 ('DF 00', FFFD+'\x00'), ('DF 7F', FFFD+'\x7f'),
1814 ('DF C0', FFFDx2), ('DF FF', FFFDx2),
1815 ]
1816 for seq, res in sequences:
1817 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1818 'invalid continuation byte')
1819
1820 def test_invalid_cb_for_3bytes_seq(self):
1821 """
1822 Test that an 'invalid continuation byte' error is raised when the
1823 continuation byte(s) of a 3-bytes sequence are invalid. When
1824 errors='replace', if the first continuation byte is valid, the first
1825 two bytes (start byte + 1st cb) are replaced by a single U+FFFD and the
1826 third byte is handled separately, otherwise only the start byte is
1827 replaced with a U+FFFD and the other continuation bytes are handled
1828 separately.
1829 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1830 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1831 because it's the ASCII letter 'A'.
1832 Note: when the start byte is E0 or ED, the valid ranges for the first
1833 continuation byte are limited to A0..BF and 80..9F respectively.
1834 Python 2 used to consider all the bytes in range 80..BF valid when the
1835 start byte was ED. This is fixed in Python 3.
1836 """
1837 FFFD = '\ufffd'
1838 FFFDx2 = FFFD * 2
1839 sequences = [
1840 ('E0 00', FFFD+'\x00'), ('E0 7F', FFFD+'\x7f'), ('E0 80', FFFDx2),
1841 ('E0 9F', FFFDx2), ('E0 C0', FFFDx2), ('E0 FF', FFFDx2),
1842 ('E0 A0 00', FFFD+'\x00'), ('E0 A0 7F', FFFD+'\x7f'),
1843 ('E0 A0 C0', FFFDx2), ('E0 A0 FF', FFFDx2),
1844 ('E0 BF 00', FFFD+'\x00'), ('E0 BF 7F', FFFD+'\x7f'),
1845 ('E0 BF C0', FFFDx2), ('E0 BF FF', FFFDx2), ('E1 00', FFFD+'\x00'),
1846 ('E1 7F', FFFD+'\x7f'), ('E1 C0', FFFDx2), ('E1 FF', FFFDx2),
1847 ('E1 80 00', FFFD+'\x00'), ('E1 80 7F', FFFD+'\x7f'),
1848 ('E1 80 C0', FFFDx2), ('E1 80 FF', FFFDx2),
1849 ('E1 BF 00', FFFD+'\x00'), ('E1 BF 7F', FFFD+'\x7f'),
1850 ('E1 BF C0', FFFDx2), ('E1 BF FF', FFFDx2), ('EC 00', FFFD+'\x00'),
1851 ('EC 7F', FFFD+'\x7f'), ('EC C0', FFFDx2), ('EC FF', FFFDx2),
1852 ('EC 80 00', FFFD+'\x00'), ('EC 80 7F', FFFD+'\x7f'),
1853 ('EC 80 C0', FFFDx2), ('EC 80 FF', FFFDx2),
1854 ('EC BF 00', FFFD+'\x00'), ('EC BF 7F', FFFD+'\x7f'),
1855 ('EC BF C0', FFFDx2), ('EC BF FF', FFFDx2), ('ED 00', FFFD+'\x00'),
1856 ('ED 7F', FFFD+'\x7f'),
1857 ('ED A0', FFFDx2), ('ED BF', FFFDx2), # see note ^
1858 ('ED C0', FFFDx2), ('ED FF', FFFDx2), ('ED 80 00', FFFD+'\x00'),
1859 ('ED 80 7F', FFFD+'\x7f'), ('ED 80 C0', FFFDx2),
1860 ('ED 80 FF', FFFDx2), ('ED 9F 00', FFFD+'\x00'),
1861 ('ED 9F 7F', FFFD+'\x7f'), ('ED 9F C0', FFFDx2),
1862 ('ED 9F FF', FFFDx2), ('EE 00', FFFD+'\x00'),
1863 ('EE 7F', FFFD+'\x7f'), ('EE C0', FFFDx2), ('EE FF', FFFDx2),
1864 ('EE 80 00', FFFD+'\x00'), ('EE 80 7F', FFFD+'\x7f'),
1865 ('EE 80 C0', FFFDx2), ('EE 80 FF', FFFDx2),
1866 ('EE BF 00', FFFD+'\x00'), ('EE BF 7F', FFFD+'\x7f'),
1867 ('EE BF C0', FFFDx2), ('EE BF FF', FFFDx2), ('EF 00', FFFD+'\x00'),
1868 ('EF 7F', FFFD+'\x7f'), ('EF C0', FFFDx2), ('EF FF', FFFDx2),
1869 ('EF 80 00', FFFD+'\x00'), ('EF 80 7F', FFFD+'\x7f'),
1870 ('EF 80 C0', FFFDx2), ('EF 80 FF', FFFDx2),
1871 ('EF BF 00', FFFD+'\x00'), ('EF BF 7F', FFFD+'\x7f'),
1872 ('EF BF C0', FFFDx2), ('EF BF FF', FFFDx2),
1873 ]
1874 for seq, res in sequences:
1875 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1876 'invalid continuation byte')
1877
1878 def test_invalid_cb_for_4bytes_seq(self):
1879 """
1880 Test that an 'invalid continuation byte' error is raised when the
1881 continuation byte(s) of a 4-bytes sequence are invalid. When
1882 errors='replace',the start byte and all the following valid
1883 continuation bytes are replaced with a single U+FFFD, and all the bytes
1884 starting from the first invalid continuation bytes (included) are
1885 handled separately.
1886 E.g. in the sequence <E1 80 41>, E1 is the start byte of a 3-bytes
1887 sequence, 80 is a valid continuation byte, but 41 is not a valid cb
1888 because it's the ASCII letter 'A'.
1889 Note: when the start byte is E0 or ED, the valid ranges for the first
1890 continuation byte are limited to A0..BF and 80..9F respectively.
1891 However, when the start byte is ED, Python 2 considers all the bytes
1892 in range 80..BF valid. This is fixed in Python 3.
1893 """
1894 FFFD = '\ufffd'
1895 FFFDx2 = FFFD * 2
1896 sequences = [
1897 ('F0 00', FFFD+'\x00'), ('F0 7F', FFFD+'\x7f'), ('F0 80', FFFDx2),
1898 ('F0 8F', FFFDx2), ('F0 C0', FFFDx2), ('F0 FF', FFFDx2),
1899 ('F0 90 00', FFFD+'\x00'), ('F0 90 7F', FFFD+'\x7f'),
1900 ('F0 90 C0', FFFDx2), ('F0 90 FF', FFFDx2),
1901 ('F0 BF 00', FFFD+'\x00'), ('F0 BF 7F', FFFD+'\x7f'),
1902 ('F0 BF C0', FFFDx2), ('F0 BF FF', FFFDx2),
1903 ('F0 90 80 00', FFFD+'\x00'), ('F0 90 80 7F', FFFD+'\x7f'),
1904 ('F0 90 80 C0', FFFDx2), ('F0 90 80 FF', FFFDx2),
1905 ('F0 90 BF 00', FFFD+'\x00'), ('F0 90 BF 7F', FFFD+'\x7f'),
1906 ('F0 90 BF C0', FFFDx2), ('F0 90 BF FF', FFFDx2),
1907 ('F0 BF 80 00', FFFD+'\x00'), ('F0 BF 80 7F', FFFD+'\x7f'),
1908 ('F0 BF 80 C0', FFFDx2), ('F0 BF 80 FF', FFFDx2),
1909 ('F0 BF BF 00', FFFD+'\x00'), ('F0 BF BF 7F', FFFD+'\x7f'),
1910 ('F0 BF BF C0', FFFDx2), ('F0 BF BF FF', FFFDx2),
1911 ('F1 00', FFFD+'\x00'), ('F1 7F', FFFD+'\x7f'), ('F1 C0', FFFDx2),
1912 ('F1 FF', FFFDx2), ('F1 80 00', FFFD+'\x00'),
1913 ('F1 80 7F', FFFD+'\x7f'), ('F1 80 C0', FFFDx2),
1914 ('F1 80 FF', FFFDx2), ('F1 BF 00', FFFD+'\x00'),
1915 ('F1 BF 7F', FFFD+'\x7f'), ('F1 BF C0', FFFDx2),
1916 ('F1 BF FF', FFFDx2), ('F1 80 80 00', FFFD+'\x00'),
1917 ('F1 80 80 7F', FFFD+'\x7f'), ('F1 80 80 C0', FFFDx2),
1918 ('F1 80 80 FF', FFFDx2), ('F1 80 BF 00', FFFD+'\x00'),
1919 ('F1 80 BF 7F', FFFD+'\x7f'), ('F1 80 BF C0', FFFDx2),
1920 ('F1 80 BF FF', FFFDx2), ('F1 BF 80 00', FFFD+'\x00'),
1921 ('F1 BF 80 7F', FFFD+'\x7f'), ('F1 BF 80 C0', FFFDx2),
1922 ('F1 BF 80 FF', FFFDx2), ('F1 BF BF 00', FFFD+'\x00'),
1923 ('F1 BF BF 7F', FFFD+'\x7f'), ('F1 BF BF C0', FFFDx2),
1924 ('F1 BF BF FF', FFFDx2), ('F3 00', FFFD+'\x00'),
1925 ('F3 7F', FFFD+'\x7f'), ('F3 C0', FFFDx2), ('F3 FF', FFFDx2),
1926 ('F3 80 00', FFFD+'\x00'), ('F3 80 7F', FFFD+'\x7f'),
1927 ('F3 80 C0', FFFDx2), ('F3 80 FF', FFFDx2),
1928 ('F3 BF 00', FFFD+'\x00'), ('F3 BF 7F', FFFD+'\x7f'),
1929 ('F3 BF C0', FFFDx2), ('F3 BF FF', FFFDx2),
1930 ('F3 80 80 00', FFFD+'\x00'), ('F3 80 80 7F', FFFD+'\x7f'),
1931 ('F3 80 80 C0', FFFDx2), ('F3 80 80 FF', FFFDx2),
1932 ('F3 80 BF 00', FFFD+'\x00'), ('F3 80 BF 7F', FFFD+'\x7f'),
1933 ('F3 80 BF C0', FFFDx2), ('F3 80 BF FF', FFFDx2),
1934 ('F3 BF 80 00', FFFD+'\x00'), ('F3 BF 80 7F', FFFD+'\x7f'),
1935 ('F3 BF 80 C0', FFFDx2), ('F3 BF 80 FF', FFFDx2),
1936 ('F3 BF BF 00', FFFD+'\x00'), ('F3 BF BF 7F', FFFD+'\x7f'),
1937 ('F3 BF BF C0', FFFDx2), ('F3 BF BF FF', FFFDx2),
1938 ('F4 00', FFFD+'\x00'), ('F4 7F', FFFD+'\x7f'), ('F4 90', FFFDx2),
1939 ('F4 BF', FFFDx2), ('F4 C0', FFFDx2), ('F4 FF', FFFDx2),
1940 ('F4 80 00', FFFD+'\x00'), ('F4 80 7F', FFFD+'\x7f'),
1941 ('F4 80 C0', FFFDx2), ('F4 80 FF', FFFDx2),
1942 ('F4 8F 00', FFFD+'\x00'), ('F4 8F 7F', FFFD+'\x7f'),
1943 ('F4 8F C0', FFFDx2), ('F4 8F FF', FFFDx2),
1944 ('F4 80 80 00', FFFD+'\x00'), ('F4 80 80 7F', FFFD+'\x7f'),
1945 ('F4 80 80 C0', FFFDx2), ('F4 80 80 FF', FFFDx2),
1946 ('F4 80 BF 00', FFFD+'\x00'), ('F4 80 BF 7F', FFFD+'\x7f'),
1947 ('F4 80 BF C0', FFFDx2), ('F4 80 BF FF', FFFDx2),
1948 ('F4 8F 80 00', FFFD+'\x00'), ('F4 8F 80 7F', FFFD+'\x7f'),
1949 ('F4 8F 80 C0', FFFDx2), ('F4 8F 80 FF', FFFDx2),
1950 ('F4 8F BF 00', FFFD+'\x00'), ('F4 8F BF 7F', FFFD+'\x7f'),
1951 ('F4 8F BF C0', FFFDx2), ('F4 8F BF FF', FFFDx2)
1952 ]
1953 for seq, res in sequences:
1954 self.assertCorrectUTF8Decoding(self.to_bytestring(seq), res,
1955 'invalid continuation byte')
1956
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001957 def test_codecs_idna(self):
1958 # Test whether trailing dot is preserved
Walter Dörwald1324c6f2007-05-11 19:57:05 +00001959 self.assertEqual("www.python.org.".encode("idna"), b"www.python.org.")
Martin v. Löwis0d8e16c2003-08-05 06:19:47 +00001960
Walter Dörwald28256f22003-01-19 16:59:20 +00001961 def test_codecs_errors(self):
1962 # Error handling (encoding)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001963 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii')
1964 self.assertRaises(UnicodeError, 'Andr\202 x'.encode, 'ascii','strict')
Walter Dörwald67e83882007-05-05 12:26:27 +00001965 self.assertEqual('Andr\202 x'.encode('ascii','ignore'), b"Andr x")
1966 self.assertEqual('Andr\202 x'.encode('ascii','replace'), b"Andr? x")
Benjamin Peterson308d6372009-09-18 21:42:35 +00001967 self.assertEqual('Andr\202 x'.encode('ascii', 'replace'),
1968 'Andr\202 x'.encode('ascii', errors='replace'))
1969 self.assertEqual('Andr\202 x'.encode('ascii', 'ignore'),
1970 'Andr\202 x'.encode(encoding='ascii', errors='ignore'))
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001971
Walter Dörwald28256f22003-01-19 16:59:20 +00001972 # Error handling (decoding)
Walter Dörwald67e83882007-05-05 12:26:27 +00001973 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii')
1974 self.assertRaises(UnicodeError, str, b'Andr\202 x', 'ascii', 'strict')
1975 self.assertEqual(str(b'Andr\202 x', 'ascii', 'ignore'), "Andr x")
1976 self.assertEqual(str(b'Andr\202 x', 'ascii', 'replace'), 'Andr\uFFFD x')
Serhiy Storchaka28b21e52015-10-02 13:07:28 +03001977 self.assertEqual(str(b'\202 x', 'ascii', 'replace'), '\uFFFD x')
Marc-André Lemburgc60e6f72001-09-20 10:35:46 +00001978
Walter Dörwald28256f22003-01-19 16:59:20 +00001979 # Error handling (unknown character names)
Guido van Rossum39478e82007-08-27 17:23:59 +00001980 self.assertEqual(b"\\N{foo}xx".decode("unicode-escape", "ignore"), "xx")
Marc-André Lemburg3688a882002-02-06 18:09:02 +00001981
Walter Dörwald28256f22003-01-19 16:59:20 +00001982 # Error handling (truncated escape sequence)
Guido van Rossum9c627722007-08-27 18:31:48 +00001983 self.assertRaises(UnicodeError, b"\\".decode, "unicode-escape")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001984
Guido van Rossum9c627722007-08-27 18:31:48 +00001985 self.assertRaises(TypeError, b"hello".decode, "test.unicode1")
1986 self.assertRaises(TypeError, str, b"hello", "test.unicode2")
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001987 self.assertRaises(TypeError, "hello".encode, "test.unicode1")
1988 self.assertRaises(TypeError, "hello".encode, "test.unicode2")
Marc-André Lemburgd6d06ad2000-07-07 17:48:52 +00001989
Walter Dörwald28256f22003-01-19 16:59:20 +00001990 # Error handling (wrong arguments)
Guido van Rossumef87d6e2007-05-02 19:09:54 +00001991 self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00001992
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001993 # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
Alexander Belopolsky942af5a2010-12-04 03:38:46 +00001994 self.assertRaises(UnicodeError, float, "\ud800")
1995 self.assertRaises(UnicodeError, float, "\udf00")
1996 self.assertRaises(UnicodeError, complex, "\ud800")
1997 self.assertRaises(UnicodeError, complex, "\udf00")
Guido van Rossum97064862000-04-10 13:52:48 +00001998
Walter Dörwald28256f22003-01-19 16:59:20 +00001999 def test_codecs(self):
2000 # Encoding
Walter Dörwald67e83882007-05-05 12:26:27 +00002001 self.assertEqual('hello'.encode('ascii'), b'hello')
2002 self.assertEqual('hello'.encode('utf-7'), b'hello')
2003 self.assertEqual('hello'.encode('utf-8'), b'hello')
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002004 self.assertEqual('hello'.encode('utf-8'), b'hello')
Walter Dörwald67e83882007-05-05 12:26:27 +00002005 self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
2006 self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
2007 self.assertEqual('hello'.encode('latin-1'), b'hello')
Guido van Rossum97064862000-04-10 13:52:48 +00002008
Marc-André Lemburg8f36af72011-02-25 15:42:01 +00002009 # Default encoding is utf-8
2010 self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
2011
Walter Dörwald28256f22003-01-19 16:59:20 +00002012 # Roundtrip safety for BMP (just the first 1024 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002013 for c in range(1024):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002014 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002015 for encoding in ('utf-7', 'utf-8', 'utf-16', 'utf-16-le',
2016 'utf-16-be', 'raw_unicode_escape',
2017 'unicode_escape', 'unicode_internal'):
Victor Stinner040e16e2011-11-15 22:44:05 +01002018 with warnings.catch_warnings():
2019 # unicode-internal has been deprecated
2020 warnings.simplefilter("ignore", DeprecationWarning)
2021
2022 self.assertEqual(str(u.encode(encoding),encoding), u)
Martin v. Löwis047c05e2002-03-21 08:55:28 +00002023
Walter Dörwald28256f22003-01-19 16:59:20 +00002024 # Roundtrip safety for BMP (just the first 256 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002025 for c in range(256):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002026 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002027 for encoding in ('latin-1',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002028 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002029
Walter Dörwald28256f22003-01-19 16:59:20 +00002030 # Roundtrip safety for BMP (just the first 128 chars)
Guido van Rossum805365e2007-05-07 22:24:25 +00002031 for c in range(128):
Guido van Rossum84fc66d2007-05-03 17:18:26 +00002032 u = chr(c)
Hye-Shik Chang835b2432005-12-17 04:38:31 +00002033 for encoding in ('ascii',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002034 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002035
Walter Dörwald28256f22003-01-19 16:59:20 +00002036 # Roundtrip safety for non-BMP (just a few chars)
Victor Stinner040e16e2011-11-15 22:44:05 +01002037 with warnings.catch_warnings():
2038 # unicode-internal has been deprecated
2039 warnings.simplefilter("ignore", DeprecationWarning)
2040
2041 u = '\U00010001\U00020002\U00030003\U00040004\U00050005'
2042 for encoding in ('utf-8', 'utf-16', 'utf-16-le', 'utf-16-be',
2043 'raw_unicode_escape',
2044 'unicode_escape', 'unicode_internal'):
2045 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossumd8855fd2000-03-24 22:14:19 +00002046
Antoine Pitrou51f66482011-11-11 13:35:44 +01002047 # UTF-8 must be roundtrip safe for all code points
2048 # (except surrogates, which are forbidden).
2049 u = ''.join(map(chr, list(range(0, 0xd800)) +
Ezio Melotti40dc9192011-11-11 17:00:46 +02002050 list(range(0xe000, 0x110000))))
Walter Dörwald28256f22003-01-19 16:59:20 +00002051 for encoding in ('utf-8',):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002052 self.assertEqual(str(u.encode(encoding),encoding), u)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002053
Walter Dörwald28256f22003-01-19 16:59:20 +00002054 def test_codecs_charmap(self):
2055 # 0-127
Guido van Rossum805365e2007-05-07 22:24:25 +00002056 s = bytes(range(128))
Walter Dörwald28256f22003-01-19 16:59:20 +00002057 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002058 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002059 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2060 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002061 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002062 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2063 'iso8859_2', 'iso8859_3', 'iso8859_4', 'iso8859_5', 'iso8859_6',
2064 'iso8859_7', 'iso8859_9', 'koi8_r', 'latin_1',
2065 'mac_cyrillic', 'mac_latin2',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002066
Walter Dörwald28256f22003-01-19 16:59:20 +00002067 'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2068 'cp1256', 'cp1257', 'cp1258',
2069 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
Marc-André Lemburgbd3be8f2002-02-07 11:33:49 +00002070
Walter Dörwald28256f22003-01-19 16:59:20 +00002071 'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
2072 'cp1006', 'iso8859_8',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002073
Walter Dörwald28256f22003-01-19 16:59:20 +00002074 ### These have undefined mappings:
2075 #'cp424',
Guido van Rossum9e896b32000-04-05 20:11:21 +00002076
Walter Dörwald28256f22003-01-19 16:59:20 +00002077 ### These fail the round-trip:
2078 #'cp875'
Guido van Rossum9e896b32000-04-05 20:11:21 +00002079
Walter Dörwald28256f22003-01-19 16:59:20 +00002080 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002081 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002082
Walter Dörwald28256f22003-01-19 16:59:20 +00002083 # 128-255
Guido van Rossum805365e2007-05-07 22:24:25 +00002084 s = bytes(range(128, 256))
Walter Dörwald28256f22003-01-19 16:59:20 +00002085 for encoding in (
Andrew Kuchlingad8156e2013-11-10 13:44:30 -05002086 'cp037', 'cp1026', 'cp273',
Benjamin Peterson5a6214a2010-06-27 22:41:29 +00002087 'cp437', 'cp500', 'cp720', 'cp737', 'cp775', 'cp850',
2088 'cp852', 'cp855', 'cp858', 'cp860', 'cp861', 'cp862',
Serhiy Storchakabe0c3252013-11-23 18:52:23 +02002089 'cp863', 'cp865', 'cp866', 'cp1125',
Walter Dörwald28256f22003-01-19 16:59:20 +00002090 'iso8859_10', 'iso8859_13', 'iso8859_14', 'iso8859_15',
2091 'iso8859_2', 'iso8859_4', 'iso8859_5',
2092 'iso8859_9', 'koi8_r', 'latin_1',
2093 'mac_cyrillic', 'mac_latin2',
Fred Drake004d5e62000-10-23 17:22:08 +00002094
Walter Dörwald28256f22003-01-19 16:59:20 +00002095 ### These have undefined mappings:
2096 #'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1255',
2097 #'cp1256', 'cp1257', 'cp1258',
2098 #'cp424', 'cp856', 'cp857', 'cp864', 'cp869', 'cp874',
2099 #'iso8859_3', 'iso8859_6', 'iso8859_7',
2100 #'mac_greek', 'mac_iceland','mac_roman', 'mac_turkish',
Fred Drake004d5e62000-10-23 17:22:08 +00002101
Walter Dörwald28256f22003-01-19 16:59:20 +00002102 ### These fail the round-trip:
2103 #'cp1006', 'cp875', 'iso8859_8',
Tim Peters2f228e72001-05-13 00:19:31 +00002104
Walter Dörwald28256f22003-01-19 16:59:20 +00002105 ):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002106 self.assertEqual(str(s, encoding).encode(encoding), s)
Guido van Rossum9e896b32000-04-05 20:11:21 +00002107
Walter Dörwald28256f22003-01-19 16:59:20 +00002108 def test_concatenation(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002109 self.assertEqual(("abc" "def"), "abcdef")
2110 self.assertEqual(("abc" "def"), "abcdef")
2111 self.assertEqual(("abc" "def"), "abcdef")
2112 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
2113 self.assertEqual(("abc" "def" "ghi"), "abcdefghi")
Fred Drake004d5e62000-10-23 17:22:08 +00002114
Walter Dörwald28256f22003-01-19 16:59:20 +00002115 def test_printing(self):
2116 class BitBucket:
2117 def write(self, text):
2118 pass
Fred Drake004d5e62000-10-23 17:22:08 +00002119
Walter Dörwald28256f22003-01-19 16:59:20 +00002120 out = BitBucket()
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002121 print('abc', file=out)
2122 print('abc', 'def', file=out)
2123 print('abc', 'def', file=out)
2124 print('abc', 'def', file=out)
2125 print('abc\n', file=out)
2126 print('abc\n', end=' ', file=out)
2127 print('abc\n', end=' ', file=out)
2128 print('def\n', file=out)
2129 print('def\n', file=out)
Fred Drake004d5e62000-10-23 17:22:08 +00002130
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002131 def test_ucs4(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002132 x = '\U00100000'
Martin v. Löwis9a3a9f72003-05-18 12:31:09 +00002133 y = x.encode("raw-unicode-escape").decode("raw-unicode-escape")
2134 self.assertEqual(x, y)
2135
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002136 y = br'\U00100000'
2137 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2138 self.assertEqual(x, y)
2139 y = br'\U00010000'
2140 x = y.decode("raw-unicode-escape").encode("raw-unicode-escape")
2141 self.assertEqual(x, y)
Christian Heimesfe337bf2008-03-23 21:54:12 +00002142
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002143 try:
2144 br'\U11111111'.decode("raw-unicode-escape")
2145 except UnicodeDecodeError as e:
2146 self.assertEqual(e.start, 0)
2147 self.assertEqual(e.end, 10)
2148 else:
2149 self.fail("Should have raised UnicodeDecodeError")
Christian Heimesfe337bf2008-03-23 21:54:12 +00002150
Brett Cannonc3647ac2005-04-26 03:45:26 +00002151 def test_conversion(self):
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002152 # Make sure __str__() works properly
2153 class ObjectToStr:
Brett Cannonc3647ac2005-04-26 03:45:26 +00002154 def __str__(self):
2155 return "foo"
2156
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002157 class StrSubclassToStr(str):
Guido van Rossum98297ee2007-11-06 21:34:58 +00002158 def __str__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002159 return "foo"
Brett Cannonc3647ac2005-04-26 03:45:26 +00002160
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002161 class StrSubclassToStrSubclass(str):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002162 def __new__(cls, content=""):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002163 return str.__new__(cls, 2*content)
Guido van Rossum98297ee2007-11-06 21:34:58 +00002164 def __str__(self):
Brett Cannonc3647ac2005-04-26 03:45:26 +00002165 return self
2166
Serhiy Storchakaa60c2fe2015-03-12 21:56:08 +02002167 self.assertEqual(str(ObjectToStr()), "foo")
2168 self.assertEqual(str(StrSubclassToStr("bar")), "foo")
2169 s = str(StrSubclassToStrSubclass("foo"))
2170 self.assertEqual(s, "foofoo")
2171 self.assertIs(type(s), StrSubclassToStrSubclass)
Brett Cannonc3647ac2005-04-26 03:45:26 +00002172
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002173 def test_unicode_repr(self):
2174 class s1:
2175 def __repr__(self):
2176 return '\\n'
2177
2178 class s2:
2179 def __repr__(self):
Guido van Rossumef87d6e2007-05-02 19:09:54 +00002180 return '\\n'
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002181
2182 self.assertEqual(repr(s1()), '\\n')
2183 self.assertEqual(repr(s2()), '\\n')
2184
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002185 def test_printable_repr(self):
2186 self.assertEqual(repr('\U00010000'), "'%c'" % (0x10000,)) # printable
Martin v. Löwisbaecd722010-10-11 22:42:28 +00002187 self.assertEqual(repr('\U00014000'), "'\\U00014000'") # nonprintable
Amaury Forgeot d'Arc324ac652010-08-18 20:44:58 +00002188
Zachary Ware9fe6d862013-12-08 00:20:35 -06002189 # This test only affects 32-bit platforms because expandtabs can only take
2190 # an int as the max value, not a 64-bit C long. If expandtabs is changed
2191 # to take a 64-bit long, this test should apply to all platforms.
2192 @unittest.skipIf(sys.maxsize > (1 << 32) or struct.calcsize('P') != 4,
2193 'only applies to 32-bit platforms')
Guido van Rossumcd16bf62007-06-13 18:07:49 +00002194 def test_expandtabs_overflows_gracefully(self):
Christian Heimesa37d4c62007-12-04 23:02:19 +00002195 self.assertRaises(OverflowError, 't\tt\t'.expandtabs, sys.maxsize)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00002196
Victor Stinner1d972ad2011-10-07 13:31:46 +02002197 @support.cpython_only
Antoine Pitroue19aa382011-10-04 16:04:01 +02002198 def test_expandtabs_optimization(self):
2199 s = 'abc'
2200 self.assertIs(s.expandtabs(), s)
2201
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002202 def test_raiseMemError(self):
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002203 if struct.calcsize('P') == 8:
2204 # 64 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002205 ascii_struct_size = 48
2206 compact_struct_size = 72
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002207 else:
2208 # 32 bits pointers
Martin v. Löwis287eca62011-09-28 10:03:28 +02002209 ascii_struct_size = 24
2210 compact_struct_size = 36
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002211
2212 for char in ('a', '\xe9', '\u20ac', '\U0010ffff'):
2213 code = ord(char)
2214 if code < 0x100:
2215 char_size = 1 # sizeof(Py_UCS1)
2216 struct_size = ascii_struct_size
2217 elif code < 0x10000:
2218 char_size = 2 # sizeof(Py_UCS2)
2219 struct_size = compact_struct_size
2220 else:
2221 char_size = 4 # sizeof(Py_UCS4)
2222 struct_size = compact_struct_size
2223 # Note: sys.maxsize is half of the actual max allocation because of
Martin v. Löwis287eca62011-09-28 10:03:28 +02002224 # the signedness of Py_ssize_t. Strings of maxlen-1 should in principle
2225 # be allocatable, given enough memory.
2226 maxlen = ((sys.maxsize - struct_size) // char_size)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002227 alloc = lambda: char * maxlen
2228 self.assertRaises(MemoryError, alloc)
2229 self.assertRaises(MemoryError, alloc)
Antoine Pitrou3db3e872008-08-17 17:06:51 +00002230
Victor Stinner808fc0a2010-03-22 12:50:40 +00002231 def test_format_subclass(self):
2232 class S(str):
2233 def __str__(self):
2234 return '__str__ overridden'
2235 s = S('xxx')
Florent Xiclunaa87b3832010-09-13 02:28:18 +00002236 self.assertEqual("%s" % s, '__str__ overridden')
2237 self.assertEqual("{}".format(s), '__str__ overridden')
Victor Stinner808fc0a2010-03-22 12:50:40 +00002238
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002239 # Test PyUnicode_FromFormat()
Victor Stinner1205f272010-09-11 00:54:47 +00002240 def test_from_format(self):
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002241 support.import_module('ctypes')
Victor Stinner15a11362012-10-06 23:48:20 +02002242 from ctypes import (
2243 pythonapi, py_object, sizeof,
Victor Stinner6d970f42011-03-02 00:04:25 +00002244 c_int, c_long, c_longlong, c_ssize_t,
Victor Stinner15a11362012-10-06 23:48:20 +02002245 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
Martin v. Löwisd63a3b82011-09-28 07:41:54 +02002246 name = "PyUnicode_FromFormat"
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002247 _PyUnicode_FromFormat = getattr(pythonapi, name)
2248 _PyUnicode_FromFormat.restype = py_object
2249
2250 def PyUnicode_FromFormat(format, *args):
2251 cargs = tuple(
2252 py_object(arg) if isinstance(arg, str) else arg
2253 for arg in args)
2254 return _PyUnicode_FromFormat(format, *cargs)
Victor Stinner1205f272010-09-11 00:54:47 +00002255
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002256 def check_format(expected, format, *args):
2257 text = PyUnicode_FromFormat(format, *args)
2258 self.assertEqual(expected, text)
2259
Victor Stinner1205f272010-09-11 00:54:47 +00002260 # ascii format, non-ascii argument
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002261 check_format('ascii\x7f=unicode\xe9',
2262 b'ascii\x7f=%U', 'unicode\xe9')
Victor Stinner1205f272010-09-11 00:54:47 +00002263
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002264 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
2265 # raises an error
Ezio Melottied3a7d22010-12-01 02:32:32 +00002266 self.assertRaisesRegex(ValueError,
Victor Stinner1205f272010-09-11 00:54:47 +00002267 '^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
Victor Stinner4c7db312010-09-12 07:51:18 +00002268 'string, got a non-ASCII byte: 0xe9$',
Victor Stinnerca1e7ec2011-01-05 00:19:28 +00002269 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
Amaury Forgeot d'Arc7888d082008-08-01 01:06:32 +00002270
Victor Stinner96865452011-03-01 23:44:09 +00002271 # test "%c"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002272 check_format('\uabcd',
2273 b'%c', c_int(0xabcd))
2274 check_format('\U0010ffff',
2275 b'%c', c_int(0x10ffff))
Serhiy Storchaka8eeae212013-06-23 20:12:14 +03002276 with self.assertRaises(OverflowError):
2277 PyUnicode_FromFormat(b'%c', c_int(0x110000))
Serhiy Storchaka31b1c8b2013-06-12 09:20:44 +03002278 # Issue #18183
Serhiy Storchakaf15ffe02013-06-12 09:28:20 +03002279 check_format('\U00010000\U00100000',
2280 b'%c%c', c_int(0x10000), c_int(0x100000))
Victor Stinner5ed8b2c2011-02-21 21:13:44 +00002281
Victor Stinner96865452011-03-01 23:44:09 +00002282 # test "%"
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002283 check_format('%',
2284 b'%')
2285 check_format('%',
2286 b'%%')
2287 check_format('%s',
2288 b'%%s')
2289 check_format('[%]',
2290 b'[%%]')
2291 check_format('%abc',
2292 b'%%%s', b'abc')
2293
2294 # truncated string
2295 check_format('abc',
2296 b'%.3s', b'abcdef')
2297 check_format('abc[\ufffd',
2298 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
2299 check_format("'\\u20acABC'",
2300 b'%A', '\u20acABC')
2301 check_format("'\\u20",
2302 b'%.5A', '\u20acABCDEF')
2303 check_format("'\u20acABC'",
2304 b'%R', '\u20acABC')
2305 check_format("'\u20acA",
2306 b'%.3R', '\u20acABCDEF')
2307 check_format('\u20acAB',
2308 b'%.3S', '\u20acABCDEF')
2309 check_format('\u20acAB',
2310 b'%.3U', '\u20acABCDEF')
2311 check_format('\u20acAB',
2312 b'%.3V', '\u20acABCDEF', None)
2313 check_format('abc[\ufffd',
2314 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
2315
2316 # following tests comes from #7330
2317 # test width modifier and precision modifier with %S
2318 check_format("repr= abc",
2319 b'repr=%5S', 'abc')
2320 check_format("repr=ab",
2321 b'repr=%.2S', 'abc')
2322 check_format("repr= ab",
2323 b'repr=%5.2S', 'abc')
2324
2325 # test width modifier and precision modifier with %R
2326 check_format("repr= 'abc'",
2327 b'repr=%8R', 'abc')
2328 check_format("repr='ab",
2329 b'repr=%.3R', 'abc')
2330 check_format("repr= 'ab",
2331 b'repr=%5.3R', 'abc')
2332
2333 # test width modifier and precision modifier with %A
2334 check_format("repr= 'abc'",
2335 b'repr=%8A', 'abc')
2336 check_format("repr='ab",
2337 b'repr=%.3A', 'abc')
2338 check_format("repr= 'ab",
2339 b'repr=%5.3A', 'abc')
2340
2341 # test width modifier and precision modifier with %s
2342 check_format("repr= abc",
2343 b'repr=%5s', b'abc')
2344 check_format("repr=ab",
2345 b'repr=%.2s', b'abc')
2346 check_format("repr= ab",
2347 b'repr=%5.2s', b'abc')
2348
2349 # test width modifier and precision modifier with %U
2350 check_format("repr= abc",
2351 b'repr=%5U', 'abc')
2352 check_format("repr=ab",
2353 b'repr=%.2U', 'abc')
2354 check_format("repr= ab",
2355 b'repr=%5.2U', 'abc')
2356
2357 # test width modifier and precision modifier with %V
2358 check_format("repr= abc",
2359 b'repr=%5V', 'abc', b'123')
2360 check_format("repr=ab",
2361 b'repr=%.2V', 'abc', b'123')
2362 check_format("repr= ab",
2363 b'repr=%5.2V', 'abc', b'123')
2364 check_format("repr= 123",
2365 b'repr=%5V', None, b'123')
2366 check_format("repr=12",
2367 b'repr=%.2V', None, b'123')
2368 check_format("repr= 12",
2369 b'repr=%5.2V', None, b'123')
Victor Stinner96865452011-03-01 23:44:09 +00002370
Victor Stinner6d970f42011-03-02 00:04:25 +00002371 # test integer formats (%i, %d, %u)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002372 check_format('010',
2373 b'%03i', c_int(10))
2374 check_format('0010',
2375 b'%0.4i', c_int(10))
2376 check_format('-123',
2377 b'%i', c_int(-123))
2378 check_format('-123',
2379 b'%li', c_long(-123))
2380 check_format('-123',
2381 b'%lli', c_longlong(-123))
2382 check_format('-123',
2383 b'%zi', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002384
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002385 check_format('-123',
2386 b'%d', c_int(-123))
2387 check_format('-123',
2388 b'%ld', c_long(-123))
2389 check_format('-123',
2390 b'%lld', c_longlong(-123))
2391 check_format('-123',
2392 b'%zd', c_ssize_t(-123))
Victor Stinner96865452011-03-01 23:44:09 +00002393
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002394 check_format('123',
2395 b'%u', c_uint(123))
2396 check_format('123',
2397 b'%lu', c_ulong(123))
2398 check_format('123',
2399 b'%llu', c_ulonglong(123))
2400 check_format('123',
2401 b'%zu', c_size_t(123))
Victor Stinner6d970f42011-03-02 00:04:25 +00002402
Victor Stinner15a11362012-10-06 23:48:20 +02002403 # test long output
2404 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
2405 max_longlong = -min_longlong - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002406 check_format(str(min_longlong),
2407 b'%lld', c_longlong(min_longlong))
2408 check_format(str(max_longlong),
2409 b'%lld', c_longlong(max_longlong))
Victor Stinner15a11362012-10-06 23:48:20 +02002410 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002411 check_format(str(max_ulonglong),
2412 b'%llu', c_ulonglong(max_ulonglong))
Victor Stinner15a11362012-10-06 23:48:20 +02002413 PyUnicode_FromFormat(b'%p', c_void_p(-1))
2414
Victor Stinnere215d962012-10-06 23:03:36 +02002415 # test padding (width and/or precision)
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002416 check_format('123'.rjust(10, '0'),
2417 b'%010i', c_int(123))
2418 check_format('123'.rjust(100),
2419 b'%100i', c_int(123))
2420 check_format('123'.rjust(100, '0'),
2421 b'%.100i', c_int(123))
2422 check_format('123'.rjust(80, '0').rjust(100),
2423 b'%100.80i', c_int(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002424
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002425 check_format('123'.rjust(10, '0'),
2426 b'%010u', c_uint(123))
2427 check_format('123'.rjust(100),
2428 b'%100u', c_uint(123))
2429 check_format('123'.rjust(100, '0'),
2430 b'%.100u', c_uint(123))
2431 check_format('123'.rjust(80, '0').rjust(100),
2432 b'%100.80u', c_uint(123))
Victor Stinnere215d962012-10-06 23:03:36 +02002433
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002434 check_format('123'.rjust(10, '0'),
2435 b'%010x', c_int(0x123))
2436 check_format('123'.rjust(100),
2437 b'%100x', c_int(0x123))
2438 check_format('123'.rjust(100, '0'),
2439 b'%.100x', c_int(0x123))
2440 check_format('123'.rjust(80, '0').rjust(100),
2441 b'%100.80x', c_int(0x123))
Victor Stinnere215d962012-10-06 23:03:36 +02002442
Victor Stinner6d970f42011-03-02 00:04:25 +00002443 # test %A
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002444 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
2445 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
Victor Stinner9a909002010-10-18 20:59:24 +00002446
Victor Stinner6d970f42011-03-02 00:04:25 +00002447 # test %V
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002448 check_format('repr=abc',
2449 b'repr=%V', 'abc', b'xyz')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002450
2451 # Test string decode from parameter of %s using utf-8.
2452 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
2453 # '\u4eba\u6c11'
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002454 check_format('repr=\u4eba\u6c11',
2455 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002456
2457 #Test replace error handler.
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002458 check_format('repr=abc\ufffd',
2459 b'repr=%V', None, b'abc\xff')
Victor Stinner2512a8b2011-03-01 22:46:52 +00002460
Victor Stinner6d970f42011-03-02 00:04:25 +00002461 # not supported: copy the raw format string. these tests are just here
2462 # to check for crashs and should not be considered as specifications
Victor Stinner8cecc8c2013-05-06 23:11:54 +02002463 check_format('%s',
2464 b'%1%s', b'abc')
2465 check_format('%1abc',
2466 b'%1abc')
2467 check_format('%+i',
2468 b'%+i', c_int(10))
2469 check_format('%.%s',
2470 b'%.%s', b'abc')
Victor Stinner6d970f42011-03-02 00:04:25 +00002471
Victor Stinner1c24bd02010-10-02 11:03:13 +00002472 # Test PyUnicode_AsWideChar()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002473 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002474 def test_aswidechar(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002475 from _testcapi import unicode_aswidechar
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002476 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002477 from ctypes import c_wchar, sizeof
2478
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002479 wchar, size = unicode_aswidechar('abcdef', 2)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002480 self.assertEqual(size, 2)
2481 self.assertEqual(wchar, 'ab')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002482
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002483 wchar, size = unicode_aswidechar('abc', 3)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002484 self.assertEqual(size, 3)
2485 self.assertEqual(wchar, 'abc')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002486
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002487 wchar, size = unicode_aswidechar('abc', 4)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002488 self.assertEqual(size, 3)
2489 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002490
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002491 wchar, size = unicode_aswidechar('abc', 10)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002492 self.assertEqual(size, 3)
2493 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002494
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002495 wchar, size = unicode_aswidechar('abc\0def', 20)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002496 self.assertEqual(size, 7)
2497 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002498
Victor Stinner5593d8a2010-10-02 11:11:27 +00002499 nonbmp = chr(0x10ffff)
2500 if sizeof(c_wchar) == 2:
2501 buflen = 3
2502 nchar = 2
2503 else: # sizeof(c_wchar) == 4
2504 buflen = 2
2505 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002506 wchar, size = unicode_aswidechar(nonbmp, buflen)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002507 self.assertEqual(size, nchar)
2508 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002509
Victor Stinner1c24bd02010-10-02 11:03:13 +00002510 # Test PyUnicode_AsWideCharString()
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002511 @support.cpython_only
Victor Stinner1c24bd02010-10-02 11:03:13 +00002512 def test_aswidecharstring(self):
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002513 from _testcapi import unicode_aswidecharstring
Antoine Pitrou0662bc22010-11-22 16:19:04 +00002514 support.import_module('ctypes')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002515 from ctypes import c_wchar, sizeof
2516
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002517 wchar, size = unicode_aswidecharstring('abc')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002518 self.assertEqual(size, 3)
2519 self.assertEqual(wchar, 'abc\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002520
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002521 wchar, size = unicode_aswidecharstring('abc\0def')
Ezio Melottib3aedd42010-11-20 19:04:17 +00002522 self.assertEqual(size, 7)
2523 self.assertEqual(wchar, 'abc\0def\0')
Victor Stinner1c24bd02010-10-02 11:03:13 +00002524
Victor Stinner5593d8a2010-10-02 11:11:27 +00002525 nonbmp = chr(0x10ffff)
2526 if sizeof(c_wchar) == 2:
2527 nchar = 2
2528 else: # sizeof(c_wchar) == 4
2529 nchar = 1
Victor Stinner46c7b3b2010-10-02 11:49:31 +00002530 wchar, size = unicode_aswidecharstring(nonbmp)
Ezio Melottib3aedd42010-11-20 19:04:17 +00002531 self.assertEqual(size, nchar)
2532 self.assertEqual(wchar, nonbmp + '\0')
Victor Stinner5593d8a2010-10-02 11:11:27 +00002533
Benjamin Peterson811c2f12011-09-30 21:31:21 -04002534 def test_subclass_add(self):
2535 class S(str):
2536 def __add__(self, o):
2537 return "3"
2538 self.assertEqual(S("4") + S("5"), "3")
2539 class S(str):
2540 def __iadd__(self, o):
2541 return "3"
2542 s = S("1")
2543 s += "4"
2544 self.assertEqual(s, "3")
2545
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002546 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002547 def test_encode_decimal(self):
2548 from _testcapi import unicode_encodedecimal
2549 self.assertEqual(unicode_encodedecimal('123'),
2550 b'123')
2551 self.assertEqual(unicode_encodedecimal('\u0663.\u0661\u0664'),
2552 b'3.14')
2553 self.assertEqual(unicode_encodedecimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2554 b' 3.14 ')
2555 self.assertRaises(UnicodeEncodeError,
2556 unicode_encodedecimal, "123\u20ac", "strict")
Victor Stinner6345be92011-11-25 20:09:01 +01002557 self.assertRaisesRegex(
2558 ValueError,
2559 "^'decimal' codec can't encode character",
2560 unicode_encodedecimal, "123\u20ac", "replace")
Victor Stinner42bf7752011-11-21 22:52:58 +01002561
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02002562 @support.cpython_only
Victor Stinner42bf7752011-11-21 22:52:58 +01002563 def test_transform_decimal(self):
2564 from _testcapi import unicode_transformdecimaltoascii as transform_decimal
2565 self.assertEqual(transform_decimal('123'),
2566 '123')
2567 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
2568 '3.14')
2569 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
2570 "\N{EM SPACE}3.14\N{EN SPACE}")
2571 self.assertEqual(transform_decimal('123\u20ac'),
2572 '123\u20ac')
2573
Victor Stinnerc814a382011-11-22 01:06:15 +01002574 def test_getnewargs(self):
2575 text = 'abc'
2576 args = text.__getnewargs__()
2577 self.assertIsNot(args[0], text)
2578 self.assertEqual(args[0], text)
2579 self.assertEqual(len(args), 1)
2580
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002581 def test_resize(self):
2582 for length in range(1, 100, 7):
2583 # generate a fresh string (refcount=1)
2584 text = 'a' * length + 'b'
2585
Ezio Melotti51e243f2013-02-20 23:56:01 +02002586 with support.check_warnings(('unicode_internal codec has been '
2587 'deprecated', DeprecationWarning)):
2588 # fill wstr internal field
2589 abc = text.encode('unicode_internal')
2590 self.assertEqual(abc.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002591
Ezio Melotti51e243f2013-02-20 23:56:01 +02002592 # resize text: wstr field must be cleared and then recomputed
2593 text += 'c'
2594 abcdef = text.encode('unicode_internal')
2595 self.assertNotEqual(abc, abcdef)
2596 self.assertEqual(abcdef.decode('unicode_internal'), text)
Victor Stinnerbbbac2e2013-02-07 23:12:46 +01002597
Victor Stinner9fc59812013-04-08 22:34:43 +02002598 def test_compare(self):
2599 # Issue #17615
2600 N = 10
2601 ascii = 'a' * N
2602 ascii2 = 'z' * N
2603 latin = '\x80' * N
2604 latin2 = '\xff' * N
2605 bmp = '\u0100' * N
2606 bmp2 = '\uffff' * N
2607 astral = '\U00100000' * N
2608 astral2 = '\U0010ffff' * N
2609 strings = (
2610 ascii, ascii2,
2611 latin, latin2,
2612 bmp, bmp2,
2613 astral, astral2)
2614 for text1, text2 in itertools.combinations(strings, 2):
2615 equal = (text1 is text2)
2616 self.assertEqual(text1 == text2, equal)
2617 self.assertEqual(text1 != text2, not equal)
2618
2619 if equal:
2620 self.assertTrue(text1 <= text2)
2621 self.assertTrue(text1 >= text2)
2622
2623 # text1 is text2: duplicate strings to skip the "str1 == str2"
2624 # optimization in unicode_compare_eq() and really compare
2625 # character per character
2626 copy1 = duplicate_string(text1)
2627 copy2 = duplicate_string(text2)
2628 self.assertIsNot(copy1, copy2)
2629
2630 self.assertTrue(copy1 == copy2)
2631 self.assertFalse(copy1 != copy2)
2632
2633 self.assertTrue(copy1 <= copy2)
2634 self.assertTrue(copy2 >= copy2)
2635
2636 self.assertTrue(ascii < ascii2)
2637 self.assertTrue(ascii < latin)
2638 self.assertTrue(ascii < bmp)
2639 self.assertTrue(ascii < astral)
2640 self.assertFalse(ascii >= ascii2)
2641 self.assertFalse(ascii >= latin)
2642 self.assertFalse(ascii >= bmp)
2643 self.assertFalse(ascii >= astral)
2644
2645 self.assertFalse(latin < ascii)
2646 self.assertTrue(latin < latin2)
2647 self.assertTrue(latin < bmp)
2648 self.assertTrue(latin < astral)
2649 self.assertTrue(latin >= ascii)
2650 self.assertFalse(latin >= latin2)
2651 self.assertFalse(latin >= bmp)
2652 self.assertFalse(latin >= astral)
2653
2654 self.assertFalse(bmp < ascii)
2655 self.assertFalse(bmp < latin)
2656 self.assertTrue(bmp < bmp2)
2657 self.assertTrue(bmp < astral)
2658 self.assertTrue(bmp >= ascii)
2659 self.assertTrue(bmp >= latin)
2660 self.assertFalse(bmp >= bmp2)
2661 self.assertFalse(bmp >= astral)
2662
2663 self.assertFalse(astral < ascii)
2664 self.assertFalse(astral < latin)
2665 self.assertFalse(astral < bmp2)
2666 self.assertTrue(astral < astral2)
2667 self.assertTrue(astral >= ascii)
2668 self.assertTrue(astral >= latin)
2669 self.assertTrue(astral >= bmp2)
2670 self.assertFalse(astral >= astral2)
2671
Victor Stinner1c24bd02010-10-02 11:03:13 +00002672
Eric Smitha1eac722011-01-29 11:15:35 +00002673class StringModuleTest(unittest.TestCase):
2674 def test_formatter_parser(self):
2675 def parse(format):
2676 return list(_string.formatter_parser(format))
2677
2678 formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
2679 self.assertEqual(formatter, [
2680 ('prefix ', '2', '', 's'),
2681 ('xxx', '0', '^+10.3f', None),
2682 ('', 'obj.attr', '', 's'),
2683 (' ', 'z[0]', '10', 's'),
2684 ])
2685
2686 formatter = parse("prefix {} suffix")
2687 self.assertEqual(formatter, [
2688 ('prefix ', '', '', None),
2689 (' suffix', None, None, None),
2690 ])
2691
2692 formatter = parse("str")
2693 self.assertEqual(formatter, [
2694 ('str', None, None, None),
2695 ])
2696
2697 formatter = parse("")
2698 self.assertEqual(formatter, [])
2699
2700 formatter = parse("{0}")
2701 self.assertEqual(formatter, [
2702 ('', '0', '', None),
2703 ])
2704
2705 self.assertRaises(TypeError, _string.formatter_parser, 1)
2706
2707 def test_formatter_field_name_split(self):
2708 def split(name):
2709 items = list(_string.formatter_field_name_split(name))
2710 items[1] = list(items[1])
2711 return items
2712 self.assertEqual(split("obj"), ["obj", []])
2713 self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
2714 self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
2715 self.assertEqual(split("obj.arg[key1][key2]"), [
2716 "obj",
2717 [(True, 'arg'),
2718 (False, 'key1'),
2719 (False, 'key2'),
2720 ]])
2721 self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
2722
2723
Walter Dörwald28256f22003-01-19 16:59:20 +00002724if __name__ == "__main__":
Ezio Melotti0dceb562013-01-10 07:43:26 +02002725 unittest.main()