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