Debian Codegraph @

Lib/test/test_capi/test_long.py

raw
1 import unittest
2 import sys
3 import test.support as support
4
5 from test.support import import_helper
6
7 # Skip this test if the _testcapi and _testlimitedcapi modules isn't available.
8 _testcapi = import_helper.import_module('_testcapi')
9 _testlimitedcapi = import_helper.import_module('_testlimitedcapi')
10
11 NULL = None
12
13 class IntSubclass(int):
14 pass
15
16 class Index:
17 def __init__(self, value):
18 self.value = value
19
20 def __index__(self):
21 return self.value
22
23 # use __index__(), not __int__()
24 class MyIndexAndInt:
25 def __index__(self):
26 return 10
27 def __int__(self):
28 return 22
29
30
31 class LongTests(unittest.TestCase):
32
33 def test_compact(self):
34 for n in {
35 # Edge cases
36 *(2**n for n in range(66)),
37 *(-2**n for n in range(66)),
38 *(2**n - 1 for n in range(66)),
39 *(-2**n + 1 for n in range(66)),
40 # Essentially random
41 *(37**n for n in range(14)),
42 *(-37**n for n in range(14)),
43 }:
44 with self.subTest(n=n):
45 is_compact, value = _testcapi.call_long_compact_api(n)
46 if is_compact:
47 self.assertEqual(n, value)
48
49 def test_compact_known(self):
50 # Sanity-check some implementation details (we don't guarantee
51 # that these are/aren't compact)
52 self.assertEqual(_testcapi.call_long_compact_api(-1), (True, -1))
53 self.assertEqual(_testcapi.call_long_compact_api(0), (True, 0))
54 self.assertEqual(_testcapi.call_long_compact_api(256), (True, 256))
55 self.assertEqual(_testcapi.call_long_compact_api(sys.maxsize),
56 (False, -1))
57
58 def test_long_check(self):
59 # Test PyLong_Check()
60 check = _testlimitedcapi.pylong_check
61 self.assertTrue(check(1))
62 self.assertTrue(check(123456789012345678901234567890))
63 self.assertTrue(check(-1))
64 self.assertTrue(check(True))
65 self.assertTrue(check(IntSubclass(1)))
66 self.assertFalse(check(1.0))
67 self.assertFalse(check(object()))
68 # CRASHES check(NULL)
69
70 def test_long_checkexact(self):
71 # Test PyLong_CheckExact()
72 check = _testlimitedcapi.pylong_checkexact
73 self.assertTrue(check(1))
74 self.assertTrue(check(123456789012345678901234567890))
75 self.assertTrue(check(-1))
76 self.assertFalse(check(True))
77 self.assertFalse(check(IntSubclass(1)))
78 self.assertFalse(check(1.0))
79 self.assertFalse(check(object()))
80 # CRASHES check(NULL)
81
82 def test_long_fromdouble(self):
83 # Test PyLong_FromDouble()
84 fromdouble = _testlimitedcapi.pylong_fromdouble
85 float_max = sys.float_info.max
86 for value in (5.0, 5.1, 5.9, -5.1, -5.9, 0.0, -0.0, float_max, -float_max):
87 with self.subTest(value=value):
88 self.assertEqual(fromdouble(value), int(value))
89 self.assertRaises(OverflowError, fromdouble, float('inf'))
90 self.assertRaises(OverflowError, fromdouble, float('-inf'))
91 self.assertRaises(ValueError, fromdouble, float('nan'))
92
93 def test_long_fromvoidptr(self):
94 # Test PyLong_FromVoidPtr()
95 fromvoidptr = _testlimitedcapi.pylong_fromvoidptr
96 obj = object()
97 x = fromvoidptr(obj)
98 y = fromvoidptr(NULL)
99 self.assertIsInstance(x, int)
100 self.assertGreaterEqual(x, 0)
101 self.assertIsInstance(y, int)
102 self.assertEqual(y, 0)
103 self.assertNotEqual(x, y)
104
105 def test_long_fromstring(self):
106 # Test PyLong_FromString()
107 fromstring = _testlimitedcapi.pylong_fromstring
108 self.assertEqual(fromstring(b'123', 10), (123, 3))
109 self.assertEqual(fromstring(b'cafe', 16), (0xcafe, 4))
110 self.assertEqual(fromstring(b'xyz', 36), (44027, 3))
111 self.assertEqual(fromstring(b'123', 0), (123, 3))
112 self.assertEqual(fromstring(b'0xcafe', 0), (0xcafe, 6))
113 self.assertRaises(ValueError, fromstring, b'cafe', 0)
114 self.assertEqual(fromstring(b'-123', 10), (-123, 4))
115 self.assertEqual(fromstring(b' -123 ', 10), (-123, 6))
116 self.assertEqual(fromstring(b'1_23', 10), (123, 4))
117 self.assertRaises(ValueError, fromstring, b'- 123', 10)
118 self.assertRaises(ValueError, fromstring, b'', 10)
119
120 self.assertRaises(ValueError, fromstring, b'123', 1)
121 self.assertRaises(ValueError, fromstring, b'123', -1)
122 self.assertRaises(ValueError, fromstring, b'123', 37)
123
124 self.assertRaises(ValueError, fromstring, '١٢٣٤٥٦٧٨٩٠'.encode(), 0)
125 self.assertRaises(ValueError, fromstring, '١٢٣٤٥٦٧٨٩٠'.encode(), 16)
126
127 self.assertEqual(fromstring(b'123\x00', 0), (123, 3))
128 self.assertEqual(fromstring(b'123\x00456', 0), (123, 3))
129 self.assertEqual(fromstring(b'123\x00', 16), (0x123, 3))
130 self.assertEqual(fromstring(b'123\x00456', 16), (0x123, 3))
131
132 # CRASHES fromstring(NULL, 0)
133 # CRASHES fromstring(NULL, 16)
134
135 def test_long_fromunicodeobject(self):
136 # Test PyLong_FromUnicodeObject()
137 fromunicodeobject = _testcapi.pylong_fromunicodeobject
138 self.assertEqual(fromunicodeobject('123', 10), 123)
139 self.assertEqual(fromunicodeobject('cafe', 16), 0xcafe)
140 self.assertEqual(fromunicodeobject('xyz', 36), 44027)
141 self.assertEqual(fromunicodeobject('123', 0), 123)
142 self.assertEqual(fromunicodeobject('0xcafe', 0), 0xcafe)
143 self.assertRaises(ValueError, fromunicodeobject, 'cafe', 0)
144 self.assertEqual(fromunicodeobject('-123', 10), -123)
145 self.assertEqual(fromunicodeobject(' -123 ', 10), -123)
146 self.assertEqual(fromunicodeobject('1_23', 10), 123)
147 self.assertRaises(ValueError, fromunicodeobject, '- 123', 10)
148 self.assertRaises(ValueError, fromunicodeobject, '', 10)
149
150 self.assertRaises(ValueError, fromunicodeobject, '123', 1)
151 self.assertRaises(ValueError, fromunicodeobject, '123', -1)
152 self.assertRaises(ValueError, fromunicodeobject, '123', 37)
153
154 self.assertEqual(fromunicodeobject('١٢٣٤٥٦٧٨٩٠', 0), 1234567890)
155 self.assertEqual(fromunicodeobject('١٢٣٤٥٦٧٨٩٠', 16), 0x1234567890)
156
157 self.assertRaises(ValueError, fromunicodeobject, '123\x00', 0)
158 self.assertRaises(ValueError, fromunicodeobject, '123\x00456', 0)
159 self.assertRaises(ValueError, fromunicodeobject, '123\x00', 16)
160 self.assertRaises(ValueError, fromunicodeobject, '123\x00456', 16)
161
162 # CRASHES fromunicodeobject(NULL, 0)
163 # CRASHES fromunicodeobject(NULL, 16)
164
165 def check_long_asint(self, func, min_val, max_val, *,
166 use_index=True,
167 mask=False,
168 negative_value_error=OverflowError):
169 # round trip (object -> C integer -> object)
170 values = (0, 1, 1234, max_val)
171 if min_val < 0:
172 values += (-1, min_val)
173 for value in values:
174 with self.subTest(value=value):
175 self.assertEqual(func(value), value)
176 self.assertEqual(func(IntSubclass(value)), value)
177 if use_index:
178 self.assertEqual(func(Index(value)), value)
179
180 if use_index:
181 self.assertEqual(func(MyIndexAndInt()), 10)
182 else:
183 self.assertRaises(TypeError, func, Index(42))
184 self.assertRaises(TypeError, func, MyIndexAndInt())
185
186 if mask:
187 self.assertEqual(func(min_val - 1), max_val)
188 self.assertEqual(func(max_val + 1), min_val)
189 self.assertEqual(func(-1 << 1000), 0)
190 self.assertEqual(func(1 << 1000), 0)
191 else:
192 self.assertRaises(negative_value_error, func, min_val - 1)
193 self.assertRaises(negative_value_error, func, -1 << 1000)
194 self.assertRaises(OverflowError, func, max_val + 1)
195 self.assertRaises(OverflowError, func, 1 << 1000)
196 self.assertRaises(TypeError, func, 1.0)
197 self.assertRaises(TypeError, func, b'2')
198 self.assertRaises(TypeError, func, '3')
199 self.assertRaises(SystemError, func, NULL)
200
201 def check_long_asintandoverflow(self, func, min_val, max_val):
202 # round trip (object -> C integer -> object)
203 for value in (min_val, max_val, -1, 0, 1, 1234):
204 with self.subTest(value=value):
205 self.assertEqual(func(value), (value, 0))
206 self.assertEqual(func(IntSubclass(value)), (value, 0))
207 self.assertEqual(func(Index(value)), (value, 0))
208
209 self.assertEqual(func(MyIndexAndInt()), (10, 0))
210
211 self.assertEqual(func(min_val - 1), (-1, -1))
212 self.assertEqual(func(max_val + 1), (-1, +1))
213 self.assertRaises(SystemError, func, None)
214 self.assertRaises(TypeError, func, 1.0)
215
216 def test_long_asint(self):
217 # Test PyLong_AsInt()
218 PyLong_AsInt = _testlimitedcapi.PyLong_AsInt
219 from _testcapi import INT_MIN, INT_MAX
220 self.check_long_asint(PyLong_AsInt, INT_MIN, INT_MAX)
221
222 def test_long_aslong(self):
223 # Test PyLong_AsLong() and PyLong_FromLong()
224 aslong = _testlimitedcapi.pylong_aslong
225 from _testcapi import LONG_MIN, LONG_MAX
226 self.check_long_asint(aslong, LONG_MIN, LONG_MAX)
227
228 def test_long_aslongandoverflow(self):
229 # Test PyLong_AsLongAndOverflow()
230 aslongandoverflow = _testlimitedcapi.pylong_aslongandoverflow
231 from _testcapi import LONG_MIN, LONG_MAX
232 self.check_long_asintandoverflow(aslongandoverflow, LONG_MIN, LONG_MAX)
233
234 def test_long_asunsignedlong(self):
235 # Test PyLong_AsUnsignedLong() and PyLong_FromUnsignedLong()
236 asunsignedlong = _testlimitedcapi.pylong_asunsignedlong
237 from _testcapi import ULONG_MAX
238 self.check_long_asint(asunsignedlong, 0, ULONG_MAX,
239 use_index=False)
240
241 def test_long_asunsignedlongmask(self):
242 # Test PyLong_AsUnsignedLongMask()
243 asunsignedlongmask = _testlimitedcapi.pylong_asunsignedlongmask
244 from _testcapi import ULONG_MAX
245 self.check_long_asint(asunsignedlongmask, 0, ULONG_MAX, mask=True)
246
247 def test_long_aslonglong(self):
248 # Test PyLong_AsLongLong() and PyLong_FromLongLong()
249 aslonglong = _testlimitedcapi.pylong_aslonglong
250 from _testcapi import LLONG_MIN, LLONG_MAX
251 self.check_long_asint(aslonglong, LLONG_MIN, LLONG_MAX)
252
253 def test_long_aslonglongandoverflow(self):
254 # Test PyLong_AsLongLongAndOverflow()
255 aslonglongandoverflow = _testlimitedcapi.pylong_aslonglongandoverflow
256 from _testcapi import LLONG_MIN, LLONG_MAX
257 self.check_long_asintandoverflow(aslonglongandoverflow, LLONG_MIN, LLONG_MAX)
258
259 def test_long_asunsignedlonglong(self):
260 # Test PyLong_AsUnsignedLongLong() and PyLong_FromUnsignedLongLong()
261 asunsignedlonglong = _testlimitedcapi.pylong_asunsignedlonglong
262 from _testcapi import ULLONG_MAX
263 self.check_long_asint(asunsignedlonglong, 0, ULLONG_MAX, use_index=False)
264
265 def test_long_asunsignedlonglongmask(self):
266 # Test PyLong_AsUnsignedLongLongMask()
267 asunsignedlonglongmask = _testlimitedcapi.pylong_asunsignedlonglongmask
268 from _testcapi import ULLONG_MAX
269 self.check_long_asint(asunsignedlonglongmask, 0, ULLONG_MAX, mask=True)
270
271 def test_long_as_ssize_t(self):
272 # Test PyLong_AsSsize_t() and PyLong_FromSsize_t()
273 as_ssize_t = _testlimitedcapi.pylong_as_ssize_t
274 from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX
275 self.check_long_asint(as_ssize_t, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX,
276 use_index=False)
277
278 def test_long_as_size_t(self):
279 # Test PyLong_AsSize_t() and PyLong_FromSize_t()
280 as_size_t = _testlimitedcapi.pylong_as_size_t
281 from _testcapi import SIZE_MAX
282 self.check_long_asint(as_size_t, 0, SIZE_MAX, use_index=False)
283
284 def test_long_asdouble(self):
285 # Test PyLong_AsDouble()
286 asdouble = _testlimitedcapi.pylong_asdouble
287 MAX = int(sys.float_info.max)
288 for value in (-MAX, MAX, -1, 0, 1, 1234):
289 with self.subTest(value=value):
290 self.assertEqual(asdouble(value), float(value))
291 self.assertIsInstance(asdouble(value), float)
292
293 self.assertEqual(asdouble(IntSubclass(42)), 42.0)
294 self.assertRaises(TypeError, asdouble, Index(42))
295 self.assertRaises(TypeError, asdouble, MyIndexAndInt())
296
297 self.assertRaises(OverflowError, asdouble, 2 * MAX)
298 self.assertRaises(OverflowError, asdouble, -2 * MAX)
299 self.assertRaises(TypeError, asdouble, 1.0)
300 self.assertRaises(TypeError, asdouble, b'2')
301 self.assertRaises(TypeError, asdouble, '3')
302 self.assertRaises(SystemError, asdouble, NULL)
303
304 def test_long_asvoidptr(self):
305 # Test PyLong_AsVoidPtr()
306 fromvoidptr = _testlimitedcapi.pylong_fromvoidptr
307 asvoidptr = _testlimitedcapi.pylong_asvoidptr
308 obj = object()
309 x = fromvoidptr(obj)
310 y = fromvoidptr(NULL)
311 self.assertIs(asvoidptr(x), obj)
312 self.assertIs(asvoidptr(y), NULL)
313 self.assertIs(asvoidptr(IntSubclass(x)), obj)
314
315 # negative values
316 M = (1 << _testcapi.SIZEOF_VOID_P * 8)
317 if x >= M//2:
318 self.assertIs(asvoidptr(x - M), obj)
319 if y >= M//2:
320 self.assertIs(asvoidptr(y - M), NULL)
321
322 self.assertRaises(TypeError, asvoidptr, Index(x))
323 self.assertRaises(TypeError, asvoidptr, object())
324 self.assertRaises(OverflowError, asvoidptr, 2**1000)
325 self.assertRaises(OverflowError, asvoidptr, -2**1000)
326 # CRASHES asvoidptr(NULL)
327
328 def _test_long_aspid(self, aspid):
329 # Test PyLong_AsPid()
330 from _testcapi import SIZEOF_PID_T
331 bits = 8 * SIZEOF_PID_T
332 PID_T_MIN = -2**(bits-1)
333 PID_T_MAX = 2**(bits-1) - 1
334 self.check_long_asint(aspid, PID_T_MIN, PID_T_MAX)
335
336 def test_long_aspid(self):
337 self._test_long_aspid(_testcapi.pylong_aspid)
338
339 def test_long_aspid_limited(self):
340 self._test_long_aspid(_testlimitedcapi.pylong_aspid)
341
342 def test_long_asnativebytes(self):
343 import math
344 from _testcapi import (
345 pylong_asnativebytes as asnativebytes,
346 SIZE_MAX,
347 )
348
349 # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot
350 SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8)
351 MAX_SSIZE = 2 ** (SZ * 8 - 1) - 1
352 MAX_USIZE = 2 ** (SZ * 8) - 1
353 if support.verbose:
354 print(f"SIZEOF_SIZE={SZ}\n{MAX_SSIZE=:016X}\n{MAX_USIZE=:016X}")
355
356 # These tests check that the requested buffer size is correct.
357 # This matches our current implementation: We only specify that the
358 # return value is a size *sufficient* to hold the result when queried
359 # using n_bytes=0. If our implementation changes, feel free to update
360 # the expectations here -- or loosen them to be range checks.
361 # (i.e. 0 *could* be stored in 1 byte and 512 in 2)
362 for v, expect in [
363 (0, SZ),
364 (512, SZ),
365 (-512, SZ),
366 (MAX_SSIZE, SZ),
367 (MAX_USIZE, SZ + 1),
368 (-MAX_SSIZE, SZ),
369 (-MAX_USIZE, SZ + 1),
370 (2**255-1, 32),
371 (-(2**255-1), 32),
372 (2**255, 33),
373 (-(2**255), 33), # if you ask, we'll say 33, but 32 would do
374 (2**256-1, 33),
375 (-(2**256-1), 33),
376 (2**256, 33),
377 (-(2**256), 33),
378 ]:
379 with self.subTest(f"sizeof-{v:X}"):
380 buffer = bytearray(b"\x5a")
381 self.assertEqual(expect, asnativebytes(v, buffer, 0, -1),
382 "PyLong_AsNativeBytes(v, <unknown>, 0, -1)")
383 self.assertEqual(buffer, b"\x5a",
384 "buffer overwritten when it should not have been")
385 # Also check via the __index__ path.
386 # We pass Py_ASNATIVEBYTES_NATIVE_ENDIAN | ALLOW_INDEX
387 self.assertEqual(expect, asnativebytes(Index(v), buffer, 0, 3 | 16),
388 "PyLong_AsNativeBytes(Index(v), <unknown>, 0, -1)")
389 self.assertEqual(buffer, b"\x5a",
390 "buffer overwritten when it should not have been")
391
392 # Test that we populate n=2 bytes but do not overwrite more.
393 buffer = bytearray(b"\x99"*3)
394 self.assertEqual(2, asnativebytes(4, buffer, 2, 0), # BE
395 "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 0) // BE")
396 self.assertEqual(buffer, b"\x00\x04\x99")
397 self.assertEqual(2, asnativebytes(4, buffer, 2, 1), # LE
398 "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 1) // LE")
399 self.assertEqual(buffer, b"\x04\x00\x99")
400
401 # We request as many bytes as `expect_be` contains, and always check
402 # the result (both big and little endian). We check the return value
403 # independently, since the buffer should always be filled correctly even
404 # if we need more bytes
405 for v, expect_be, expect_n in [
406 (0, b'\x00', 1),
407 (0, b'\x00' * 2, 2),
408 (0, b'\x00' * 8, min(8, SZ)),
409 (1, b'\x01', 1),
410 (1, b'\x00' * 10 + b'\x01', min(11, SZ)),
411 (42, b'\x2a', 1),
412 (42, b'\x00' * 10 + b'\x2a', min(11, SZ)),
413 (-1, b'\xff', 1),
414 (-1, b'\xff' * 10, min(11, SZ)),
415 (-42, b'\xd6', 1),
416 (-42, b'\xff' * 10 + b'\xd6', min(11, SZ)),
417 # Extracts 255 into a single byte, but requests 2
418 # (this is currently a special case, and "should" request SZ)
419 (255, b'\xff', 2),
420 (255, b'\x00\xff', 2),
421 (256, b'\x01\x00', 2),
422 (0x80, b'\x00' * 7 + b'\x80', min(8, SZ)),
423 # Extracts successfully (unsigned), but requests 9 bytes
424 (2**63, b'\x80' + b'\x00' * 7, 9),
425 (2**63, b'\x00\x80' + b'\x00' * 7, 9),
426 # Extracts into 8 bytes, but if you provide 9 we'll say 9
427 (-2**63, b'\x80' + b'\x00' * 7, 8),
428 (-2**63, b'\xff\x80' + b'\x00' * 7, 9),
429
430 (2**255-1, b'\x7f' + b'\xff' * 31, 32),
431 (-(2**255-1), b'\x80' + b'\x00' * 30 + b'\x01', 32),
432 # Request extra bytes, but result says we only needed 32
433 (-(2**255-1), b'\xff\x80' + b'\x00' * 30 + b'\x01', 32),
434 (-(2**255-1), b'\xff\xff\x80' + b'\x00' * 30 + b'\x01', 32),
435
436 # Extracting 256 bits of integer will request 33 bytes, but still
437 # copy as many bits as possible into the buffer. So we *can* copy
438 # into a 32-byte buffer, though negative number may be unrecoverable
439 (2**256-1, b'\xff' * 32, 33),
440 (2**256-1, b'\x00' + b'\xff' * 32, 33),
441 (-(2**256-1), b'\x00' * 31 + b'\x01', 33),
442 (-(2**256-1), b'\xff' + b'\x00' * 31 + b'\x01', 33),
443 (-(2**256-1), b'\xff\xff' + b'\x00' * 31 + b'\x01', 33),
444 # However, -2**255 precisely will extract into 32 bytes and return
445 # success. For bigger buffers, it will still succeed, but will
446 # return 33
447 (-(2**255), b'\x80' + b'\x00' * 31, 32),
448 (-(2**255), b'\xff\x80' + b'\x00' * 31, 33),
449
450 # The classic "Windows HRESULT as negative number" case
451 # HRESULT hr;
452 # PyLong_AsNativeBytes(<-2147467259>, &hr, sizeof(HRESULT), -1)
453 # assert(hr == E_FAIL)
454 (-2147467259, b'\x80\x00\x40\x05', 4),
455 ]:
456 with self.subTest(f"{v:X}-{len(expect_be)}bytes"):
457 n = len(expect_be)
458 # Fill the buffer with dummy data to ensure all bytes
459 # are overwritten.
460 buffer = bytearray(b"\xa5"*n)
461 expect_le = expect_be[::-1]
462
463 self.assertEqual(expect_n, asnativebytes(v, buffer, n, 0),
464 f"PyLong_AsNativeBytes(v, buffer, {n}, <big>)")
465 self.assertEqual(expect_be, buffer[:n], "<big>")
466 self.assertEqual(expect_n, asnativebytes(v, buffer, n, 1),
467 f"PyLong_AsNativeBytes(v, buffer, {n}, <little>)")
468 self.assertEqual(expect_le, buffer[:n], "<little>")
469
470 # Test cases that do not request size for a sign bit when we pass the
471 # Py_ASNATIVEBYTES_UNSIGNED_BUFFER flag
472 for v, expect_be, expect_n in [
473 (255, b'\xff', 1),
474 # We pass a 2 byte buffer so it just uses the whole thing
475 (255, b'\x00\xff', 2),
476
477 (2**63, b'\x80' + b'\x00' * 7, 8),
478 # We pass a 9 byte buffer so it uses the whole thing
479 (2**63, b'\x00\x80' + b'\x00' * 7, 9),
480
481 (2**256-1, b'\xff' * 32, 32),
482 # We pass a 33 byte buffer so it uses the whole thing
483 (2**256-1, b'\x00' + b'\xff' * 32, 33),
484 ]:
485 with self.subTest(f"{v:X}-{len(expect_be)}bytes-unsigned"):
486 n = len(expect_be)
487 buffer = bytearray(b"\xa5"*n)
488 self.assertEqual(expect_n, asnativebytes(v, buffer, n, 4),
489 f"PyLong_AsNativeBytes(v, buffer, {n}, <big|unsigned>)")
490 self.assertEqual(expect_n, asnativebytes(v, buffer, n, 5),
491 f"PyLong_AsNativeBytes(v, buffer, {n}, <little|unsigned>)")
492
493 # Ensure Py_ASNATIVEBYTES_REJECT_NEGATIVE raises on negative value
494 with self.assertRaises(ValueError):
495 asnativebytes(-1, buffer, 0, 8)
496
497 # Ensure omitting Py_ASNATIVEBYTES_ALLOW_INDEX raises on __index__ value
498 with self.assertRaises(TypeError):
499 asnativebytes(Index(1), buffer, 0, -1)
500 with self.assertRaises(TypeError):
501 asnativebytes(Index(1), buffer, 0, 3)
502
503 # Check a few error conditions. These are validated in code, but are
504 # unspecified in docs, so if we make changes to the implementation, it's
505 # fine to just update these tests rather than preserve the behaviour.
506 with self.assertRaises(TypeError):
507 asnativebytes('not a number', buffer, 0, -1)
508
509 def test_long_asnativebytes_fuzz(self):
510 import math
511 from random import Random
512 from _testcapi import (
513 pylong_asnativebytes as asnativebytes,
514 SIZE_MAX,
515 )
516
517 # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot
518 SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8)
519
520 rng = Random()
521 # Allocate bigger buffer than actual values are going to be
522 buffer = bytearray(260)
523
524 for _ in range(1000):
525 n = rng.randrange(1, 256)
526 bytes_be = bytes([
527 # Ensure the most significant byte is nonzero
528 rng.randrange(1, 256),
529 *[rng.randrange(256) for _ in range(n - 1)]
530 ])
531 bytes_le = bytes_be[::-1]
532 v = int.from_bytes(bytes_le, 'little')
533
534 expect_1 = expect_2 = (SZ, n)
535 if bytes_be[0] & 0x80:
536 # All values are positive, so if MSB is set, expect extra bit
537 # when we request the size or have a large enough buffer
538 expect_1 = (SZ, n + 1)
539 # When passing Py_ASNATIVEBYTES_UNSIGNED_BUFFER, we expect the
540 # return to be exactly the right size.
541 expect_2 = (n,)
542
543 try:
544 actual = asnativebytes(v, buffer, 0, -1)
545 self.assertIn(actual, expect_1)
546
547 actual = asnativebytes(v, buffer, len(buffer), 0)
548 self.assertIn(actual, expect_1)
549 self.assertEqual(bytes_be, buffer[-n:])
550
551 actual = asnativebytes(v, buffer, len(buffer), 1)
552 self.assertIn(actual, expect_1)
553 self.assertEqual(bytes_le, buffer[:n])
554
555 actual = asnativebytes(v, buffer, n, 4)
556 self.assertIn(actual, expect_2, bytes_be.hex())
557 actual = asnativebytes(v, buffer, n, 5)
558 self.assertIn(actual, expect_2, bytes_be.hex())
559 except AssertionError as ex:
560 value_hex = ''.join(reversed([
561 f'{b:02X}{"" if i % 8 else "_"}'
562 for i, b in enumerate(bytes_le, start=1)
563 ])).strip('_')
564 if support.verbose:
565 print()
566 print(n, 'bytes')
567 print('hex =', value_hex)
568 print('int =', v)
569 raise
570 raise AssertionError(f"Value: 0x{value_hex}") from ex
571
572 def test_long_fromnativebytes(self):
573 import math
574 from _testcapi import (
575 pylong_fromnativebytes as fromnativebytes,
576 SIZE_MAX,
577 )
578
579 # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot
580 SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8)
581 MAX_SSIZE = 2 ** (SZ * 8 - 1) - 1
582 MAX_USIZE = 2 ** (SZ * 8) - 1
583
584 for v_be, expect_s, expect_u in [
585 (b'\x00', 0, 0),
586 (b'\x01', 1, 1),
587 (b'\xff', -1, 255),
588 (b'\x00\xff', 255, 255),
589 (b'\xff\xff', -1, 65535),
590 ]:
591 with self.subTest(f"{expect_s}-{expect_u:X}-{len(v_be)}bytes"):
592 n = len(v_be)
593 v_le = v_be[::-1]
594
595 self.assertEqual(expect_s, fromnativebytes(v_be, n, 0, 1),
596 f"PyLong_FromNativeBytes(buffer, {n}, <big>)")
597 self.assertEqual(expect_s, fromnativebytes(v_le, n, 1, 1),
598 f"PyLong_FromNativeBytes(buffer, {n}, <little>)")
599 self.assertEqual(expect_u, fromnativebytes(v_be, n, 0, 0),
600 f"PyLong_FromUnsignedNativeBytes(buffer, {n}, <big>)")
601 self.assertEqual(expect_u, fromnativebytes(v_le, n, 1, 0),
602 f"PyLong_FromUnsignedNativeBytes(buffer, {n}, <little>)")
603
604 # Check native endian when the result would be the same either
605 # way and we can test it.
606 if v_be == v_le:
607 self.assertEqual(expect_s, fromnativebytes(v_be, n, -1, 1),
608 f"PyLong_FromNativeBytes(buffer, {n}, <native>)")
609 self.assertEqual(expect_u, fromnativebytes(v_be, n, -1, 0),
610 f"PyLong_FromUnsignedNativeBytes(buffer, {n}, <native>)")
611
612 # Swap the unsigned request for tests and use the
613 # Py_ASNATIVEBYTES_UNSIGNED_BUFFER flag instead
614 self.assertEqual(expect_u, fromnativebytes(v_be, n, 4, 1),
615 f"PyLong_FromNativeBytes(buffer, {n}, <big|unsigned>)")
616
617
618 if __name__ == "__main__":
619 unittest.main()