Debian Codegraph @

Lib/test/test_capi/test_unicode.py

raw
1 import unittest
2 import sys
3 from test import support
4 from test.support import threading_helper, import_helper
5
6 try:
7 import _testcapi
8 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
9 except ImportError:
10 _testcapi = None
11 try:
12 import _testlimitedcapi
13 except ImportError:
14 _testlimitedcapi = None
15 try:
16 import _testinternalcapi
17 except ImportError:
18 _testinternalcapi = None
19
20
21 NULL = None
22
23 class Str(str):
24 pass
25
26
27 class CAPITest(unittest.TestCase):
28
29 @support.cpython_only
30 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
31 def test_new(self):
32 """Test PyUnicode_New()"""
33 from _testcapi import unicode_new as new
34
35 for maxchar in 0, 0x61, 0xa1, 0x4f60, 0x1f600, 0x10ffff:
36 self.assertEqual(new(0, maxchar), '')
37 self.assertEqual(new(5, maxchar), chr(maxchar)*5)
38 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX, maxchar)
39 self.assertEqual(new(0, 0x110000), '')
40 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//2, 0x4f60)
41 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//2+1, 0x4f60)
42 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//2, 0x1f600)
43 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//2+1, 0x1f600)
44 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//4, 0x1f600)
45 self.assertRaises(MemoryError, new, PY_SSIZE_T_MAX//4+1, 0x1f600)
46 self.assertRaises(SystemError, new, 5, 0x110000)
47 self.assertRaises(SystemError, new, -1, 0)
48 self.assertRaises(SystemError, new, PY_SSIZE_T_MIN, 0)
49
50 @support.cpython_only
51 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
52 def test_fill(self):
53 """Test PyUnicode_Fill()"""
54 from _testcapi import unicode_fill as fill
55
56 strings = [
57 # all strings have exactly 5 characters
58 'abcde', '\xa1\xa2\xa3\xa4\xa5',
59 '\u4f60\u597d\u4e16\u754c\uff01',
60 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
61 ]
62 chars = [0x78, 0xa9, 0x20ac, 0x1f638]
63
64 for idx, fill_char in enumerate(chars):
65 # wide -> narrow: exceed maxchar limitation
66 for to in strings[:idx]:
67 self.assertRaises(ValueError, fill, to, 0, 0, fill_char)
68 for to in strings[idx:]:
69 for start in [*range(7), PY_SSIZE_T_MAX]:
70 for length in [*range(-1, 7 - start), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]:
71 filled = max(min(length, 5 - start), 0)
72 if filled == 5 and to != strings[idx]:
73 # narrow -> wide
74 # Tests omitted since this creates invalid strings.
75 continue
76 expected = to[:start] + chr(fill_char) * filled + to[start + filled:]
77 self.assertEqual(fill(to, start, length, fill_char),
78 (expected, filled))
79
80 s = strings[0]
81 self.assertRaises(IndexError, fill, s, -1, 0, 0x78)
82 self.assertRaises(IndexError, fill, s, PY_SSIZE_T_MIN, 0, 0x78)
83 self.assertRaises(ValueError, fill, s, 0, 0, 0x110000)
84 self.assertRaises(SystemError, fill, b'abc', 0, 0, 0x78)
85 self.assertRaises(SystemError, fill, [], 0, 0, 0x78)
86 # CRASHES fill(s, 0, NULL, 0, 0)
87 # CRASHES fill(NULL, 0, 0, 0x78)
88 # TODO: Test PyUnicode_Fill() with non-modifiable unicode.
89
90 @support.cpython_only
91 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
92 def test_writechar(self):
93 """Test PyUnicode_WriteChar()"""
94 from _testlimitedcapi import unicode_writechar as writechar
95
96 strings = [
97 # one string for every kind
98 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
99 '\U0001f600\U0001f601\U0001f602'
100 ]
101 # one character for every kind + out of range code
102 chars = [0x78, 0xa9, 0x20ac, 0x1f638, 0x110000]
103 for i, s in enumerate(strings):
104 for j, c in enumerate(chars):
105 if j <= i:
106 self.assertEqual(writechar(s, 1, c),
107 (s[:1] + chr(c) + s[2:], 0))
108 else:
109 self.assertRaises(ValueError, writechar, s, 1, c)
110
111 self.assertRaises(IndexError, writechar, 'abc', 3, 0x78)
112 self.assertRaises(IndexError, writechar, 'abc', -1, 0x78)
113 self.assertRaises(IndexError, writechar, 'abc', PY_SSIZE_T_MAX, 0x78)
114 self.assertRaises(IndexError, writechar, 'abc', PY_SSIZE_T_MIN, 0x78)
115 self.assertRaises(TypeError, writechar, b'abc', 0, 0x78)
116 self.assertRaises(TypeError, writechar, [], 0, 0x78)
117 # CRASHES writechar(NULL, 0, 0x78)
118 # TODO: Test PyUnicode_WriteChar() with non-modifiable and legacy
119 # unicode.
120
121 @support.cpython_only
122 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
123 def test_resize(self):
124 """Test PyUnicode_Resize()"""
125 from _testlimitedcapi import unicode_resize as resize
126
127 strings = [
128 # all strings have exactly 3 characters
129 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
130 '\U0001f600\U0001f601\U0001f602'
131 ]
132 for s in strings:
133 self.assertEqual(resize(s, 3), (s, 0))
134 self.assertEqual(resize(s, 2), (s[:2], 0))
135 self.assertEqual(resize(s, 4), (s + '\0', 0))
136 self.assertEqual(resize(s, 10), (s + '\0'*7, 0))
137 self.assertEqual(resize(s, 0), ('', 0))
138 self.assertRaises(MemoryError, resize, s, PY_SSIZE_T_MAX)
139 self.assertRaises(SystemError, resize, s, -1)
140 self.assertRaises(SystemError, resize, s, PY_SSIZE_T_MIN)
141 self.assertRaises(SystemError, resize, b'abc', 0)
142 self.assertRaises(SystemError, resize, [], 0)
143 self.assertRaises(SystemError, resize, NULL, 0)
144 # TODO: Test PyUnicode_Resize() with non-modifiable and legacy unicode
145 # and with NULL as the address.
146
147 @support.cpython_only
148 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
149 def test_append(self):
150 """Test PyUnicode_Append()"""
151 from _testlimitedcapi import unicode_append as append
152
153 strings = [
154 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
155 '\U0001f600\U0001f601\U0001f602'
156 ]
157 for left in strings:
158 left = left[::-1]
159 for right in strings:
160 expected = left + right
161 self.assertEqual(append(left, right), expected)
162
163 self.assertRaises(SystemError, append, 'abc', b'abc')
164 self.assertRaises(SystemError, append, b'abc', 'abc')
165 self.assertRaises(SystemError, append, b'abc', b'abc')
166 self.assertRaises(SystemError, append, 'abc', [])
167 self.assertRaises(SystemError, append, [], 'abc')
168 self.assertRaises(SystemError, append, [], [])
169 self.assertRaises(SystemError, append, NULL, 'abc')
170 self.assertRaises(SystemError, append, 'abc', NULL)
171 # TODO: Test PyUnicode_Append() with modifiable unicode
172 # and with NULL as the address.
173 # TODO: Check reference counts.
174
175 @support.cpython_only
176 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
177 def test_appendanddel(self):
178 """Test PyUnicode_AppendAndDel()"""
179 from _testlimitedcapi import unicode_appendanddel as appendanddel
180
181 strings = [
182 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
183 '\U0001f600\U0001f601\U0001f602'
184 ]
185 for left in strings:
186 left = left[::-1]
187 for right in strings:
188 self.assertEqual(appendanddel(left, right), left + right)
189
190 self.assertRaises(SystemError, appendanddel, 'abc', b'abc')
191 self.assertRaises(SystemError, appendanddel, b'abc', 'abc')
192 self.assertRaises(SystemError, appendanddel, b'abc', b'abc')
193 self.assertRaises(SystemError, appendanddel, 'abc', [])
194 self.assertRaises(SystemError, appendanddel, [], 'abc')
195 self.assertRaises(SystemError, appendanddel, [], [])
196 self.assertRaises(SystemError, appendanddel, NULL, 'abc')
197 self.assertRaises(SystemError, appendanddel, 'abc', NULL)
198 # TODO: Test PyUnicode_AppendAndDel() with modifiable unicode
199 # and with NULL as the address.
200 # TODO: Check reference counts.
201
202 @support.cpython_only
203 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
204 def test_fromstringandsize(self):
205 """Test PyUnicode_FromStringAndSize()"""
206 from _testlimitedcapi import unicode_fromstringandsize as fromstringandsize
207
208 self.assertEqual(fromstringandsize(b'abc'), 'abc')
209 self.assertEqual(fromstringandsize(b'abc', 2), 'ab')
210 self.assertEqual(fromstringandsize(b'abc\0def'), 'abc\0def')
211 self.assertEqual(fromstringandsize(b'\xc2\xa1\xc2\xa2'), '\xa1\xa2')
212 self.assertEqual(fromstringandsize(b'\xe4\xbd\xa0'), '\u4f60')
213 self.assertEqual(fromstringandsize(b'\xf0\x9f\x98\x80'), '\U0001f600')
214 self.assertRaises(UnicodeDecodeError, fromstringandsize, b'\xc2\xa1', 1)
215 self.assertRaises(UnicodeDecodeError, fromstringandsize, b'\xa1', 1)
216 self.assertEqual(fromstringandsize(b'', 0), '')
217 self.assertEqual(fromstringandsize(NULL, 0), '')
218
219 self.assertRaises(MemoryError, fromstringandsize, b'abc', PY_SSIZE_T_MAX)
220 self.assertRaises(SystemError, fromstringandsize, b'abc', -1)
221 self.assertRaises(SystemError, fromstringandsize, b'abc', PY_SSIZE_T_MIN)
222 self.assertRaises(SystemError, fromstringandsize, NULL, -1)
223 self.assertRaises(SystemError, fromstringandsize, NULL, PY_SSIZE_T_MIN)
224 self.assertRaises(SystemError, fromstringandsize, NULL, 3)
225 self.assertRaises(SystemError, fromstringandsize, NULL, PY_SSIZE_T_MAX)
226
227 @support.cpython_only
228 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
229 def test_fromstring(self):
230 """Test PyUnicode_FromString()"""
231 from _testlimitedcapi import unicode_fromstring as fromstring
232
233 self.assertEqual(fromstring(b'abc'), 'abc')
234 self.assertEqual(fromstring(b'\xc2\xa1\xc2\xa2'), '\xa1\xa2')
235 self.assertEqual(fromstring(b'\xe4\xbd\xa0'), '\u4f60')
236 self.assertEqual(fromstring(b'\xf0\x9f\x98\x80'), '\U0001f600')
237 self.assertRaises(UnicodeDecodeError, fromstring, b'\xc2')
238 self.assertRaises(UnicodeDecodeError, fromstring, b'\xa1')
239 self.assertEqual(fromstring(b''), '')
240
241 # CRASHES fromstring(NULL)
242
243 @support.cpython_only
244 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
245 def test_fromkindanddata(self):
246 """Test PyUnicode_FromKindAndData()"""
247 from _testcapi import unicode_fromkindanddata as fromkindanddata
248
249 strings = [
250 'abcde', '\xa1\xa2\xa3\xa4\xa5',
251 '\u4f60\u597d\u4e16\u754c\uff01',
252 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
253 ]
254 enc1 = 'latin1'
255 for s in strings[:2]:
256 self.assertEqual(fromkindanddata(1, s.encode(enc1)), s)
257 enc2 = 'utf-16le' if sys.byteorder == 'little' else 'utf-16be'
258 for s in strings[:3]:
259 self.assertEqual(fromkindanddata(2, s.encode(enc2)), s)
260 enc4 = 'utf-32le' if sys.byteorder == 'little' else 'utf-32be'
261 for s in strings:
262 self.assertEqual(fromkindanddata(4, s.encode(enc4)), s)
263 self.assertEqual(fromkindanddata(2, '\U0001f600'.encode(enc2)),
264 '\ud83d\ude00')
265 for kind in 1, 2, 4:
266 self.assertEqual(fromkindanddata(kind, b''), '')
267 self.assertEqual(fromkindanddata(kind, b'\0'*kind), '\0')
268 self.assertEqual(fromkindanddata(kind, NULL, 0), '')
269
270 for kind in -1, 0, 3, 5, 8:
271 self.assertRaises(SystemError, fromkindanddata, kind, b'')
272 self.assertRaises(ValueError, fromkindanddata, 1, b'abc', -1)
273 self.assertRaises(ValueError, fromkindanddata, 1, b'abc', PY_SSIZE_T_MIN)
274 self.assertRaises(ValueError, fromkindanddata, 1, NULL, -1)
275 self.assertRaises(ValueError, fromkindanddata, 1, NULL, PY_SSIZE_T_MIN)
276 # CRASHES fromkindanddata(1, NULL, 1)
277 # CRASHES fromkindanddata(4, b'\xff\xff\xff\xff')
278
279 @support.cpython_only
280 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
281 def test_substring(self):
282 """Test PyUnicode_Substring()"""
283 from _testlimitedcapi import unicode_substring as substring
284
285 strings = [
286 'ab', 'ab\xa1\xa2',
287 'ab\xa1\xa2\u4f60\u597d',
288 'ab\xa1\xa2\u4f60\u597d\U0001f600\U0001f601'
289 ]
290 for s in strings:
291 for start in [*range(0, len(s) + 2), PY_SSIZE_T_MAX]:
292 for end in [*range(max(start-1, 0), len(s) + 2), PY_SSIZE_T_MAX]:
293 self.assertEqual(substring(s, start, end), s[start:end])
294
295 self.assertRaises(IndexError, substring, 'abc', -1, 0)
296 self.assertRaises(IndexError, substring, 'abc', PY_SSIZE_T_MIN, 0)
297 self.assertRaises(IndexError, substring, 'abc', 0, -1)
298 self.assertRaises(IndexError, substring, 'abc', 0, PY_SSIZE_T_MIN)
299 # CRASHES substring(b'abc', 0, 0)
300 # CRASHES substring([], 0, 0)
301 # CRASHES substring(NULL, 0, 0)
302
303 @support.cpython_only
304 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
305 def test_getlength(self):
306 """Test PyUnicode_GetLength()"""
307 from _testlimitedcapi import unicode_getlength as getlength
308
309 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
310 'a\ud800b\udfffc', '\ud834\udd1e']:
311 self.assertEqual(getlength(s), len(s))
312
313 self.assertRaises(TypeError, getlength, b'abc')
314 self.assertRaises(TypeError, getlength, [])
315 # CRASHES getlength(NULL)
316
317 @support.cpython_only
318 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
319 def test_readchar(self):
320 """Test PyUnicode_ReadChar()"""
321 from _testlimitedcapi import unicode_readchar as readchar
322
323 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
324 'a\ud800b\udfffc', '\ud834\udd1e']:
325 for i, c in enumerate(s):
326 self.assertEqual(readchar(s, i), ord(c))
327 self.assertRaises(IndexError, readchar, s, len(s))
328 self.assertRaises(IndexError, readchar, s, PY_SSIZE_T_MAX)
329 self.assertRaises(IndexError, readchar, s, -1)
330 self.assertRaises(IndexError, readchar, s, PY_SSIZE_T_MIN)
331
332 self.assertRaises(TypeError, readchar, b'abc', 0)
333 self.assertRaises(TypeError, readchar, [], 0)
334 # CRASHES readchar(NULL, 0)
335
336 @support.cpython_only
337 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
338 def test_fromobject(self):
339 """Test PyUnicode_FromObject()"""
340 from _testlimitedcapi import unicode_fromobject as fromobject
341
342 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
343 'a\ud800b\udfffc', '\ud834\udd1e']:
344 self.assertEqual(fromobject(s), s)
345 o = Str(s)
346 s2 = fromobject(o)
347 self.assertEqual(s2, s)
348 self.assertIs(type(s2), str)
349 self.assertIsNot(s2, s)
350
351 self.assertRaises(TypeError, fromobject, b'abc')
352 self.assertRaises(TypeError, fromobject, [])
353 # CRASHES fromobject(NULL)
354
355 def test_from_format(self):
356 """Test PyUnicode_FromFormat()"""
357 # Length modifiers "j" and "t" are not tested here because ctypes does
358 # not expose types for intmax_t and ptrdiff_t.
359 # _testlimitedcapi.test_string_from_format() has a wider coverage of all
360 # formats.
361 import_helper.import_module('ctypes')
362 from ctypes import (
363 c_char_p,
364 pythonapi, py_object, sizeof,
365 c_int, c_long, c_longlong, c_ssize_t,
366 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p,
367 c_wchar, c_wchar_p)
368 name = "PyUnicode_FromFormat"
369 _PyUnicode_FromFormat = getattr(pythonapi, name)
370 _PyUnicode_FromFormat.argtypes = (c_char_p,)
371 _PyUnicode_FromFormat.restype = py_object
372
373 def PyUnicode_FromFormat(format, *args):
374 cargs = tuple(
375 py_object(arg) if isinstance(arg, str) else arg
376 for arg in args)
377 return _PyUnicode_FromFormat(format, *cargs)
378
379 def check_format(expected, format, *args):
380 text = PyUnicode_FromFormat(format, *args)
381 self.assertEqual(expected, text)
382
383 # ascii format, non-ascii argument
384 check_format('ascii\x7f=unicode\xe9',
385 b'ascii\x7f=%U', 'unicode\xe9')
386
387 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
388 # raises an error
389 self.assertRaisesRegex(ValueError,
390 r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
391 'string, got a non-ASCII byte: 0xe9$',
392 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
393
394 # test "%c"
395 check_format('\uabcd',
396 b'%c', c_int(0xabcd))
397 check_format('\U0010ffff',
398 b'%c', c_int(0x10ffff))
399 with self.assertRaises(OverflowError):
400 PyUnicode_FromFormat(b'%c', c_int(0x110000))
401 # Issue #18183
402 check_format('\U00010000\U00100000',
403 b'%c%c', c_int(0x10000), c_int(0x100000))
404
405 # test "%"
406 check_format('%',
407 b'%%')
408 check_format('%s',
409 b'%%s')
410 check_format('[%]',
411 b'[%%]')
412 check_format('%abc',
413 b'%%%s', b'abc')
414
415 # truncated string
416 check_format('abc',
417 b'%.3s', b'abcdef')
418 check_format('abc[\ufffd',
419 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
420 check_format("'\\u20acABC'",
421 b'%A', '\u20acABC')
422 check_format("'\\u20",
423 b'%.5A', '\u20acABCDEF')
424 check_format("'\u20acABC'",
425 b'%R', '\u20acABC')
426 check_format("'\u20acA",
427 b'%.3R', '\u20acABCDEF')
428 check_format('\u20acAB',
429 b'%.3S', '\u20acABCDEF')
430 check_format('\u20acAB',
431 b'%.3U', '\u20acABCDEF')
432 check_format('\u20acAB',
433 b'%.3V', '\u20acABCDEF', None)
434 check_format('abc[\ufffd',
435 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
436
437 # following tests comes from #7330
438 # test width modifier and precision modifier with %S
439 check_format("repr= abc",
440 b'repr=%5S', 'abc')
441 check_format("repr=ab",
442 b'repr=%.2S', 'abc')
443 check_format("repr= ab",
444 b'repr=%5.2S', 'abc')
445
446 # test width modifier and precision modifier with %R
447 check_format("repr= 'abc'",
448 b'repr=%8R', 'abc')
449 check_format("repr='ab",
450 b'repr=%.3R', 'abc')
451 check_format("repr= 'ab",
452 b'repr=%5.3R', 'abc')
453
454 # test width modifier and precision modifier with %A
455 check_format("repr= 'abc'",
456 b'repr=%8A', 'abc')
457 check_format("repr='ab",
458 b'repr=%.3A', 'abc')
459 check_format("repr= 'ab",
460 b'repr=%5.3A', 'abc')
461
462 # test width modifier and precision modifier with %s
463 check_format("repr= abc",
464 b'repr=%5s', b'abc')
465 check_format("repr=ab",
466 b'repr=%.2s', b'abc')
467 check_format("repr= ab",
468 b'repr=%5.2s', b'abc')
469
470 # test width modifier and precision modifier with %U
471 check_format("repr= abc",
472 b'repr=%5U', 'abc')
473 check_format("repr=ab",
474 b'repr=%.2U', 'abc')
475 check_format("repr= ab",
476 b'repr=%5.2U', 'abc')
477
478 # test width modifier and precision modifier with %V
479 check_format("repr= abc",
480 b'repr=%5V', 'abc', b'123')
481 check_format("repr=ab",
482 b'repr=%.2V', 'abc', b'123')
483 check_format("repr= ab",
484 b'repr=%5.2V', 'abc', b'123')
485 check_format("repr= 123",
486 b'repr=%5V', None, b'123')
487 check_format("repr=12",
488 b'repr=%.2V', None, b'123')
489 check_format("repr= 12",
490 b'repr=%5.2V', None, b'123')
491
492 # test integer formats (%i, %d, %u, %o, %x, %X)
493 check_format('010',
494 b'%03i', c_int(10))
495 check_format('0010',
496 b'%0.4i', c_int(10))
497 for conv, signed, value, expected in [
498 (b'i', True, -123, '-123'),
499 (b'd', True, -123, '-123'),
500 (b'u', False, 123, '123'),
501 (b'o', False, 0o123, '123'),
502 (b'x', False, 0xabc, 'abc'),
503 (b'X', False, 0xabc, 'ABC'),
504 ]:
505 for mod, ctype in [
506 (b'', c_int if signed else c_uint),
507 (b'l', c_long if signed else c_ulong),
508 (b'll', c_longlong if signed else c_ulonglong),
509 (b'z', c_ssize_t if signed else c_size_t),
510 ]:
511 with self.subTest(format=b'%' + mod + conv):
512 check_format(expected,
513 b'%' + mod + conv, ctype(value))
514
515 # test long output
516 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
517 max_longlong = -min_longlong - 1
518 check_format(str(min_longlong),
519 b'%lld', c_longlong(min_longlong))
520 check_format(str(max_longlong),
521 b'%lld', c_longlong(max_longlong))
522 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
523 check_format(str(max_ulonglong),
524 b'%llu', c_ulonglong(max_ulonglong))
525 PyUnicode_FromFormat(b'%p', c_void_p(-1))
526
527 # test padding (width and/or precision)
528 check_format('123', b'%2i', c_int(123))
529 check_format(' 123', b'%10i', c_int(123))
530 check_format('0000000123', b'%010i', c_int(123))
531 check_format('123 ', b'%-10i', c_int(123))
532 check_format('123 ', b'%-010i', c_int(123))
533 check_format('123', b'%.2i', c_int(123))
534 check_format('0000123', b'%.7i', c_int(123))
535 check_format(' 123', b'%10.2i', c_int(123))
536 check_format(' 0000123', b'%10.7i', c_int(123))
537 check_format('0000000123', b'%010.7i', c_int(123))
538 check_format('0000123 ', b'%-10.7i', c_int(123))
539 check_format('0000123 ', b'%-010.7i', c_int(123))
540
541 check_format('-123', b'%2i', c_int(-123))
542 check_format(' -123', b'%10i', c_int(-123))
543 check_format('-000000123', b'%010i', c_int(-123))
544 check_format('-123 ', b'%-10i', c_int(-123))
545 check_format('-123 ', b'%-010i', c_int(-123))
546 check_format('-123', b'%.2i', c_int(-123))
547 check_format('-0000123', b'%.7i', c_int(-123))
548 check_format(' -123', b'%10.2i', c_int(-123))
549 check_format(' -0000123', b'%10.7i', c_int(-123))
550 check_format('-000000123', b'%010.7i', c_int(-123))
551 check_format('-0000123 ', b'%-10.7i', c_int(-123))
552 check_format('-0000123 ', b'%-010.7i', c_int(-123))
553
554 check_format('123', b'%2u', c_uint(123))
555 check_format(' 123', b'%10u', c_uint(123))
556 check_format('0000000123', b'%010u', c_uint(123))
557 check_format('123 ', b'%-10u', c_uint(123))
558 check_format('123 ', b'%-010u', c_uint(123))
559 check_format('123', b'%.2u', c_uint(123))
560 check_format('0000123', b'%.7u', c_uint(123))
561 check_format(' 123', b'%10.2u', c_uint(123))
562 check_format(' 0000123', b'%10.7u', c_uint(123))
563 check_format('0000000123', b'%010.7u', c_uint(123))
564 check_format('0000123 ', b'%-10.7u', c_uint(123))
565 check_format('0000123 ', b'%-010.7u', c_uint(123))
566
567 check_format('123', b'%2o', c_uint(0o123))
568 check_format(' 123', b'%10o', c_uint(0o123))
569 check_format('0000000123', b'%010o', c_uint(0o123))
570 check_format('123 ', b'%-10o', c_uint(0o123))
571 check_format('123 ', b'%-010o', c_uint(0o123))
572 check_format('123', b'%.2o', c_uint(0o123))
573 check_format('0000123', b'%.7o', c_uint(0o123))
574 check_format(' 123', b'%10.2o', c_uint(0o123))
575 check_format(' 0000123', b'%10.7o', c_uint(0o123))
576 check_format('0000000123', b'%010.7o', c_uint(0o123))
577 check_format('0000123 ', b'%-10.7o', c_uint(0o123))
578 check_format('0000123 ', b'%-010.7o', c_uint(0o123))
579
580 check_format('abc', b'%2x', c_uint(0xabc))
581 check_format(' abc', b'%10x', c_uint(0xabc))
582 check_format('0000000abc', b'%010x', c_uint(0xabc))
583 check_format('abc ', b'%-10x', c_uint(0xabc))
584 check_format('abc ', b'%-010x', c_uint(0xabc))
585 check_format('abc', b'%.2x', c_uint(0xabc))
586 check_format('0000abc', b'%.7x', c_uint(0xabc))
587 check_format(' abc', b'%10.2x', c_uint(0xabc))
588 check_format(' 0000abc', b'%10.7x', c_uint(0xabc))
589 check_format('0000000abc', b'%010.7x', c_uint(0xabc))
590 check_format('0000abc ', b'%-10.7x', c_uint(0xabc))
591 check_format('0000abc ', b'%-010.7x', c_uint(0xabc))
592
593 check_format('ABC', b'%2X', c_uint(0xabc))
594 check_format(' ABC', b'%10X', c_uint(0xabc))
595 check_format('0000000ABC', b'%010X', c_uint(0xabc))
596 check_format('ABC ', b'%-10X', c_uint(0xabc))
597 check_format('ABC ', b'%-010X', c_uint(0xabc))
598 check_format('ABC', b'%.2X', c_uint(0xabc))
599 check_format('0000ABC', b'%.7X', c_uint(0xabc))
600 check_format(' ABC', b'%10.2X', c_uint(0xabc))
601 check_format(' 0000ABC', b'%10.7X', c_uint(0xabc))
602 check_format('0000000ABC', b'%010.7X', c_uint(0xabc))
603 check_format('0000ABC ', b'%-10.7X', c_uint(0xabc))
604 check_format('0000ABC ', b'%-010.7X', c_uint(0xabc))
605
606 # test %A
607 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
608 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
609
610 # test %V
611 check_format('abc',
612 b'%V', 'abc', b'xyz')
613 check_format('xyz',
614 b'%V', None, b'xyz')
615
616 # test %ls
617 check_format('abc', b'%ls', c_wchar_p('abc'))
618 check_format('\u4eba\u6c11', b'%ls', c_wchar_p('\u4eba\u6c11'))
619 check_format('\U0001f4bb+\U0001f40d',
620 b'%ls', c_wchar_p('\U0001f4bb+\U0001f40d'))
621 check_format(' ab', b'%5.2ls', c_wchar_p('abc'))
622 check_format(' \u4eba\u6c11', b'%5ls', c_wchar_p('\u4eba\u6c11'))
623 check_format(' \U0001f4bb+\U0001f40d',
624 b'%5ls', c_wchar_p('\U0001f4bb+\U0001f40d'))
625 check_format('\u4eba', b'%.1ls', c_wchar_p('\u4eba\u6c11'))
626 check_format('\U0001f4bb' if sizeof(c_wchar) > 2 else '\ud83d',
627 b'%.1ls', c_wchar_p('\U0001f4bb+\U0001f40d'))
628 check_format('\U0001f4bb+' if sizeof(c_wchar) > 2 else '\U0001f4bb',
629 b'%.2ls', c_wchar_p('\U0001f4bb+\U0001f40d'))
630
631 # test %lV
632 check_format('abc',
633 b'%lV', 'abc', c_wchar_p('xyz'))
634 check_format('xyz',
635 b'%lV', None, c_wchar_p('xyz'))
636 check_format('\u4eba\u6c11',
637 b'%lV', None, c_wchar_p('\u4eba\u6c11'))
638 check_format('\U0001f4bb+\U0001f40d',
639 b'%lV', None, c_wchar_p('\U0001f4bb+\U0001f40d'))
640 check_format(' ab',
641 b'%5.2lV', None, c_wchar_p('abc'))
642 check_format(' \u4eba\u6c11',
643 b'%5lV', None, c_wchar_p('\u4eba\u6c11'))
644 check_format(' \U0001f4bb+\U0001f40d',
645 b'%5lV', None, c_wchar_p('\U0001f4bb+\U0001f40d'))
646 check_format('\u4eba',
647 b'%.1lV', None, c_wchar_p('\u4eba\u6c11'))
648 check_format('\U0001f4bb' if sizeof(c_wchar) > 2 else '\ud83d',
649 b'%.1lV', None, c_wchar_p('\U0001f4bb+\U0001f40d'))
650 check_format('\U0001f4bb+' if sizeof(c_wchar) > 2 else '\U0001f4bb',
651 b'%.2lV', None, c_wchar_p('\U0001f4bb+\U0001f40d'))
652
653 # test %T
654 check_format('type: str',
655 b'type: %T', py_object("abc"))
656 check_format(f'type: st',
657 b'type: %.2T', py_object("abc"))
658 check_format(f'type: str',
659 b'type: %10T', py_object("abc"))
660
661 class LocalType:
662 pass
663 obj = LocalType()
664 fullname = f'{__name__}.{LocalType.__qualname__}'
665 check_format(f'type: {fullname}',
666 b'type: %T', py_object(obj))
667 fullname_alt = f'{__name__}:{LocalType.__qualname__}'
668 check_format(f'type: {fullname_alt}',
669 b'type: %#T', py_object(obj))
670
671 # test %N
672 check_format('type: str',
673 b'type: %N', py_object(str))
674 check_format(f'type: st',
675 b'type: %.2N', py_object(str))
676 check_format(f'type: str',
677 b'type: %10N', py_object(str))
678
679 check_format(f'type: {fullname}',
680 b'type: %N', py_object(type(obj)))
681 check_format(f'type: {fullname_alt}',
682 b'type: %#N', py_object(type(obj)))
683 with self.assertRaisesRegex(TypeError, "%N argument must be a type"):
684 check_format('type: str',
685 b'type: %N', py_object("abc"))
686
687 # test variable width and precision
688 check_format(' abc', b'%*s', c_int(5), b'abc')
689 check_format('ab', b'%.*s', c_int(2), b'abc')
690 check_format(' ab', b'%*.*s', c_int(5), c_int(2), b'abc')
691 check_format(' abc', b'%*U', c_int(5), 'abc')
692 check_format('ab', b'%.*U', c_int(2), 'abc')
693 check_format(' ab', b'%*.*U', c_int(5), c_int(2), 'abc')
694 check_format(' ab', b'%*.*V', c_int(5), c_int(2), None, b'abc')
695 check_format(' ab', b'%*.*lV', c_int(5), c_int(2),
696 None, c_wchar_p('abc'))
697 check_format(' 123', b'%*i', c_int(8), c_int(123))
698 check_format('00123', b'%.*i', c_int(5), c_int(123))
699 check_format(' 00123', b'%*.*i', c_int(8), c_int(5), c_int(123))
700
701 # test %p
702 # We cannot test the exact result,
703 # because it returns a hex representation of a C pointer,
704 # which is going to be different each time. But, we can test the format.
705 p_format_regex = r'^0x[a-zA-Z0-9]{3,}$'
706 p_format1 = PyUnicode_FromFormat(b'%p', 'abc')
707 self.assertIsInstance(p_format1, str)
708 self.assertRegex(p_format1, p_format_regex)
709
710 p_format2 = PyUnicode_FromFormat(b'%p %p', '123456', b'xyz')
711 self.assertIsInstance(p_format2, str)
712 self.assertRegex(p_format2,
713 r'0x[a-zA-Z0-9]{3,} 0x[a-zA-Z0-9]{3,}')
714
715 # Extra args are ignored:
716 p_format3 = PyUnicode_FromFormat(b'%p', '123456', None, b'xyz')
717 self.assertIsInstance(p_format3, str)
718 self.assertRegex(p_format3, p_format_regex)
719
720 # Test string decode from parameter of %s using utf-8.
721 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
722 # '\u4eba\u6c11'
723 check_format('repr=\u4eba\u6c11',
724 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
725
726 #Test replace error handler.
727 check_format('repr=abc\ufffd',
728 b'repr=%V', None, b'abc\xff')
729
730 # Issue #33817: empty strings
731 check_format('',
732 b'')
733 check_format('',
734 b'%s', b'')
735
736 # test invalid format strings. these tests are just here
737 # to check for crashes and should not be considered as specifications
738 for fmt in (b'%', b'%0', b'%01', b'%.', b'%.1',
739 b'%0%s', b'%1%s', b'%.%s', b'%.1%s', b'%1abc',
740 b'%l', b'%ll', b'%z', b'%lls', b'%zs'):
741 with self.subTest(fmt=fmt):
742 self.assertRaisesRegex(SystemError, 'invalid format string',
743 PyUnicode_FromFormat, fmt, b'abc')
744 self.assertRaisesRegex(SystemError, 'invalid format string',
745 PyUnicode_FromFormat, b'%+i', c_int(10))
746
747 @support.cpython_only
748 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
749 def test_interninplace(self):
750 """Test PyUnicode_InternInPlace()"""
751 from _testlimitedcapi import unicode_interninplace as interninplace
752
753 s = b'abc'.decode()
754 r = interninplace(s)
755 self.assertEqual(r, 'abc')
756
757 # CRASHES interninplace(b'abc')
758 # CRASHES interninplace(NULL)
759
760 @support.cpython_only
761 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
762 def test_internfromstring(self):
763 """Test PyUnicode_InternFromString()"""
764 from _testlimitedcapi import unicode_internfromstring as internfromstring
765
766 self.assertEqual(internfromstring(b'abc'), 'abc')
767 self.assertEqual(internfromstring(b'\xf0\x9f\x98\x80'), '\U0001f600')
768 self.assertRaises(UnicodeDecodeError, internfromstring, b'\xc2')
769 self.assertRaises(UnicodeDecodeError, internfromstring, b'\xa1')
770 self.assertEqual(internfromstring(b''), '')
771
772 # CRASHES internfromstring(NULL)
773
774 @support.cpython_only
775 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
776 def test_fromwidechar(self):
777 """Test PyUnicode_FromWideChar()"""
778 from _testlimitedcapi import unicode_fromwidechar as fromwidechar
779 from _testcapi import SIZEOF_WCHAR_T
780
781 if SIZEOF_WCHAR_T == 2:
782 encoding = 'utf-16le' if sys.byteorder == 'little' else 'utf-16be'
783 elif SIZEOF_WCHAR_T == 4:
784 encoding = 'utf-32le' if sys.byteorder == 'little' else 'utf-32be'
785
786 for s in '', 'abc', '\xa1\xa2', '\u4f60', '\U0001f600':
787 b = s.encode(encoding)
788 self.assertEqual(fromwidechar(b), s)
789 self.assertEqual(fromwidechar(b + b'\0'*SIZEOF_WCHAR_T, -1), s)
790 for s in '\ud83d', '\ude00':
791 b = s.encode(encoding, 'surrogatepass')
792 self.assertEqual(fromwidechar(b), s)
793 self.assertEqual(fromwidechar(b + b'\0'*SIZEOF_WCHAR_T, -1), s)
794
795 self.assertEqual(fromwidechar('abc'.encode(encoding), 2), 'ab')
796 if SIZEOF_WCHAR_T == 2:
797 self.assertEqual(fromwidechar('a\U0001f600'.encode(encoding), 2), 'a\ud83d')
798
799 self.assertRaises(MemoryError, fromwidechar, b'', PY_SSIZE_T_MAX)
800 self.assertRaises(SystemError, fromwidechar, b'\0'*SIZEOF_WCHAR_T, -2)
801 self.assertRaises(SystemError, fromwidechar, b'\0'*SIZEOF_WCHAR_T, PY_SSIZE_T_MIN)
802 self.assertEqual(fromwidechar(NULL, 0), '')
803 self.assertRaises(SystemError, fromwidechar, NULL, 1)
804 self.assertRaises(SystemError, fromwidechar, NULL, PY_SSIZE_T_MAX)
805 self.assertRaises(SystemError, fromwidechar, NULL, -1)
806 self.assertRaises(SystemError, fromwidechar, NULL, -2)
807 self.assertRaises(SystemError, fromwidechar, NULL, PY_SSIZE_T_MIN)
808
809 @support.cpython_only
810 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
811 def test_aswidechar(self):
812 """Test PyUnicode_AsWideChar()"""
813 from _testlimitedcapi import unicode_aswidechar
814 from _testlimitedcapi import unicode_aswidechar_null
815 from _testcapi import SIZEOF_WCHAR_T
816
817 wchar, size = unicode_aswidechar('abcdef', 2)
818 self.assertEqual(size, 2)
819 self.assertEqual(wchar, 'ab')
820
821 wchar, size = unicode_aswidechar('abc', 3)
822 self.assertEqual(size, 3)
823 self.assertEqual(wchar, 'abc')
824 self.assertEqual(unicode_aswidechar_null('abc', 10), 4)
825 self.assertEqual(unicode_aswidechar_null('abc', 0), 4)
826
827 wchar, size = unicode_aswidechar('abc', 4)
828 self.assertEqual(size, 3)
829 self.assertEqual(wchar, 'abc\0')
830
831 wchar, size = unicode_aswidechar('abc', 10)
832 self.assertEqual(size, 3)
833 self.assertEqual(wchar, 'abc\0')
834
835 wchar, size = unicode_aswidechar('abc\0def', 20)
836 self.assertEqual(size, 7)
837 self.assertEqual(wchar, 'abc\0def\0')
838 self.assertEqual(unicode_aswidechar_null('abc\0def', 20), 8)
839
840 nonbmp = chr(0x10ffff)
841 if SIZEOF_WCHAR_T == 2:
842 nchar = 2
843 else: # SIZEOF_WCHAR_T == 4
844 nchar = 1
845 wchar, size = unicode_aswidechar(nonbmp, 10)
846 self.assertEqual(size, nchar)
847 self.assertEqual(wchar, nonbmp + '\0')
848 self.assertEqual(unicode_aswidechar_null(nonbmp, 10), nchar + 1)
849
850 self.assertRaises(TypeError, unicode_aswidechar, b'abc', 10)
851 self.assertRaises(TypeError, unicode_aswidechar, [], 10)
852 self.assertRaises(SystemError, unicode_aswidechar, NULL, 10)
853 self.assertRaises(TypeError, unicode_aswidechar_null, b'abc', 10)
854 self.assertRaises(TypeError, unicode_aswidechar_null, [], 10)
855 self.assertRaises(SystemError, unicode_aswidechar_null, NULL, 10)
856
857 @support.cpython_only
858 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
859 def test_aswidecharstring(self):
860 """Test PyUnicode_AsWideCharString()"""
861 from _testlimitedcapi import unicode_aswidecharstring
862 from _testlimitedcapi import unicode_aswidecharstring_null
863 from _testcapi import SIZEOF_WCHAR_T
864
865 wchar, size = unicode_aswidecharstring('abc')
866 self.assertEqual(size, 3)
867 self.assertEqual(wchar, 'abc\0')
868 self.assertEqual(unicode_aswidecharstring_null('abc'), 'abc')
869
870 wchar, size = unicode_aswidecharstring('abc\0def')
871 self.assertEqual(size, 7)
872 self.assertEqual(wchar, 'abc\0def\0')
873 self.assertRaises(ValueError, unicode_aswidecharstring_null, 'abc\0def')
874
875 nonbmp = chr(0x10ffff)
876 if SIZEOF_WCHAR_T == 2:
877 nchar = 2
878 else: # SIZEOF_WCHAR_T == 4
879 nchar = 1
880 wchar, size = unicode_aswidecharstring(nonbmp)
881 self.assertEqual(size, nchar)
882 self.assertEqual(wchar, nonbmp + '\0')
883 self.assertEqual(unicode_aswidecharstring_null(nonbmp), nonbmp)
884
885 self.assertRaises(TypeError, unicode_aswidecharstring, b'abc')
886 self.assertRaises(TypeError, unicode_aswidecharstring, [])
887 self.assertRaises(SystemError, unicode_aswidecharstring, NULL)
888 self.assertRaises(TypeError, unicode_aswidecharstring_null, b'abc')
889 self.assertRaises(TypeError, unicode_aswidecharstring_null, [])
890 self.assertRaises(SystemError, unicode_aswidecharstring_null, NULL)
891
892 @support.cpython_only
893 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
894 def test_asucs4(self):
895 """Test PyUnicode_AsUCS4()"""
896 from _testcapi import unicode_asucs4
897
898 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
899 'a\ud800b\udfffc', '\ud834\udd1e']:
900 l = len(s)
901 self.assertEqual(unicode_asucs4(s, l, 1), s+'\0')
902 self.assertEqual(unicode_asucs4(s, l, 0), s+'\uffff')
903 self.assertEqual(unicode_asucs4(s, l+1, 1), s+'\0\uffff')
904 self.assertEqual(unicode_asucs4(s, l+1, 0), s+'\0\uffff')
905 self.assertRaises(SystemError, unicode_asucs4, s, l-1, 1)
906 self.assertRaises(SystemError, unicode_asucs4, s, l-2, 0)
907 s = '\0'.join([s, s])
908 self.assertEqual(unicode_asucs4(s, len(s), 1), s+'\0')
909 self.assertEqual(unicode_asucs4(s, len(s), 0), s+'\uffff')
910
911 # CRASHES unicode_asucs4(b'abc', 1, 0)
912 # CRASHES unicode_asucs4(b'abc', 1, 1)
913 # CRASHES unicode_asucs4([], 1, 1)
914 # CRASHES unicode_asucs4(NULL, 1, 0)
915 # CRASHES unicode_asucs4(NULL, 1, 1)
916
917 @support.cpython_only
918 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
919 def test_asucs4copy(self):
920 """Test PyUnicode_AsUCS4Copy()"""
921 from _testcapi import unicode_asucs4copy as asucs4copy
922
923 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
924 'a\ud800b\udfffc', '\ud834\udd1e']:
925 self.assertEqual(asucs4copy(s), s+'\0')
926 s = '\0'.join([s, s])
927 self.assertEqual(asucs4copy(s), s+'\0')
928
929 # CRASHES asucs4copy(b'abc')
930 # CRASHES asucs4copy([])
931 # CRASHES asucs4copy(NULL)
932
933 @support.cpython_only
934 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
935 def test_fromordinal(self):
936 """Test PyUnicode_FromOrdinal()"""
937 from _testlimitedcapi import unicode_fromordinal as fromordinal
938
939 self.assertEqual(fromordinal(0x61), 'a')
940 self.assertEqual(fromordinal(0x20ac), '\u20ac')
941 self.assertEqual(fromordinal(0x1f600), '\U0001f600')
942
943 self.assertRaises(ValueError, fromordinal, 0x110000)
944 self.assertRaises(ValueError, fromordinal, -1)
945
946 @support.cpython_only
947 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
948 def test_asutf8(self):
949 """Test PyUnicode_AsUTF8()"""
950 from _testcapi import unicode_asutf8
951
952 self.assertEqual(unicode_asutf8('abc', 4), b'abc\0')
953 self.assertEqual(unicode_asutf8('абв', 7), b'\xd0\xb0\xd0\xb1\xd0\xb2\0')
954 self.assertEqual(unicode_asutf8('\U0001f600', 5), b'\xf0\x9f\x98\x80\0')
955 self.assertEqual(unicode_asutf8('abc\0def', 8), b'abc\0def\0')
956
957 self.assertRaises(UnicodeEncodeError, unicode_asutf8, '\ud8ff', 0)
958 self.assertRaises(TypeError, unicode_asutf8, b'abc', 0)
959 self.assertRaises(TypeError, unicode_asutf8, [], 0)
960 # CRASHES unicode_asutf8(NULL, 0)
961
962 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
963 @threading_helper.requires_working_threading()
964 def test_asutf8_race(self):
965 """Test that there's no race condition in PyUnicode_AsUTF8()"""
966 unicode_asutf8 = _testcapi.unicode_asutf8
967 from threading import Thread
968
969 data = "😊"
970
971 def worker():
972 for _ in range(1000):
973 self.assertEqual(unicode_asutf8(data, 5), b'\xf0\x9f\x98\x8a\0')
974
975 threads = [Thread(target=worker) for _ in range(10)]
976 with threading_helper.start_threads(threads):
977 pass
978
979
980 @support.cpython_only
981 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
982 def test_asutf8andsize(self):
983 """Test PyUnicode_AsUTF8AndSize()"""
984 from _testlimitedcapi import unicode_asutf8andsize
985 from _testlimitedcapi import unicode_asutf8andsize_null
986
987 self.assertEqual(unicode_asutf8andsize('abc', 4), (b'abc\0', 3))
988 self.assertEqual(unicode_asutf8andsize('абв', 7), (b'\xd0\xb0\xd0\xb1\xd0\xb2\0', 6))
989 self.assertEqual(unicode_asutf8andsize('\U0001f600', 5), (b'\xf0\x9f\x98\x80\0', 4))
990 self.assertEqual(unicode_asutf8andsize('abc\0def', 8), (b'abc\0def\0', 7))
991 self.assertEqual(unicode_asutf8andsize_null('abc', 4), b'abc\0')
992 self.assertEqual(unicode_asutf8andsize_null('abc\0def', 8), b'abc\0def\0')
993
994 self.assertRaises(UnicodeEncodeError, unicode_asutf8andsize, '\ud8ff', 0)
995 self.assertRaises(TypeError, unicode_asutf8andsize, b'abc', 0)
996 self.assertRaises(TypeError, unicode_asutf8andsize, [], 0)
997 self.assertRaises(UnicodeEncodeError, unicode_asutf8andsize_null, '\ud8ff', 0)
998 self.assertRaises(TypeError, unicode_asutf8andsize_null, b'abc', 0)
999 self.assertRaises(TypeError, unicode_asutf8andsize_null, [], 0)
1000 # CRASHES unicode_asutf8andsize(NULL, 0)
1001 # CRASHES unicode_asutf8andsize_null(NULL, 0)
1002
1003 @support.cpython_only
1004 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1005 def test_getdefaultencoding(self):
1006 """Test PyUnicode_GetDefaultEncoding()"""
1007 from _testlimitedcapi import unicode_getdefaultencoding as getdefaultencoding
1008
1009 self.assertEqual(getdefaultencoding(), b'utf-8')
1010
1011 @support.cpython_only
1012 @unittest.skipIf(_testinternalcapi is None, 'need _testinternalcapi module')
1013 def test_transform_decimal_and_space(self):
1014 """Test _PyUnicode_TransformDecimalAndSpaceToASCII()"""
1015 from _testinternalcapi import _PyUnicode_TransformDecimalAndSpaceToASCII as transform_decimal
1016
1017 self.assertEqual(transform_decimal('123'),
1018 '123')
1019 self.assertEqual(transform_decimal('\u0663.\u0661\u0664'),
1020 '3.14')
1021 self.assertEqual(transform_decimal("\N{EM SPACE}3.14\N{EN SPACE}"),
1022 " 3.14 ")
1023 self.assertEqual(transform_decimal('12\u20ac3'),
1024 '12?')
1025 self.assertEqual(transform_decimal(''), '')
1026
1027 self.assertRaises(SystemError, transform_decimal, b'123')
1028 self.assertRaises(SystemError, transform_decimal, [])
1029 # CRASHES transform_decimal(NULL)
1030
1031 @support.cpython_only
1032 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1033 def test_concat(self):
1034 """Test PyUnicode_Concat()"""
1035 from _testlimitedcapi import unicode_concat as concat
1036
1037 self.assertEqual(concat('abc', 'def'), 'abcdef')
1038 self.assertEqual(concat('abc', 'где'), 'abcгде')
1039 self.assertEqual(concat('абв', 'def'), 'абвdef')
1040 self.assertEqual(concat('абв', 'где'), 'абвгде')
1041 self.assertEqual(concat('a\0b', 'c\0d'), 'a\0bc\0d')
1042
1043 self.assertRaises(TypeError, concat, b'abc', 'def')
1044 self.assertRaises(TypeError, concat, 'abc', b'def')
1045 self.assertRaises(TypeError, concat, b'abc', b'def')
1046 self.assertRaises(TypeError, concat, [], 'def')
1047 self.assertRaises(TypeError, concat, 'abc', [])
1048 self.assertRaises(TypeError, concat, [], [])
1049 # CRASHES concat(NULL, 'def')
1050 # CRASHES concat('abc', NULL)
1051
1052 @support.cpython_only
1053 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1054 def test_split(self):
1055 """Test PyUnicode_Split()"""
1056 from _testlimitedcapi import unicode_split as split
1057
1058 self.assertEqual(split('a|b|c|d', '|'), ['a', 'b', 'c', 'd'])
1059 self.assertEqual(split('a|b|c|d', '|', 2), ['a', 'b', 'c|d'])
1060 self.assertEqual(split('a|b|c|d', '|', PY_SSIZE_T_MAX),
1061 ['a', 'b', 'c', 'd'])
1062 self.assertEqual(split('a|b|c|d', '|', -1), ['a', 'b', 'c', 'd'])
1063 self.assertEqual(split('a|b|c|d', '|', PY_SSIZE_T_MIN),
1064 ['a', 'b', 'c', 'd'])
1065 self.assertEqual(split('a|b|c|d', '\u20ac'), ['a|b|c|d'])
1066 self.assertEqual(split('a||b|c||d', '||'), ['a', 'b|c', 'd'])
1067 self.assertEqual(split('а|б|в|г', '|'), ['а', 'б', 'в', 'г'])
1068 self.assertEqual(split('абабагаламага', 'а'),
1069 ['', 'б', 'б', 'г', 'л', 'м', 'г', ''])
1070 self.assertEqual(split(' a\tb\nc\rd\ve\f', NULL),
1071 ['a', 'b', 'c', 'd', 'e'])
1072 self.assertEqual(split('a\x85b\xa0c\u1680d\u2000e', NULL),
1073 ['a', 'b', 'c', 'd', 'e'])
1074
1075 self.assertRaises(ValueError, split, 'a|b|c|d', '')
1076 self.assertRaises(TypeError, split, 'a|b|c|d', ord('|'))
1077 self.assertRaises(TypeError, split, [], '|')
1078 # CRASHES split(NULL, '|')
1079
1080 @support.cpython_only
1081 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1082 def test_rsplit(self):
1083 """Test PyUnicode_RSplit()"""
1084 from _testlimitedcapi import unicode_rsplit as rsplit
1085
1086 self.assertEqual(rsplit('a|b|c|d', '|'), ['a', 'b', 'c', 'd'])
1087 self.assertEqual(rsplit('a|b|c|d', '|', 2), ['a|b', 'c', 'd'])
1088 self.assertEqual(rsplit('a|b|c|d', '|', PY_SSIZE_T_MAX),
1089 ['a', 'b', 'c', 'd'])
1090 self.assertEqual(rsplit('a|b|c|d', '|', -1), ['a', 'b', 'c', 'd'])
1091 self.assertEqual(rsplit('a|b|c|d', '|', PY_SSIZE_T_MIN),
1092 ['a', 'b', 'c', 'd'])
1093 self.assertEqual(rsplit('a|b|c|d', '\u20ac'), ['a|b|c|d'])
1094 self.assertEqual(rsplit('a||b|c||d', '||'), ['a', 'b|c', 'd'])
1095 self.assertEqual(rsplit('а|б|в|г', '|'), ['а', 'б', 'в', 'г'])
1096 self.assertEqual(rsplit('абабагаламага', 'а'),
1097 ['', 'б', 'б', 'г', 'л', 'м', 'г', ''])
1098 self.assertEqual(rsplit('aжbжcжd', 'ж'), ['a', 'b', 'c', 'd'])
1099 self.assertEqual(rsplit(' a\tb\nc\rd\ve\f', NULL),
1100 ['a', 'b', 'c', 'd', 'e'])
1101 self.assertEqual(rsplit('a\x85b\xa0c\u1680d\u2000e', NULL),
1102 ['a', 'b', 'c', 'd', 'e'])
1103
1104 self.assertRaises(ValueError, rsplit, 'a|b|c|d', '')
1105 self.assertRaises(TypeError, rsplit, 'a|b|c|d', ord('|'))
1106 self.assertRaises(TypeError, rsplit, [], '|')
1107 # CRASHES rsplit(NULL, '|')
1108
1109 @support.cpython_only
1110 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1111 def test_partition(self):
1112 """Test PyUnicode_Partition()"""
1113 from _testlimitedcapi import unicode_partition as partition
1114
1115 self.assertEqual(partition('a|b|c', '|'), ('a', '|', 'b|c'))
1116 self.assertEqual(partition('a||b||c', '||'), ('a', '||', 'b||c'))
1117 self.assertEqual(partition('а|б|в', '|'), ('а', '|', 'б|в'))
1118 self.assertEqual(partition('кабан', 'а'), ('к', 'а', 'бан'))
1119 self.assertEqual(partition('aжbжc', 'ж'), ('a', 'ж', 'bжc'))
1120
1121 self.assertRaises(ValueError, partition, 'a|b|c', '')
1122 self.assertRaises(TypeError, partition, b'a|b|c', '|')
1123 self.assertRaises(TypeError, partition, 'a|b|c', b'|')
1124 self.assertRaises(TypeError, partition, 'a|b|c', ord('|'))
1125 self.assertRaises(TypeError, partition, [], '|')
1126 # CRASHES partition(NULL, '|')
1127 # CRASHES partition('a|b|c', NULL)
1128
1129 @support.cpython_only
1130 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1131 def test_rpartition(self):
1132 """Test PyUnicode_RPartition()"""
1133 from _testlimitedcapi import unicode_rpartition as rpartition
1134
1135 self.assertEqual(rpartition('a|b|c', '|'), ('a|b', '|', 'c'))
1136 self.assertEqual(rpartition('a||b||c', '||'), ('a||b', '||', 'c'))
1137 self.assertEqual(rpartition('а|б|в', '|'), ('а|б', '|', 'в'))
1138 self.assertEqual(rpartition('кабан', 'а'), ('каб', 'а', 'н'))
1139 self.assertEqual(rpartition('aжbжc', 'ж'), ('aжb', 'ж', 'c'))
1140
1141 self.assertRaises(ValueError, rpartition, 'a|b|c', '')
1142 self.assertRaises(TypeError, rpartition, b'a|b|c', '|')
1143 self.assertRaises(TypeError, rpartition, 'a|b|c', b'|')
1144 self.assertRaises(TypeError, rpartition, 'a|b|c', ord('|'))
1145 self.assertRaises(TypeError, rpartition, [], '|')
1146 # CRASHES rpartition(NULL, '|')
1147 # CRASHES rpartition('a|b|c', NULL)
1148
1149 @support.cpython_only
1150 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1151 def test_splitlines(self):
1152 """Test PyUnicode_SplitLines()"""
1153 from _testlimitedcapi import unicode_splitlines as splitlines
1154
1155 self.assertEqual(splitlines('a\nb\rc\r\nd'), ['a', 'b', 'c', 'd'])
1156 self.assertEqual(splitlines('a\nb\rc\r\nd', True),
1157 ['a\n', 'b\r', 'c\r\n', 'd'])
1158 self.assertEqual(splitlines('a\x85b\u2028c\u2029d'),
1159 ['a', 'b', 'c', 'd'])
1160 self.assertEqual(splitlines('a\x85b\u2028c\u2029d', True),
1161 ['a\x85', 'b\u2028', 'c\u2029', 'd'])
1162 self.assertEqual(splitlines('а\nб\rв\r\nг'), ['а', 'б', 'в', 'г'])
1163
1164 self.assertRaises(TypeError, splitlines, b'a\nb\rc\r\nd')
1165 # CRASHES splitlines(NULL)
1166
1167 @support.cpython_only
1168 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1169 def test_translate(self):
1170 """Test PyUnicode_Translate()"""
1171 from _testlimitedcapi import unicode_translate as translate
1172
1173 self.assertEqual(translate('abcd', {ord('a'): 'A', ord('b'): ord('B'), ord('c'): '<>'}), 'AB<>d')
1174 self.assertEqual(translate('абвг', {ord('а'): 'А', ord('б'): ord('Б'), ord('в'): '<>'}), 'АБ<>г')
1175 self.assertEqual(translate('abc', {}), 'abc')
1176 self.assertEqual(translate('abc', []), 'abc')
1177 self.assertRaises(UnicodeTranslateError, translate, 'abc', {ord('b'): None})
1178 self.assertRaises(UnicodeTranslateError, translate, 'abc', {ord('b'): None}, 'strict')
1179 self.assertRaises(LookupError, translate, 'abc', {ord('b'): None}, 'foo')
1180 self.assertEqual(translate('abc', {ord('b'): None}, 'ignore'), 'ac')
1181 self.assertEqual(translate('abc', {ord('b'): None}, 'replace'), 'a\ufffdc')
1182 self.assertEqual(translate('abc', {ord('b'): None}, 'backslashreplace'), r'a\x62c')
1183 # XXX Other error handlers do not support UnicodeTranslateError
1184 self.assertRaises(TypeError, translate, b'abc', [])
1185 self.assertRaises(TypeError, translate, 123, [])
1186 self.assertRaises(TypeError, translate, 'abc', {ord('a'): b'A'})
1187 self.assertRaises(TypeError, translate, 'abc', 123)
1188 self.assertRaises(TypeError, translate, 'abc', NULL)
1189 self.assertRaises(LookupError, translate, 'abc', {ord('b'): None}, 'foo')
1190 # CRASHES translate(NULL, [])
1191
1192 @support.cpython_only
1193 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1194 def test_join(self):
1195 """Test PyUnicode_Join()"""
1196 from _testlimitedcapi import unicode_join as join
1197 self.assertEqual(join('|', ['a', 'b', 'c']), 'a|b|c')
1198 self.assertEqual(join('|', ['a', '', 'c']), 'a||c')
1199 self.assertEqual(join('', ['a', 'b', 'c']), 'abc')
1200 self.assertEqual(join(NULL, ['a', 'b', 'c']), 'a b c')
1201 self.assertEqual(join('|', ['а', 'б', 'в']), 'а|б|в')
1202 self.assertEqual(join('ж', ['а', 'б', 'в']), 'ажбжв')
1203 self.assertRaises(TypeError, join, b'|', ['a', 'b', 'c'])
1204 self.assertRaises(TypeError, join, '|', [b'a', b'b', b'c'])
1205 self.assertRaises(TypeError, join, NULL, [b'a', b'b', b'c'])
1206 self.assertRaises(TypeError, join, '|', b'123')
1207 self.assertRaises(TypeError, join, '|', 123)
1208 self.assertRaises(SystemError, join, '|', NULL)
1209
1210 @support.cpython_only
1211 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1212 def test_count(self):
1213 """Test PyUnicode_Count()"""
1214 from _testlimitedcapi import unicode_count
1215
1216 for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1":
1217 for i, ch in enumerate(str):
1218 self.assertEqual(unicode_count(str, ch, 0, len(str)), 1)
1219
1220 str = "!>_<!"
1221 self.assertEqual(unicode_count(str, 'z', 0, len(str)), 0)
1222 self.assertEqual(unicode_count(str, '', 0, len(str)), len(str)+1)
1223 # start < end
1224 self.assertEqual(unicode_count(str, '!', 1, len(str)+1), 1)
1225 self.assertEqual(unicode_count(str, '!', 1, PY_SSIZE_T_MAX), 1)
1226 # start >= end
1227 self.assertEqual(unicode_count(str, '!', 0, 0), 0)
1228 self.assertEqual(unicode_count(str, '!', len(str), 0), 0)
1229 # negative
1230 self.assertEqual(unicode_count(str, '!', -len(str), -1), 1)
1231 self.assertEqual(unicode_count(str, '!', -len(str)-1, -1), 1)
1232 self.assertEqual(unicode_count(str, '!', PY_SSIZE_T_MIN, -1), 1)
1233 # bad arguments
1234 self.assertRaises(TypeError, unicode_count, str, b'!', 0, len(str))
1235 self.assertRaises(TypeError, unicode_count, b"!>_<!", '!', 0, len(str))
1236 self.assertRaises(TypeError, unicode_count, str, ord('!'), 0, len(str))
1237 self.assertRaises(TypeError, unicode_count, [], '!', 0, len(str), 1)
1238 # CRASHES unicode_count(NULL, '!', 0, len(str))
1239 # CRASHES unicode_count(str, NULL, 0, len(str))
1240
1241 @support.cpython_only
1242 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1243 def test_tailmatch(self):
1244 """Test PyUnicode_Tailmatch()"""
1245 from _testlimitedcapi import unicode_tailmatch as tailmatch
1246
1247 str = 'ababahalamaha'
1248 self.assertEqual(tailmatch(str, 'aba', 0, len(str), -1), 1)
1249 self.assertEqual(tailmatch(str, 'aha', 0, len(str), 1), 1)
1250
1251 self.assertEqual(tailmatch(str, 'aba', 0, PY_SSIZE_T_MAX, -1), 1)
1252 self.assertEqual(tailmatch(str, 'aba', -len(str), PY_SSIZE_T_MAX, -1), 1)
1253 self.assertEqual(tailmatch(str, 'aba', PY_SSIZE_T_MIN, len(str), -1), 1)
1254 self.assertEqual(tailmatch(str, 'aha', 0, PY_SSIZE_T_MAX, 1), 1)
1255 self.assertEqual(tailmatch(str, 'aha', PY_SSIZE_T_MIN, len(str), 1), 1)
1256
1257 self.assertEqual(tailmatch(str, 'z', 0, len(str), 1), 0)
1258 self.assertEqual(tailmatch(str, 'z', 0, len(str), -1), 0)
1259 self.assertEqual(tailmatch(str, '', 0, len(str), 1), 1)
1260 self.assertEqual(tailmatch(str, '', 0, len(str), -1), 1)
1261
1262 self.assertEqual(tailmatch(str, 'ba', 0, len(str)-1, -1), 0)
1263 self.assertEqual(tailmatch(str, 'ba', 1, len(str)-1, -1), 1)
1264 self.assertEqual(tailmatch(str, 'aba', 1, len(str)-1, -1), 0)
1265 self.assertEqual(tailmatch(str, 'ba', -len(str)+1, -1, -1), 1)
1266 self.assertEqual(tailmatch(str, 'ah', 0, len(str), 1), 0)
1267 self.assertEqual(tailmatch(str, 'ah', 0, len(str)-1, 1), 1)
1268 self.assertEqual(tailmatch(str, 'ah', -len(str), -1, 1), 1)
1269
1270 # bad arguments
1271 self.assertRaises(TypeError, tailmatch, str, ('aba', 'aha'), 0, len(str), -1)
1272 self.assertRaises(TypeError, tailmatch, str, ('aba', 'aha'), 0, len(str), 1)
1273 # CRASHES tailmatch(NULL, 'aba', 0, len(str), -1)
1274 # CRASHES tailmatch(str, NULL, 0, len(str), -1)
1275
1276 @support.cpython_only
1277 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1278 def test_find(self):
1279 """Test PyUnicode_Find()"""
1280 from _testlimitedcapi import unicode_find as find
1281
1282 for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1":
1283 for i, ch in enumerate(str):
1284 self.assertEqual(find(str, ch, 0, len(str), 1), i)
1285 self.assertEqual(find(str, ch, 0, len(str), -1), i)
1286
1287 str = "!>_<!"
1288 self.assertEqual(find(str, 'z', 0, len(str), 1), -1)
1289 self.assertEqual(find(str, 'z', 0, len(str), -1), -1)
1290 self.assertEqual(find(str, '', 0, len(str), 1), 0)
1291 self.assertEqual(find(str, '', 0, len(str), -1), len(str))
1292 # start < end
1293 self.assertEqual(find(str, '!', 1, len(str)+1, 1), 4)
1294 self.assertEqual(find(str, '!', 1, PY_SSIZE_T_MAX, 1), 4)
1295 self.assertEqual(find(str, '!', 0, len(str)+1, -1), 4)
1296 self.assertEqual(find(str, '!', 0, PY_SSIZE_T_MAX, -1), 4)
1297 # start >= end
1298 self.assertEqual(find(str, '!', 0, 0, 1), -1)
1299 self.assertEqual(find(str, '!', 0, 0, -1), -1)
1300 self.assertEqual(find(str, '!', len(str), 0, 1), -1)
1301 self.assertEqual(find(str, '!', len(str), 0, -1), -1)
1302 # negative
1303 self.assertEqual(find(str, '!', -len(str), -1, 1), 0)
1304 self.assertEqual(find(str, '!', -len(str), -1, -1), 0)
1305 self.assertEqual(find(str, '!', PY_SSIZE_T_MIN, -1, 1), 0)
1306 self.assertEqual(find(str, '!', PY_SSIZE_T_MIN, -1, -1), 0)
1307 self.assertEqual(find(str, '!', PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, 1), 0)
1308 self.assertEqual(find(str, '!', PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, -1), 4)
1309 # bad arguments
1310 self.assertRaises(TypeError, find, str, b'!', 0, len(str), 1)
1311 self.assertRaises(TypeError, find, b"!>_<!", '!', 0, len(str), 1)
1312 self.assertRaises(TypeError, find, str, ord('!'), 0, len(str), 1)
1313 self.assertRaises(TypeError, find, [], '!', 0, len(str), 1)
1314 # CRASHES find(NULL, '!', 0, len(str), 1)
1315 # CRASHES find(str, NULL, 0, len(str), 1)
1316
1317 @support.cpython_only
1318 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1319 def test_findchar(self):
1320 """Test PyUnicode_FindChar()"""
1321 from _testlimitedcapi import unicode_findchar
1322
1323 for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1":
1324 for i, ch in enumerate(str):
1325 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), 1), i)
1326 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), -1), i)
1327
1328 str = "!>_<!"
1329 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), 1), -1)
1330 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), -1), -1)
1331 # start < end
1332 self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, 1), 4)
1333 self.assertEqual(unicode_findchar(str, ord('!'), 1, PY_SSIZE_T_MAX, 1), 4)
1334 self.assertEqual(unicode_findchar(str, ord('!'), 0, len(str)+1, -1), 4)
1335 self.assertEqual(unicode_findchar(str, ord('!'), 0, PY_SSIZE_T_MAX, -1), 4)
1336 # start >= end
1337 self.assertEqual(unicode_findchar(str, ord('!'), 0, 0, 1), -1)
1338 self.assertEqual(unicode_findchar(str, ord('!'), 0, 0, -1), -1)
1339 self.assertEqual(unicode_findchar(str, ord('!'), len(str), 0, 1), -1)
1340 self.assertEqual(unicode_findchar(str, ord('!'), len(str), 0, -1), -1)
1341 # negative
1342 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, 1), 0)
1343 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, -1), 0)
1344 self.assertEqual(unicode_findchar(str, ord('!'), PY_SSIZE_T_MIN, -1, 1), 0)
1345 self.assertEqual(unicode_findchar(str, ord('!'), PY_SSIZE_T_MIN, -1, -1), 0)
1346 self.assertEqual(unicode_findchar(str, ord('!'), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, 1), 0)
1347 self.assertEqual(unicode_findchar(str, ord('!'), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, -1), 4)
1348 # bad arguments
1349 # CRASHES unicode_findchar(b"!>_<!", ord('!'), 0, len(str), 1)
1350 # CRASHES unicode_findchar([], ord('!'), 0, len(str), 1)
1351 # CRASHES unicode_findchar(NULL, ord('!'), 0, len(str), 1), 1)
1352
1353 @support.cpython_only
1354 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1355 def test_replace(self):
1356 """Test PyUnicode_Replace()"""
1357 from _testlimitedcapi import unicode_replace as replace
1358
1359 str = 'abracadabra'
1360 self.assertEqual(replace(str, 'a', '='), '=br=c=d=br=')
1361 self.assertEqual(replace(str, 'a', '<>'), '<>br<>c<>d<>br<>')
1362 self.assertEqual(replace(str, 'abra', '='), '=cad=')
1363 self.assertEqual(replace(str, 'a', '=', 2), '=br=cadabra')
1364 self.assertEqual(replace(str, 'a', '=', 0), str)
1365 self.assertEqual(replace(str, 'a', '=', PY_SSIZE_T_MAX), '=br=c=d=br=')
1366 self.assertEqual(replace(str, 'a', '=', -1), '=br=c=d=br=')
1367 self.assertEqual(replace(str, 'a', '=', PY_SSIZE_T_MIN), '=br=c=d=br=')
1368 self.assertEqual(replace(str, 'z', '='), str)
1369 self.assertEqual(replace(str, '', '='), '=a=b=r=a=c=a=d=a=b=r=a=')
1370 self.assertEqual(replace(str, 'a', 'ж'), 'жbrжcжdжbrж')
1371 self.assertEqual(replace('абабагаламага', 'а', '='), '=б=б=г=л=м=г=')
1372 self.assertEqual(replace('Баден-Баден', 'Баден', 'Baden'), 'Baden-Baden')
1373 # bad arguments
1374 self.assertRaises(TypeError, replace, 'a', 'a', b'=')
1375 self.assertRaises(TypeError, replace, 'a', b'a', '=')
1376 self.assertRaises(TypeError, replace, b'a', 'a', '=')
1377 self.assertRaises(TypeError, replace, 'a', 'a', ord('='))
1378 self.assertRaises(TypeError, replace, 'a', ord('a'), '=')
1379 self.assertRaises(TypeError, replace, [], 'a', '=')
1380 # CRASHES replace('a', 'a', NULL)
1381 # CRASHES replace('a', NULL, '=')
1382 # CRASHES replace(NULL, 'a', '=')
1383
1384 @support.cpython_only
1385 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1386 def test_compare(self):
1387 """Test PyUnicode_Compare()"""
1388 from _testlimitedcapi import unicode_compare as compare
1389
1390 self.assertEqual(compare('abc', 'abc'), 0)
1391 self.assertEqual(compare('abc', 'def'), -1)
1392 self.assertEqual(compare('def', 'abc'), 1)
1393 self.assertEqual(compare('abc', 'abc\0def'), -1)
1394 self.assertEqual(compare('abc\0def', 'abc\0def'), 0)
1395 self.assertEqual(compare('абв', 'abc'), 1)
1396
1397 self.assertRaises(TypeError, compare, b'abc', 'abc')
1398 self.assertRaises(TypeError, compare, 'abc', b'abc')
1399 self.assertRaises(TypeError, compare, b'abc', b'abc')
1400 self.assertRaises(TypeError, compare, [], 'abc')
1401 self.assertRaises(TypeError, compare, 'abc', [])
1402 self.assertRaises(TypeError, compare, [], [])
1403 # CRASHES compare(NULL, 'abc')
1404 # CRASHES compare('abc', NULL)
1405
1406 @support.cpython_only
1407 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1408 def test_comparewithasciistring(self):
1409 """Test PyUnicode_CompareWithASCIIString()"""
1410 from _testlimitedcapi import unicode_comparewithasciistring as comparewithasciistring
1411
1412 self.assertEqual(comparewithasciistring('abc', b'abc'), 0)
1413 self.assertEqual(comparewithasciistring('abc', b'def'), -1)
1414 self.assertEqual(comparewithasciistring('def', b'abc'), 1)
1415 self.assertEqual(comparewithasciistring('abc', b'abc\0def'), 0)
1416 self.assertEqual(comparewithasciistring('abc\0def', b'abc\0def'), 1)
1417 self.assertEqual(comparewithasciistring('абв', b'abc'), 1)
1418
1419 # CRASHES comparewithasciistring(b'abc', b'abc')
1420 # CRASHES comparewithasciistring([], b'abc')
1421 # CRASHES comparewithasciistring(NULL, b'abc')
1422
1423 @support.cpython_only
1424 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1425 def test_equaltoutf8(self):
1426 # Test PyUnicode_EqualToUTF8()
1427 from _testlimitedcapi import unicode_equaltoutf8 as equaltoutf8
1428 from _testlimitedcapi import unicode_asutf8andsize as asutf8andsize
1429
1430 strings = [
1431 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
1432 '\U0001f600\U0001f601\U0001f602',
1433 '\U0010ffff',
1434 ]
1435 for s in strings:
1436 # Call PyUnicode_AsUTF8AndSize() which creates the UTF-8
1437 # encoded string cached in the Unicode object.
1438 asutf8andsize(s, 0)
1439 b = s.encode()
1440 self.assertEqual(equaltoutf8(s, b), 1) # Use the UTF-8 cache.
1441 s2 = b.decode() # New Unicode object without the UTF-8 cache.
1442 self.assertEqual(equaltoutf8(s2, b), 1)
1443 self.assertEqual(equaltoutf8(s + 'x', b + b'x'), 1)
1444 self.assertEqual(equaltoutf8(s + 'x', b + b'y'), 0)
1445 self.assertEqual(equaltoutf8(s, b + b'\0'), 1)
1446 self.assertEqual(equaltoutf8(s2, b + b'\0'), 1)
1447 self.assertEqual(equaltoutf8(s + '\0', b + b'\0'), 0)
1448 self.assertEqual(equaltoutf8(s + '\0', b), 0)
1449 self.assertEqual(equaltoutf8(s2, b + b'x'), 0)
1450 self.assertEqual(equaltoutf8(s2, b[:-1]), 0)
1451 self.assertEqual(equaltoutf8(s2, b[:-1] + b'x'), 0)
1452
1453 self.assertEqual(equaltoutf8('', b''), 1)
1454 self.assertEqual(equaltoutf8('', b'\0'), 1)
1455
1456 # embedded null chars/bytes
1457 self.assertEqual(equaltoutf8('abc', b'abc\0def\0'), 1)
1458 self.assertEqual(equaltoutf8('a\0bc', b'abc'), 0)
1459 self.assertEqual(equaltoutf8('abc', b'a\0bc'), 0)
1460
1461 # Surrogate characters are always treated as not equal
1462 self.assertEqual(equaltoutf8('\udcfe',
1463 '\udcfe'.encode("utf8", "surrogateescape")), 0)
1464 self.assertEqual(equaltoutf8('\udcfe',
1465 '\udcfe'.encode("utf8", "surrogatepass")), 0)
1466 self.assertEqual(equaltoutf8('\ud801',
1467 '\ud801'.encode("utf8", "surrogatepass")), 0)
1468
1469 @support.cpython_only
1470 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1471 def test_equaltoutf8andsize(self):
1472 # Test PyUnicode_EqualToUTF8AndSize()
1473 from _testlimitedcapi import unicode_equaltoutf8andsize as equaltoutf8andsize
1474 from _testlimitedcapi import unicode_asutf8andsize as asutf8andsize
1475
1476 strings = [
1477 'abc', '\xa1\xa2\xa3', '\u4f60\u597d\u4e16',
1478 '\U0001f600\U0001f601\U0001f602',
1479 '\U0010ffff',
1480 ]
1481 for s in strings:
1482 # Call PyUnicode_AsUTF8AndSize() which creates the UTF-8
1483 # encoded string cached in the Unicode object.
1484 asutf8andsize(s, 0)
1485 b = s.encode()
1486 self.assertEqual(equaltoutf8andsize(s, b), 1) # Use the UTF-8 cache.
1487 s2 = b.decode() # New Unicode object without the UTF-8 cache.
1488 self.assertEqual(equaltoutf8andsize(s2, b), 1)
1489 self.assertEqual(equaltoutf8andsize(s + 'x', b + b'x'), 1)
1490 self.assertEqual(equaltoutf8andsize(s + 'x', b + b'y'), 0)
1491 self.assertEqual(equaltoutf8andsize(s, b + b'\0'), 0)
1492 self.assertEqual(equaltoutf8andsize(s2, b + b'\0'), 0)
1493 self.assertEqual(equaltoutf8andsize(s + '\0', b + b'\0'), 1)
1494 self.assertEqual(equaltoutf8andsize(s + '\0', b), 0)
1495 self.assertEqual(equaltoutf8andsize(s2, b + b'x'), 0)
1496 self.assertEqual(equaltoutf8andsize(s2, b[:-1]), 0)
1497 self.assertEqual(equaltoutf8andsize(s2, b[:-1] + b'x'), 0)
1498 # Not null-terminated,
1499 self.assertEqual(equaltoutf8andsize(s, b + b'x', len(b)), 1)
1500 self.assertEqual(equaltoutf8andsize(s2, b + b'x', len(b)), 1)
1501 self.assertEqual(equaltoutf8andsize(s + '\0', b + b'\0x', len(b) + 1), 1)
1502 self.assertEqual(equaltoutf8andsize(s2, b, len(b) - 1), 0)
1503 self.assertEqual(equaltoutf8andsize(s, b, -1), 0)
1504 self.assertEqual(equaltoutf8andsize(s, b, PY_SSIZE_T_MAX), 0)
1505 self.assertEqual(equaltoutf8andsize(s, b, PY_SSIZE_T_MIN), 0)
1506
1507 self.assertEqual(equaltoutf8andsize('', b''), 1)
1508 self.assertEqual(equaltoutf8andsize('', b'\0'), 0)
1509 self.assertEqual(equaltoutf8andsize('', b'x', 0), 1)
1510
1511 # embedded null chars/bytes
1512 self.assertEqual(equaltoutf8andsize('abc\0def', b'abc\0def'), 1)
1513 self.assertEqual(equaltoutf8andsize('abc\0def\0', b'abc\0def\0'), 1)
1514
1515 # Surrogate characters are always treated as not equal
1516 self.assertEqual(equaltoutf8andsize('\udcfe',
1517 '\udcfe'.encode("utf8", "surrogateescape")), 0)
1518 self.assertEqual(equaltoutf8andsize('\udcfe',
1519 '\udcfe'.encode("utf8", "surrogatepass")), 0)
1520 self.assertEqual(equaltoutf8andsize('\ud801',
1521 '\ud801'.encode("utf8", "surrogatepass")), 0)
1522
1523 def check_not_equal_encoding(text, encoding):
1524 self.assertEqual(equaltoutf8andsize(text, text.encode(encoding)), 0)
1525 self.assertNotEqual(text.encode(encoding), text.encode("utf8"))
1526
1527 # Strings encoded to other encodings are not equal to expected UTF8-encoding string
1528 check_not_equal_encoding('Stéphane', 'latin1')
1529 check_not_equal_encoding('Stéphane', 'utf-16-le') # embedded null characters
1530 check_not_equal_encoding('北京市', 'gbk')
1531
1532 # CRASHES equaltoutf8andsize('abc', b'abc', -1)
1533 # CRASHES equaltoutf8andsize(b'abc', b'abc')
1534 # CRASHES equaltoutf8andsize([], b'abc')
1535 # CRASHES equaltoutf8andsize(NULL, b'abc')
1536 # CRASHES equaltoutf8andsize('abc', NULL)
1537
1538 @support.cpython_only
1539 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1540 def test_richcompare(self):
1541 """Test PyUnicode_RichCompare()"""
1542 from _testlimitedcapi import unicode_richcompare as richcompare
1543
1544 LT, LE, EQ, NE, GT, GE = range(6)
1545 strings = ('abc', 'абв', '\U0001f600', 'abc\0')
1546 for s1 in strings:
1547 for s2 in strings:
1548 self.assertIs(richcompare(s1, s2, LT), s1 < s2)
1549 self.assertIs(richcompare(s1, s2, LE), s1 <= s2)
1550 self.assertIs(richcompare(s1, s2, EQ), s1 == s2)
1551 self.assertIs(richcompare(s1, s2, NE), s1 != s2)
1552 self.assertIs(richcompare(s1, s2, GT), s1 > s2)
1553 self.assertIs(richcompare(s1, s2, GE), s1 >= s2)
1554
1555 for op in LT, LE, EQ, NE, GT, GE:
1556 self.assertIs(richcompare(b'abc', 'abc', op), NotImplemented)
1557 self.assertIs(richcompare('abc', b'abc', op), NotImplemented)
1558 self.assertIs(richcompare(b'abc', b'abc', op), NotImplemented)
1559 self.assertIs(richcompare([], 'abc', op), NotImplemented)
1560 self.assertIs(richcompare('abc', [], op), NotImplemented)
1561 self.assertIs(richcompare([], [], op), NotImplemented)
1562
1563 # CRASHES richcompare(NULL, 'abc', op)
1564 # CRASHES richcompare('abc', NULL, op)
1565
1566 @support.cpython_only
1567 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1568 def test_format(self):
1569 """Test PyUnicode_Format()"""
1570 from _testlimitedcapi import unicode_format as format
1571
1572 self.assertEqual(format('x=%d!', 42), 'x=42!')
1573 self.assertEqual(format('x=%d!', (42,)), 'x=42!')
1574 self.assertEqual(format('x=%d y=%s!', (42, [])), 'x=42 y=[]!')
1575
1576 self.assertRaises(SystemError, format, 'x=%d!', NULL)
1577 self.assertRaises(SystemError, format, NULL, 42)
1578
1579 @support.cpython_only
1580 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1581 def test_contains(self):
1582 """Test PyUnicode_Contains()"""
1583 from _testlimitedcapi import unicode_contains as contains
1584
1585 self.assertEqual(contains('abcd', ''), 1)
1586 self.assertEqual(contains('abcd', 'b'), 1)
1587 self.assertEqual(contains('abcd', 'x'), 0)
1588 self.assertEqual(contains('abcd', 'ж'), 0)
1589 self.assertEqual(contains('abcd', '\0'), 0)
1590 self.assertEqual(contains('abc\0def', '\0'), 1)
1591 self.assertEqual(contains('abcd', 'bc'), 1)
1592
1593 self.assertRaises(TypeError, contains, b'abcd', 'b')
1594 self.assertRaises(TypeError, contains, 'abcd', b'b')
1595 self.assertRaises(TypeError, contains, b'abcd', b'b')
1596 self.assertRaises(TypeError, contains, [], 'b')
1597 self.assertRaises(TypeError, contains, 'abcd', ord('b'))
1598 # CRASHES contains(NULL, 'b')
1599 # CRASHES contains('abcd', NULL)
1600
1601 @support.cpython_only
1602 @unittest.skipIf(_testlimitedcapi is None, 'need _testlimitedcapi module')
1603 def test_isidentifier(self):
1604 """Test PyUnicode_IsIdentifier()"""
1605 from _testlimitedcapi import unicode_isidentifier as isidentifier
1606
1607 self.assertEqual(isidentifier("a"), 1)
1608 self.assertEqual(isidentifier("b0"), 1)
1609 self.assertEqual(isidentifier("µ"), 1)
1610 self.assertEqual(isidentifier("𝔘𝔫𝔦𝔠𝔬𝔡𝔢"), 1)
1611
1612 self.assertEqual(isidentifier(""), 0)
1613 self.assertEqual(isidentifier(" "), 0)
1614 self.assertEqual(isidentifier("["), 0)
1615 self.assertEqual(isidentifier("©"), 0)
1616 self.assertEqual(isidentifier("0"), 0)
1617 self.assertEqual(isidentifier("32M"), 0)
1618
1619 # CRASHES isidentifier(b"a")
1620 # CRASHES isidentifier([])
1621 # CRASHES isidentifier(NULL)
1622
1623 @support.cpython_only
1624 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
1625 def test_copycharacters(self):
1626 """Test PyUnicode_CopyCharacters()"""
1627 from _testcapi import unicode_copycharacters
1628
1629 strings = [
1630 # all strings have exactly 5 characters
1631 'abcde', '\xa1\xa2\xa3\xa4\xa5',
1632 '\u4f60\u597d\u4e16\u754c\uff01',
1633 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
1634 ]
1635
1636 for idx, from_ in enumerate(strings):
1637 # wide -> narrow: exceed maxchar limitation
1638 for to in strings[:idx]:
1639 self.assertRaises(
1640 SystemError,
1641 unicode_copycharacters, to, 0, from_, 0, 5
1642 )
1643 # same kind
1644 for from_start in range(5):
1645 self.assertEqual(
1646 unicode_copycharacters(from_, 0, from_, from_start, 5),
1647 (from_[from_start:from_start+5].ljust(5, '\0'),
1648 5-from_start)
1649 )
1650 for to_start in range(5):
1651 self.assertEqual(
1652 unicode_copycharacters(from_, to_start, from_, to_start, 5),
1653 (from_[to_start:to_start+5].rjust(5, '\0'),
1654 5-to_start)
1655 )
1656 # narrow -> wide
1657 # Tests omitted since this creates invalid strings.
1658
1659 s = strings[0]
1660 self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
1661 self.assertRaises(IndexError, unicode_copycharacters, s, PY_SSIZE_T_MAX, s, 0, 5)
1662 self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
1663 self.assertRaises(IndexError, unicode_copycharacters, s, PY_SSIZE_T_MIN, s, 0, 5)
1664 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
1665 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, PY_SSIZE_T_MAX, 5)
1666 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
1667 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, PY_SSIZE_T_MIN, 5)
1668 self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
1669 self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, PY_SSIZE_T_MAX)
1670 self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
1671 self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, PY_SSIZE_T_MIN)
1672 self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
1673 self.assertRaises(SystemError, unicode_copycharacters, s, 0, [], 0, 0)
1674 # CRASHES unicode_copycharacters(s, 0, NULL, 0, 0)
1675 # TODO: Test PyUnicode_CopyCharacters() with non-unicode and
1676 # non-modifiable unicode as "to".
1677
1678 @support.cpython_only
1679 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
1680 def test_pep393_utf8_caching_bug(self):
1681 # Issue #25709: Problem with string concatenation and utf-8 cache
1682 from _testcapi import getargs_s_hash
1683 for k in 0x24, 0xa4, 0x20ac, 0x1f40d:
1684 s = ''
1685 for i in range(5):
1686 # Due to CPython specific optimization the 's' string can be
1687 # resized in-place.
1688 s += chr(k)
1689 # Parsing with the "s#" format code calls indirectly
1690 # PyUnicode_AsUTF8AndSize() which creates the UTF-8
1691 # encoded string cached in the Unicode object.
1692 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
1693 # Check that the second call returns the same result
1694 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
1695
1696
1697 if __name__ == "__main__":
1698 unittest.main()