Debian Codegraph @

lib-python/3/test/test_capi/test_unicode.py

raw symbols SCIP
1 import unittest
2 import sys
3 from test import support
4 from test.support import import_helper
5
6 try:
7 import _testcapi
8 except ImportError:
9 _testcapi = None
10
11
12 class CAPITest(unittest.TestCase):
13
14 # Test PyUnicode_FromFormat()
15
16 @support.impl_detail('no pythonapi in PyPy', pypy=False)
17 def test_from_format(self):
18 import_helper.import_module('ctypes')
19 from ctypes import (
20 c_char_p,
21 pythonapi, py_object, sizeof,
22 c_int, c_long, c_longlong, c_ssize_t,
23 c_uint, c_ulong, c_ulonglong, c_size_t, c_void_p)
24 name = "PyUnicode_FromFormat"
25 _PyUnicode_FromFormat = getattr(pythonapi, name)
26 _PyUnicode_FromFormat.argtypes = (c_char_p,)
27 _PyUnicode_FromFormat.restype = py_object
28
29 def PyUnicode_FromFormat(format, *args):
30 cargs = tuple(
31 py_object(arg) if isinstance(arg, str) else arg
32 for arg in args)
33 return _PyUnicode_FromFormat(format, *cargs)
34
35 def check_format(expected, format, *args):
36 text = PyUnicode_FromFormat(format, *args)
37 self.assertEqual(expected, text)
38
39 # ascii format, non-ascii argument
40 check_format('ascii\x7f=unicode\xe9',
41 b'ascii\x7f=%U', 'unicode\xe9')
42
43 # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
44 # raises an error
45 self.assertRaisesRegex(ValueError,
46 r'^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
47 'string, got a non-ASCII byte: 0xe9$',
48 PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
49
50 # test "%c"
51 check_format('\uabcd',
52 b'%c', c_int(0xabcd))
53 check_format('\U0010ffff',
54 b'%c', c_int(0x10ffff))
55 with self.assertRaises(OverflowError):
56 PyUnicode_FromFormat(b'%c', c_int(0x110000))
57 # Issue #18183
58 check_format('\U00010000\U00100000',
59 b'%c%c', c_int(0x10000), c_int(0x100000))
60
61 # test "%"
62 check_format('%',
63 b'%')
64 check_format('%',
65 b'%%')
66 check_format('%s',
67 b'%%s')
68 check_format('[%]',
69 b'[%%]')
70 check_format('%abc',
71 b'%%%s', b'abc')
72
73 # truncated string
74 check_format('abc',
75 b'%.3s', b'abcdef')
76 check_format('abc[\ufffd',
77 b'%.5s', 'abc[\u20ac]'.encode('utf8'))
78 check_format("'\\u20acABC'",
79 b'%A', '\u20acABC')
80 check_format("'\\u20",
81 b'%.5A', '\u20acABCDEF')
82 check_format("'\u20acABC'",
83 b'%R', '\u20acABC')
84 check_format("'\u20acA",
85 b'%.3R', '\u20acABCDEF')
86 check_format('\u20acAB',
87 b'%.3S', '\u20acABCDEF')
88 check_format('\u20acAB',
89 b'%.3U', '\u20acABCDEF')
90 check_format('\u20acAB',
91 b'%.3V', '\u20acABCDEF', None)
92 check_format('abc[\ufffd',
93 b'%.5V', None, 'abc[\u20ac]'.encode('utf8'))
94
95 # following tests comes from #7330
96 # test width modifier and precision modifier with %S
97 check_format("repr= abc",
98 b'repr=%5S', 'abc')
99 check_format("repr=ab",
100 b'repr=%.2S', 'abc')
101 check_format("repr= ab",
102 b'repr=%5.2S', 'abc')
103
104 # test width modifier and precision modifier with %R
105 check_format("repr= 'abc'",
106 b'repr=%8R', 'abc')
107 check_format("repr='ab",
108 b'repr=%.3R', 'abc')
109 check_format("repr= 'ab",
110 b'repr=%5.3R', 'abc')
111
112 # test width modifier and precision modifier with %A
113 check_format("repr= 'abc'",
114 b'repr=%8A', 'abc')
115 check_format("repr='ab",
116 b'repr=%.3A', 'abc')
117 check_format("repr= 'ab",
118 b'repr=%5.3A', 'abc')
119
120 # test width modifier and precision modifier with %s
121 check_format("repr= abc",
122 b'repr=%5s', b'abc')
123 check_format("repr=ab",
124 b'repr=%.2s', b'abc')
125 check_format("repr= ab",
126 b'repr=%5.2s', b'abc')
127
128 # test width modifier and precision modifier with %U
129 check_format("repr= abc",
130 b'repr=%5U', 'abc')
131 check_format("repr=ab",
132 b'repr=%.2U', 'abc')
133 check_format("repr= ab",
134 b'repr=%5.2U', 'abc')
135
136 # test width modifier and precision modifier with %V
137 check_format("repr= abc",
138 b'repr=%5V', 'abc', b'123')
139 check_format("repr=ab",
140 b'repr=%.2V', 'abc', b'123')
141 check_format("repr= ab",
142 b'repr=%5.2V', 'abc', b'123')
143 check_format("repr= 123",
144 b'repr=%5V', None, b'123')
145 check_format("repr=12",
146 b'repr=%.2V', None, b'123')
147 check_format("repr= 12",
148 b'repr=%5.2V', None, b'123')
149
150 # test integer formats (%i, %d, %u)
151 check_format('010',
152 b'%03i', c_int(10))
153 check_format('0010',
154 b'%0.4i', c_int(10))
155 check_format('-123',
156 b'%i', c_int(-123))
157 check_format('-123',
158 b'%li', c_long(-123))
159 check_format('-123',
160 b'%lli', c_longlong(-123))
161 check_format('-123',
162 b'%zi', c_ssize_t(-123))
163
164 check_format('-123',
165 b'%d', c_int(-123))
166 check_format('-123',
167 b'%ld', c_long(-123))
168 check_format('-123',
169 b'%lld', c_longlong(-123))
170 check_format('-123',
171 b'%zd', c_ssize_t(-123))
172
173 check_format('123',
174 b'%u', c_uint(123))
175 check_format('123',
176 b'%lu', c_ulong(123))
177 check_format('123',
178 b'%llu', c_ulonglong(123))
179 check_format('123',
180 b'%zu', c_size_t(123))
181
182 # test long output
183 min_longlong = -(2 ** (8 * sizeof(c_longlong) - 1))
184 max_longlong = -min_longlong - 1
185 check_format(str(min_longlong),
186 b'%lld', c_longlong(min_longlong))
187 check_format(str(max_longlong),
188 b'%lld', c_longlong(max_longlong))
189 max_ulonglong = 2 ** (8 * sizeof(c_ulonglong)) - 1
190 check_format(str(max_ulonglong),
191 b'%llu', c_ulonglong(max_ulonglong))
192 PyUnicode_FromFormat(b'%p', c_void_p(-1))
193
194 # test padding (width and/or precision)
195 check_format('123'.rjust(10, '0'),
196 b'%010i', c_int(123))
197 check_format('123'.rjust(100),
198 b'%100i', c_int(123))
199 check_format('123'.rjust(100, '0'),
200 b'%.100i', c_int(123))
201 check_format('123'.rjust(80, '0').rjust(100),
202 b'%100.80i', c_int(123))
203
204 check_format('123'.rjust(10, '0'),
205 b'%010u', c_uint(123))
206 check_format('123'.rjust(100),
207 b'%100u', c_uint(123))
208 check_format('123'.rjust(100, '0'),
209 b'%.100u', c_uint(123))
210 check_format('123'.rjust(80, '0').rjust(100),
211 b'%100.80u', c_uint(123))
212
213 check_format('123'.rjust(10, '0'),
214 b'%010x', c_int(0x123))
215 check_format('123'.rjust(100),
216 b'%100x', c_int(0x123))
217 check_format('123'.rjust(100, '0'),
218 b'%.100x', c_int(0x123))
219 check_format('123'.rjust(80, '0').rjust(100),
220 b'%100.80x', c_int(0x123))
221
222 # test %A
223 check_format(r"%A:'abc\xe9\uabcd\U0010ffff'",
224 b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
225
226 # test %V
227 check_format('repr=abc',
228 b'repr=%V', 'abc', b'xyz')
229
230 # test %p
231 # We cannot test the exact result,
232 # because it returns a hex representation of a C pointer,
233 # which is going to be different each time. But, we can test the format.
234 p_format_regex = r'^0x[a-zA-Z0-9]{3,}$'
235 p_format1 = PyUnicode_FromFormat(b'%p', 'abc')
236 self.assertIsInstance(p_format1, str)
237 self.assertRegex(p_format1, p_format_regex)
238
239 p_format2 = PyUnicode_FromFormat(b'%p %p', '123456', b'xyz')
240 self.assertIsInstance(p_format2, str)
241 self.assertRegex(p_format2,
242 r'0x[a-zA-Z0-9]{3,} 0x[a-zA-Z0-9]{3,}')
243
244 # Extra args are ignored:
245 p_format3 = PyUnicode_FromFormat(b'%p', '123456', None, b'xyz')
246 self.assertIsInstance(p_format3, str)
247 self.assertRegex(p_format3, p_format_regex)
248
249 # Test string decode from parameter of %s using utf-8.
250 # b'\xe4\xba\xba\xe6\xb0\x91' is utf-8 encoded byte sequence of
251 # '\u4eba\u6c11'
252 check_format('repr=\u4eba\u6c11',
253 b'repr=%V', None, b'\xe4\xba\xba\xe6\xb0\x91')
254
255 #Test replace error handler.
256 check_format('repr=abc\ufffd',
257 b'repr=%V', None, b'abc\xff')
258
259 # not supported: copy the raw format string. these tests are just here
260 # to check for crashes and should not be considered as specifications
261 check_format('%s',
262 b'%1%s', b'abc')
263 check_format('%1abc',
264 b'%1abc')
265 check_format('%+i',
266 b'%+i', c_int(10))
267 check_format('%.%s',
268 b'%.%s', b'abc')
269
270 # Issue #33817: empty strings
271 check_format('',
272 b'')
273 check_format('',
274 b'%s', b'')
275
276 # Test PyUnicode_AsWideChar()
277 @support.cpython_only
278 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
279 def test_aswidechar(self):
280 from _testcapi import unicode_aswidechar
281 import_helper.import_module('ctypes')
282 from ctypes import c_wchar, sizeof
283
284 wchar, size = unicode_aswidechar('abcdef', 2)
285 self.assertEqual(size, 2)
286 self.assertEqual(wchar, 'ab')
287
288 wchar, size = unicode_aswidechar('abc', 3)
289 self.assertEqual(size, 3)
290 self.assertEqual(wchar, 'abc')
291
292 wchar, size = unicode_aswidechar('abc', 4)
293 self.assertEqual(size, 3)
294 self.assertEqual(wchar, 'abc\0')
295
296 wchar, size = unicode_aswidechar('abc', 10)
297 self.assertEqual(size, 3)
298 self.assertEqual(wchar, 'abc\0')
299
300 wchar, size = unicode_aswidechar('abc\0def', 20)
301 self.assertEqual(size, 7)
302 self.assertEqual(wchar, 'abc\0def\0')
303
304 nonbmp = chr(0x10ffff)
305 if sizeof(c_wchar) == 2:
306 buflen = 3
307 nchar = 2
308 else: # sizeof(c_wchar) == 4
309 buflen = 2
310 nchar = 1
311 wchar, size = unicode_aswidechar(nonbmp, buflen)
312 self.assertEqual(size, nchar)
313 self.assertEqual(wchar, nonbmp + '\0')
314
315 # Test PyUnicode_AsWideCharString()
316 @support.cpython_only
317 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
318 def test_aswidecharstring(self):
319 from _testcapi import unicode_aswidecharstring
320 import_helper.import_module('ctypes')
321 from ctypes import c_wchar, sizeof
322
323 wchar, size = unicode_aswidecharstring('abc')
324 self.assertEqual(size, 3)
325 self.assertEqual(wchar, 'abc\0')
326
327 wchar, size = unicode_aswidecharstring('abc\0def')
328 self.assertEqual(size, 7)
329 self.assertEqual(wchar, 'abc\0def\0')
330
331 nonbmp = chr(0x10ffff)
332 if sizeof(c_wchar) == 2:
333 nchar = 2
334 else: # sizeof(c_wchar) == 4
335 nchar = 1
336 wchar, size = unicode_aswidecharstring(nonbmp)
337 self.assertEqual(size, nchar)
338 self.assertEqual(wchar, nonbmp + '\0')
339
340 # Test PyUnicode_AsUCS4()
341 @support.cpython_only
342 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
343 def test_asucs4(self):
344 from _testcapi import unicode_asucs4
345 for s in ['abc', '\xa1\xa2', '\u4f60\u597d', 'a\U0001f600',
346 'a\ud800b\udfffc', '\ud834\udd1e']:
347 l = len(s)
348 self.assertEqual(unicode_asucs4(s, l, True), s+'\0')
349 self.assertEqual(unicode_asucs4(s, l, False), s+'\uffff')
350 self.assertEqual(unicode_asucs4(s, l+1, True), s+'\0\uffff')
351 self.assertEqual(unicode_asucs4(s, l+1, False), s+'\0\uffff')
352 self.assertRaises(SystemError, unicode_asucs4, s, l-1, True)
353 self.assertRaises(SystemError, unicode_asucs4, s, l-2, False)
354 s = '\0'.join([s, s])
355 self.assertEqual(unicode_asucs4(s, len(s), True), s+'\0')
356 self.assertEqual(unicode_asucs4(s, len(s), False), s+'\uffff')
357
358 # Test PyUnicode_AsUTF8()
359 @support.cpython_only
360 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
361 def test_asutf8(self):
362 from _testcapi import unicode_asutf8
363
364 bmp = '\u0100'
365 bmp2 = '\uffff'
366 nonbmp = chr(0x10ffff)
367
368 self.assertEqual(unicode_asutf8(bmp), b'\xc4\x80')
369 self.assertEqual(unicode_asutf8(bmp2), b'\xef\xbf\xbf')
370 self.assertEqual(unicode_asutf8(nonbmp), b'\xf4\x8f\xbf\xbf')
371 self.assertRaises(UnicodeEncodeError, unicode_asutf8, 'a\ud800b\udfffc')
372
373 # Test PyUnicode_AsUTF8AndSize()
374 @support.cpython_only
375 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
376 def test_asutf8andsize(self):
377 from _testcapi import unicode_asutf8andsize
378
379 bmp = '\u0100'
380 bmp2 = '\uffff'
381 nonbmp = chr(0x10ffff)
382
383 self.assertEqual(unicode_asutf8andsize(bmp), (b'\xc4\x80', 2))
384 self.assertEqual(unicode_asutf8andsize(bmp2), (b'\xef\xbf\xbf', 3))
385 self.assertEqual(unicode_asutf8andsize(nonbmp), (b'\xf4\x8f\xbf\xbf', 4))
386 self.assertRaises(UnicodeEncodeError, unicode_asutf8andsize, 'a\ud800b\udfffc')
387
388 # Test PyUnicode_FindChar()
389 @support.cpython_only
390 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
391 def test_findchar(self):
392 from _testcapi import unicode_findchar
393
394 for str in "\xa1", "\u8000\u8080", "\ud800\udc02", "\U0001f100\U0001f1f1":
395 for i, ch in enumerate(str):
396 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), 1), i)
397 self.assertEqual(unicode_findchar(str, ord(ch), 0, len(str), -1), i)
398
399 str = "!>_<!"
400 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), 1), -1)
401 self.assertEqual(unicode_findchar(str, 0x110000, 0, len(str), -1), -1)
402 # start < end
403 self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, 1), 4)
404 self.assertEqual(unicode_findchar(str, ord('!'), 1, len(str)+1, -1), 4)
405 # start >= end
406 self.assertEqual(unicode_findchar(str, ord('!'), 0, 0, 1), -1)
407 self.assertEqual(unicode_findchar(str, ord('!'), len(str), 0, 1), -1)
408 # negative
409 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, 1), 0)
410 self.assertEqual(unicode_findchar(str, ord('!'), -len(str), -1, -1), 0)
411
412 # Test PyUnicode_CopyCharacters()
413 @support.cpython_only
414 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
415 def test_copycharacters(self):
416 from _testcapi import unicode_copycharacters
417
418 strings = [
419 'abcde', '\xa1\xa2\xa3\xa4\xa5',
420 '\u4f60\u597d\u4e16\u754c\uff01',
421 '\U0001f600\U0001f601\U0001f602\U0001f603\U0001f604'
422 ]
423
424 for idx, from_ in enumerate(strings):
425 # wide -> narrow: exceed maxchar limitation
426 for to in strings[:idx]:
427 self.assertRaises(
428 SystemError,
429 unicode_copycharacters, to, 0, from_, 0, 5
430 )
431 # same kind
432 for from_start in range(5):
433 self.assertEqual(
434 unicode_copycharacters(from_, 0, from_, from_start, 5),
435 (from_[from_start:from_start+5].ljust(5, '\0'),
436 5-from_start)
437 )
438 for to_start in range(5):
439 self.assertEqual(
440 unicode_copycharacters(from_, to_start, from_, to_start, 5),
441 (from_[to_start:to_start+5].rjust(5, '\0'),
442 5-to_start)
443 )
444 # narrow -> wide
445 # Tests omitted since this creates invalid strings.
446
447 s = strings[0]
448 self.assertRaises(IndexError, unicode_copycharacters, s, 6, s, 0, 5)
449 self.assertRaises(IndexError, unicode_copycharacters, s, -1, s, 0, 5)
450 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, 6, 5)
451 self.assertRaises(IndexError, unicode_copycharacters, s, 0, s, -1, 5)
452 self.assertRaises(SystemError, unicode_copycharacters, s, 1, s, 0, 5)
453 self.assertRaises(SystemError, unicode_copycharacters, s, 0, s, 0, -1)
454 self.assertRaises(SystemError, unicode_copycharacters, s, 0, b'', 0, 0)
455
456 @support.cpython_only
457 @unittest.skipIf(_testcapi is None, 'need _testcapi module')
458 def test_pep393_utf8_caching_bug(self):
459 # Issue #25709: Problem with string concatenation and utf-8 cache
460 from _testcapi import getargs_s_hash
461 for k in 0x24, 0xa4, 0x20ac, 0x1f40d:
462 s = ''
463 for i in range(5):
464 # Due to CPython specific optimization the 's' string can be
465 # resized in-place.
466 s += chr(k)
467 # Parsing with the "s#" format code calls indirectly
468 # PyUnicode_AsUTF8AndSize() which creates the UTF-8
469 # encoded string cached in the Unicode object.
470 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
471 # Check that the second call returns the same result
472 self.assertEqual(getargs_s_hash(s), chr(k).encode() * (i + 1))
473
474
475 if __name__ == "__main__":
476 unittest.main()