Debian Codegraph @

Lib/test/test_int.py

raw
1 import sys
2 import time
3
4 import unittest
5 from unittest import mock
6 from test import support
7 from test.support.numbers import (
8 VALID_UNDERSCORE_LITERALS,
9 INVALID_UNDERSCORE_LITERALS,
10 )
11
12 try:
13 import _pylong
14 except ImportError:
15 _pylong = None
16
17 L = [
18 ('0', 0),
19 ('1', 1),
20 ('9', 9),
21 ('10', 10),
22 ('99', 99),
23 ('100', 100),
24 ('314', 314),
25 (' 314', 314),
26 ('314 ', 314),
27 (' \t\t 314 \t\t ', 314),
28 (repr(sys.maxsize), sys.maxsize),
29 (' 1x', ValueError),
30 (' 1 ', 1),
31 (' 1\02 ', ValueError),
32 ('', ValueError),
33 (' ', ValueError),
34 (' \t\t ', ValueError),
35 ("\u0200", ValueError)
36 ]
37
38 class IntSubclass(int):
39 pass
40
41 class IntTestCases(unittest.TestCase):
42
43 def test_basic(self):
44 self.assertEqual(int(314), 314)
45 self.assertEqual(int(3.14), 3)
46 # Check that conversion from float truncates towards zero
47 self.assertEqual(int(-3.14), -3)
48 self.assertEqual(int(3.9), 3)
49 self.assertEqual(int(-3.9), -3)
50 self.assertEqual(int(3.5), 3)
51 self.assertEqual(int(-3.5), -3)
52 self.assertEqual(int("-3"), -3)
53 self.assertEqual(int(" -3 "), -3)
54 self.assertEqual(int("\N{EM SPACE}-3\N{EN SPACE}"), -3)
55 # Different base:
56 self.assertEqual(int("10",16), 16)
57 # Test conversion from strings and various anomalies
58 for s, v in L:
59 for sign in "", "+", "-":
60 for prefix in "", " ", "\t", " \t\t ":
61 ss = prefix + sign + s
62 vv = v
63 if sign == "-" and v is not ValueError:
64 vv = -v
65 try:
66 self.assertEqual(int(ss), vv)
67 except ValueError:
68 pass
69
70 s = repr(-1-sys.maxsize)
71 x = int(s)
72 self.assertEqual(x+1, -sys.maxsize)
73 self.assertIsInstance(x, int)
74 # should return int
75 self.assertEqual(int(s[1:]), sys.maxsize+1)
76
77 # should return int
78 x = int(1e100)
79 self.assertIsInstance(x, int)
80 x = int(-1e100)
81 self.assertIsInstance(x, int)
82
83
84 # SF bug 434186: 0x80000000/2 != 0x80000000>>1.
85 # Worked by accident in Windows release build, but failed in debug build.
86 # Failed in all Linux builds.
87 x = -1-sys.maxsize
88 self.assertEqual(x >> 1, x//2)
89
90 x = int('1' * 600)
91 self.assertIsInstance(x, int)
92
93
94 self.assertRaises(TypeError, int, 1, 12)
95 self.assertRaises(TypeError, int, "10", 2, 1)
96
97 self.assertEqual(int('0o123', 0), 83)
98 self.assertEqual(int('0x123', 16), 291)
99
100 # Bug 1679: "0x" is not a valid hex literal
101 self.assertRaises(ValueError, int, "0x", 16)
102 self.assertRaises(ValueError, int, "0x", 0)
103
104 self.assertRaises(ValueError, int, "0o", 8)
105 self.assertRaises(ValueError, int, "0o", 0)
106
107 self.assertRaises(ValueError, int, "0b", 2)
108 self.assertRaises(ValueError, int, "0b", 0)
109
110 # SF bug 1334662: int(string, base) wrong answers
111 # Various representations of 2**32 evaluated to 0
112 # rather than 2**32 in previous versions
113
114 self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
115 self.assertEqual(int('102002022201221111211', 3), 4294967296)
116 self.assertEqual(int('10000000000000000', 4), 4294967296)
117 self.assertEqual(int('32244002423141', 5), 4294967296)
118 self.assertEqual(int('1550104015504', 6), 4294967296)
119 self.assertEqual(int('211301422354', 7), 4294967296)
120 self.assertEqual(int('40000000000', 8), 4294967296)
121 self.assertEqual(int('12068657454', 9), 4294967296)
122 self.assertEqual(int('4294967296', 10), 4294967296)
123 self.assertEqual(int('1904440554', 11), 4294967296)
124 self.assertEqual(int('9ba461594', 12), 4294967296)
125 self.assertEqual(int('535a79889', 13), 4294967296)
126 self.assertEqual(int('2ca5b7464', 14), 4294967296)
127 self.assertEqual(int('1a20dcd81', 15), 4294967296)
128 self.assertEqual(int('100000000', 16), 4294967296)
129 self.assertEqual(int('a7ffda91', 17), 4294967296)
130 self.assertEqual(int('704he7g4', 18), 4294967296)
131 self.assertEqual(int('4f5aff66', 19), 4294967296)
132 self.assertEqual(int('3723ai4g', 20), 4294967296)
133 self.assertEqual(int('281d55i4', 21), 4294967296)
134 self.assertEqual(int('1fj8b184', 22), 4294967296)
135 self.assertEqual(int('1606k7ic', 23), 4294967296)
136 self.assertEqual(int('mb994ag', 24), 4294967296)
137 self.assertEqual(int('hek2mgl', 25), 4294967296)
138 self.assertEqual(int('dnchbnm', 26), 4294967296)
139 self.assertEqual(int('b28jpdm', 27), 4294967296)
140 self.assertEqual(int('8pfgih4', 28), 4294967296)
141 self.assertEqual(int('76beigg', 29), 4294967296)
142 self.assertEqual(int('5qmcpqg', 30), 4294967296)
143 self.assertEqual(int('4q0jto4', 31), 4294967296)
144 self.assertEqual(int('4000000', 32), 4294967296)
145 self.assertEqual(int('3aokq94', 33), 4294967296)
146 self.assertEqual(int('2qhxjli', 34), 4294967296)
147 self.assertEqual(int('2br45qb', 35), 4294967296)
148 self.assertEqual(int('1z141z4', 36), 4294967296)
149
150 # tests with base 0
151 # this fails on 3.0, but in 2.x the old octal syntax is allowed
152 self.assertEqual(int(' 0o123 ', 0), 83)
153 self.assertEqual(int(' 0o123 ', 0), 83)
154 self.assertEqual(int('000', 0), 0)
155 self.assertEqual(int('0o123', 0), 83)
156 self.assertEqual(int('0x123', 0), 291)
157 self.assertEqual(int('0b100', 0), 4)
158 self.assertEqual(int(' 0O123 ', 0), 83)
159 self.assertEqual(int(' 0X123 ', 0), 291)
160 self.assertEqual(int(' 0B100 ', 0), 4)
161 with self.assertRaises(ValueError):
162 int('010', 0)
163
164 # without base still base 10
165 self.assertEqual(int('0123'), 123)
166 self.assertEqual(int('0123', 10), 123)
167
168 # tests with prefix and base != 0
169 self.assertEqual(int('0x123', 16), 291)
170 self.assertEqual(int('0o123', 8), 83)
171 self.assertEqual(int('0b100', 2), 4)
172 self.assertEqual(int('0X123', 16), 291)
173 self.assertEqual(int('0O123', 8), 83)
174 self.assertEqual(int('0B100', 2), 4)
175
176 # the code has special checks for the first character after the
177 # type prefix
178 self.assertRaises(ValueError, int, '0b2', 2)
179 self.assertRaises(ValueError, int, '0b02', 2)
180 self.assertRaises(ValueError, int, '0B2', 2)
181 self.assertRaises(ValueError, int, '0B02', 2)
182 self.assertRaises(ValueError, int, '0o8', 8)
183 self.assertRaises(ValueError, int, '0o08', 8)
184 self.assertRaises(ValueError, int, '0O8', 8)
185 self.assertRaises(ValueError, int, '0O08', 8)
186 self.assertRaises(ValueError, int, '0xg', 16)
187 self.assertRaises(ValueError, int, '0x0g', 16)
188 self.assertRaises(ValueError, int, '0Xg', 16)
189 self.assertRaises(ValueError, int, '0X0g', 16)
190
191 # SF bug 1334662: int(string, base) wrong answers
192 # Checks for proper evaluation of 2**32 + 1
193 self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
194 self.assertEqual(int('102002022201221111212', 3), 4294967297)
195 self.assertEqual(int('10000000000000001', 4), 4294967297)
196 self.assertEqual(int('32244002423142', 5), 4294967297)
197 self.assertEqual(int('1550104015505', 6), 4294967297)
198 self.assertEqual(int('211301422355', 7), 4294967297)
199 self.assertEqual(int('40000000001', 8), 4294967297)
200 self.assertEqual(int('12068657455', 9), 4294967297)
201 self.assertEqual(int('4294967297', 10), 4294967297)
202 self.assertEqual(int('1904440555', 11), 4294967297)
203 self.assertEqual(int('9ba461595', 12), 4294967297)
204 self.assertEqual(int('535a7988a', 13), 4294967297)
205 self.assertEqual(int('2ca5b7465', 14), 4294967297)
206 self.assertEqual(int('1a20dcd82', 15), 4294967297)
207 self.assertEqual(int('100000001', 16), 4294967297)
208 self.assertEqual(int('a7ffda92', 17), 4294967297)
209 self.assertEqual(int('704he7g5', 18), 4294967297)
210 self.assertEqual(int('4f5aff67', 19), 4294967297)
211 self.assertEqual(int('3723ai4h', 20), 4294967297)
212 self.assertEqual(int('281d55i5', 21), 4294967297)
213 self.assertEqual(int('1fj8b185', 22), 4294967297)
214 self.assertEqual(int('1606k7id', 23), 4294967297)
215 self.assertEqual(int('mb994ah', 24), 4294967297)
216 self.assertEqual(int('hek2mgm', 25), 4294967297)
217 self.assertEqual(int('dnchbnn', 26), 4294967297)
218 self.assertEqual(int('b28jpdn', 27), 4294967297)
219 self.assertEqual(int('8pfgih5', 28), 4294967297)
220 self.assertEqual(int('76beigh', 29), 4294967297)
221 self.assertEqual(int('5qmcpqh', 30), 4294967297)
222 self.assertEqual(int('4q0jto5', 31), 4294967297)
223 self.assertEqual(int('4000001', 32), 4294967297)
224 self.assertEqual(int('3aokq95', 33), 4294967297)
225 self.assertEqual(int('2qhxjlj', 34), 4294967297)
226 self.assertEqual(int('2br45qc', 35), 4294967297)
227 self.assertEqual(int('1z141z5', 36), 4294967297)
228
229 def test_invalid_signs(self):
230 with self.assertRaises(ValueError):
231 int('+')
232 with self.assertRaises(ValueError):
233 int('-')
234 with self.assertRaises(ValueError):
235 int('- 1')
236 with self.assertRaises(ValueError):
237 int('+ 1')
238 with self.assertRaises(ValueError):
239 int(' + 1 ')
240
241 def test_unicode(self):
242 self.assertEqual(int("१२३४५६७८९०1234567890"), 12345678901234567890)
243 self.assertEqual(int('١٢٣٤٥٦٧٨٩٠'), 1234567890)
244 self.assertEqual(int("१२३४५६७८९०1234567890", 0), 12345678901234567890)
245 self.assertEqual(int('١٢٣٤٥٦٧٨٩٠', 0), 1234567890)
246
247 def test_underscores(self):
248 for lit in VALID_UNDERSCORE_LITERALS:
249 if any(ch in lit for ch in '.eEjJ'):
250 continue
251 self.assertEqual(int(lit, 0), eval(lit))
252 self.assertEqual(int(lit, 0), int(lit.replace('_', ''), 0))
253 for lit in INVALID_UNDERSCORE_LITERALS:
254 if any(ch in lit for ch in '.eEjJ'):
255 continue
256 self.assertRaises(ValueError, int, lit, 0)
257 # Additional test cases with bases != 0, only for the constructor:
258 self.assertEqual(int("1_00", 3), 9)
259 self.assertEqual(int("0_100"), 100) # not valid as a literal!
260 self.assertEqual(int(b"1_00"), 100) # byte underscore
261 self.assertRaises(ValueError, int, "_100")
262 self.assertRaises(ValueError, int, "+_100")
263 self.assertRaises(ValueError, int, "1__00")
264 self.assertRaises(ValueError, int, "100_")
265
266 @support.cpython_only
267 def test_small_ints(self):
268 # Bug #3236: Return small longs from PyLong_FromString
269 self.assertIs(int('10'), 10)
270 self.assertIs(int('-1'), -1)
271 self.assertIs(int(b'10'), 10)
272 self.assertIs(int(b'-1'), -1)
273
274 def test_no_args(self):
275 self.assertEqual(int(), 0)
276
277 def test_keyword_args(self):
278 # Test invoking int() using keyword arguments.
279 self.assertEqual(int('100', base=2), 4)
280 with self.assertRaisesRegex(TypeError, 'keyword argument'):
281 int(x=1.2)
282 with self.assertRaisesRegex(TypeError, 'keyword argument'):
283 int(x='100', base=2)
284 self.assertRaises(TypeError, int, base=10)
285 self.assertRaises(TypeError, int, base=0)
286
287 def test_int_base_limits(self):
288 """Testing the supported limits of the int() base parameter."""
289 self.assertEqual(int('0', 5), 0)
290 with self.assertRaises(ValueError):
291 int('0', 1)
292 with self.assertRaises(ValueError):
293 int('0', 37)
294 with self.assertRaises(ValueError):
295 int('0', -909) # An old magic value base from Python 2.
296 with self.assertRaises(ValueError):
297 int('0', base=0-(2**234))
298 with self.assertRaises(ValueError):
299 int('0', base=2**234)
300 # Bases 2 through 36 are supported.
301 for base in range(2,37):
302 self.assertEqual(int('0', base=base), 0)
303
304 def test_int_base_bad_types(self):
305 """Not integer types are not valid bases; issue16772."""
306 with self.assertRaises(TypeError):
307 int('0', 5.5)
308 with self.assertRaises(TypeError):
309 int('0', 5.0)
310
311 def test_int_base_indexable(self):
312 class MyIndexable(object):
313 def __init__(self, value):
314 self.value = value
315 def __index__(self):
316 return self.value
317
318 # Check out of range bases.
319 for base in 2**100, -2**100, 1, 37:
320 with self.assertRaises(ValueError):
321 int('43', base)
322
323 # Check in-range bases.
324 self.assertEqual(int('101', base=MyIndexable(2)), 5)
325 self.assertEqual(int('101', base=MyIndexable(10)), 101)
326 self.assertEqual(int('101', base=MyIndexable(36)), 1 + 36**2)
327
328 def test_non_numeric_input_types(self):
329 # Test possible non-numeric types for the argument x, including
330 # subclasses of the explicitly documented accepted types.
331 class CustomStr(str): pass
332 class CustomBytes(bytes): pass
333 class CustomByteArray(bytearray): pass
334
335 factories = [
336 bytes,
337 bytearray,
338 lambda b: CustomStr(b.decode()),
339 CustomBytes,
340 CustomByteArray,
341 memoryview,
342 ]
343 try:
344 from array import array
345 except ImportError:
346 pass
347 else:
348 factories.append(lambda b: array('B', b))
349
350 for f in factories:
351 x = f(b'100')
352 with self.subTest(type(x)):
353 self.assertEqual(int(x), 100)
354 if isinstance(x, (str, bytes, bytearray)):
355 self.assertEqual(int(x, 2), 4)
356 else:
357 msg = "can't convert non-string"
358 with self.assertRaisesRegex(TypeError, msg):
359 int(x, 2)
360 with self.assertRaisesRegex(ValueError, 'invalid literal'):
361 int(f(b'A' * 0x10))
362
363 def test_int_memoryview(self):
364 self.assertEqual(int(memoryview(b'123')[1:3]), 23)
365 self.assertEqual(int(memoryview(b'123\x00')[1:3]), 23)
366 self.assertEqual(int(memoryview(b'123 ')[1:3]), 23)
367 self.assertEqual(int(memoryview(b'123A')[1:3]), 23)
368 self.assertEqual(int(memoryview(b'1234')[1:3]), 23)
369
370 def test_string_float(self):
371 self.assertRaises(ValueError, int, '1.2')
372
373 def test_intconversion(self):
374 # Test __int__()
375 class ClassicMissingMethods:
376 pass
377 self.assertRaises(TypeError, int, ClassicMissingMethods())
378
379 class MissingMethods(object):
380 pass
381 self.assertRaises(TypeError, int, MissingMethods())
382
383 class Foo0:
384 def __int__(self):
385 return 42
386
387 self.assertEqual(int(Foo0()), 42)
388
389 class Classic:
390 pass
391 for base in (object, Classic):
392 class IntOverridesTrunc(base):
393 def __int__(self):
394 return 42
395 def __trunc__(self):
396 return -12
397 self.assertEqual(int(IntOverridesTrunc()), 42)
398
399 class JustTrunc(base):
400 def __trunc__(self):
401 return 42
402 with self.assertWarns(DeprecationWarning):
403 self.assertEqual(int(JustTrunc()), 42)
404
405 class ExceptionalTrunc(base):
406 def __trunc__(self):
407 1 / 0
408 with self.assertRaises(ZeroDivisionError), \
409 self.assertWarns(DeprecationWarning):
410 int(ExceptionalTrunc())
411
412 for trunc_result_base in (object, Classic):
413 class Index(trunc_result_base):
414 def __index__(self):
415 return 42
416
417 class TruncReturnsNonInt(base):
418 def __trunc__(self):
419 return Index()
420 with self.assertWarns(DeprecationWarning):
421 self.assertEqual(int(TruncReturnsNonInt()), 42)
422
423 class Intable(trunc_result_base):
424 def __int__(self):
425 return 42
426
427 class TruncReturnsNonIndex(base):
428 def __trunc__(self):
429 return Intable()
430 with self.assertWarns(DeprecationWarning):
431 self.assertEqual(int(TruncReturnsNonInt()), 42)
432
433 class NonIntegral(trunc_result_base):
434 def __trunc__(self):
435 # Check that we avoid infinite recursion.
436 return NonIntegral()
437
438 class TruncReturnsNonIntegral(base):
439 def __trunc__(self):
440 return NonIntegral()
441 try:
442 with self.assertWarns(DeprecationWarning):
443 int(TruncReturnsNonIntegral())
444 except TypeError as e:
445 self.assertEqual(str(e),
446 "__trunc__ returned non-Integral"
447 " (type NonIntegral)")
448 else:
449 self.fail("Failed to raise TypeError with %s" %
450 ((base, trunc_result_base),))
451
452 # Regression test for bugs.python.org/issue16060.
453 class BadInt(trunc_result_base):
454 def __int__(self):
455 return 42.0
456
457 class TruncReturnsBadInt(base):
458 def __trunc__(self):
459 return BadInt()
460
461 with self.assertRaises(TypeError), \
462 self.assertWarns(DeprecationWarning):
463 int(TruncReturnsBadInt())
464
465 def test_int_subclass_with_index(self):
466 class MyIndex(int):
467 def __index__(self):
468 return 42
469
470 class BadIndex(int):
471 def __index__(self):
472 return 42.0
473
474 my_int = MyIndex(7)
475 self.assertEqual(my_int, 7)
476 self.assertEqual(int(my_int), 7)
477
478 self.assertEqual(int(BadIndex()), 0)
479
480 def test_int_subclass_with_int(self):
481 class MyInt(int):
482 def __int__(self):
483 return 42
484
485 class BadInt(int):
486 def __int__(self):
487 return 42.0
488
489 my_int = MyInt(7)
490 self.assertEqual(my_int, 7)
491 self.assertEqual(int(my_int), 42)
492
493 my_int = BadInt(7)
494 self.assertEqual(my_int, 7)
495 self.assertRaises(TypeError, int, my_int)
496
497 def test_int_returns_int_subclass(self):
498 class BadIndex:
499 def __index__(self):
500 return True
501
502 class BadIndex2(int):
503 def __index__(self):
504 return True
505
506 class BadInt:
507 def __int__(self):
508 return True
509
510 class BadInt2(int):
511 def __int__(self):
512 return True
513
514 class TruncReturnsBadIndex:
515 def __trunc__(self):
516 return BadIndex()
517
518 class TruncReturnsBadInt:
519 def __trunc__(self):
520 return BadInt()
521
522 class TruncReturnsIntSubclass:
523 def __trunc__(self):
524 return True
525
526 bad_int = BadIndex()
527 with self.assertWarns(DeprecationWarning):
528 n = int(bad_int)
529 self.assertEqual(n, 1)
530 self.assertIs(type(n), int)
531
532 bad_int = BadIndex2()
533 n = int(bad_int)
534 self.assertEqual(n, 0)
535 self.assertIs(type(n), int)
536
537 bad_int = BadInt()
538 with self.assertWarns(DeprecationWarning):
539 n = int(bad_int)
540 self.assertEqual(n, 1)
541 self.assertIs(type(n), int)
542
543 bad_int = BadInt2()
544 with self.assertWarns(DeprecationWarning):
545 n = int(bad_int)
546 self.assertEqual(n, 1)
547 self.assertIs(type(n), int)
548
549 bad_int = TruncReturnsBadIndex()
550 with self.assertWarns(DeprecationWarning):
551 n = int(bad_int)
552 self.assertEqual(n, 1)
553 self.assertIs(type(n), int)
554
555 bad_int = TruncReturnsBadInt()
556 with self.assertWarns(DeprecationWarning):
557 self.assertRaises(TypeError, int, bad_int)
558
559 good_int = TruncReturnsIntSubclass()
560 with self.assertWarns(DeprecationWarning):
561 n = int(good_int)
562 self.assertEqual(n, 1)
563 self.assertIs(type(n), int)
564 with self.assertWarns(DeprecationWarning):
565 n = IntSubclass(good_int)
566 self.assertEqual(n, 1)
567 self.assertIs(type(n), IntSubclass)
568
569 def test_error_message(self):
570 def check(s, base=None):
571 with self.assertRaises(ValueError,
572 msg="int(%r, %r)" % (s, base)) as cm:
573 if base is None:
574 int(s)
575 else:
576 int(s, base)
577 self.assertEqual(cm.exception.args[0],
578 "invalid literal for int() with base %d: %r" %
579 (10 if base is None else base, s))
580
581 check('\xbd')
582 check('123\xbd')
583 check(' 123 456 ')
584
585 check('123\x00')
586 # SF bug 1545497: embedded NULs were not detected with explicit base
587 check('123\x00', 10)
588 check('123\x00 245', 20)
589 check('123\x00 245', 16)
590 check('123\x00245', 20)
591 check('123\x00245', 16)
592 # byte string with embedded NUL
593 check(b'123\x00')
594 check(b'123\x00', 10)
595 # non-UTF-8 byte string
596 check(b'123\xbd')
597 check(b'123\xbd', 10)
598 # lone surrogate in Unicode string
599 check('123\ud800')
600 check('123\ud800', 10)
601
602 def test_issue31619(self):
603 self.assertEqual(int('1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1_0_1', 2),
604 0b1010101010101010101010101010101)
605 self.assertEqual(int('1_2_3_4_5_6_7_0_1_2_3', 8), 0o12345670123)
606 self.assertEqual(int('1_2_3_4_5_6_7_8_9', 16), 0x123456789)
607 self.assertEqual(int('1_2_3_4_5_6_7', 32), 1144132807)
608
609
610 class IntStrDigitLimitsTests(unittest.TestCase):
611
612 int_class = int # Override this in subclasses to reuse the suite.
613
614 def setUp(self):
615 super().setUp()
616 self._previous_limit = sys.get_int_max_str_digits()
617 sys.set_int_max_str_digits(2048)
618
619 def tearDown(self):
620 sys.set_int_max_str_digits(self._previous_limit)
621 super().tearDown()
622
623 def test_disabled_limit(self):
624 self.assertGreater(sys.get_int_max_str_digits(), 0)
625 self.assertLess(sys.get_int_max_str_digits(), 20_000)
626 with support.adjust_int_max_str_digits(0):
627 self.assertEqual(sys.get_int_max_str_digits(), 0)
628 i = self.int_class('1' * 20_000)
629 str(i)
630 self.assertGreater(sys.get_int_max_str_digits(), 0)
631
632 def test_max_str_digits_edge_cases(self):
633 """Ignore the +/- sign and space padding."""
634 int_class = self.int_class
635 maxdigits = sys.get_int_max_str_digits()
636
637 int_class('1' * maxdigits)
638 int_class(' ' + '1' * maxdigits)
639 int_class('1' * maxdigits + ' ')
640 int_class('+' + '1' * maxdigits)
641 int_class('-' + '1' * maxdigits)
642 self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)
643
644 def check(self, i, base=None):
645 with self.assertRaises(ValueError):
646 if base is None:
647 self.int_class(i)
648 else:
649 self.int_class(i, base)
650
651 def test_max_str_digits(self):
652 maxdigits = sys.get_int_max_str_digits()
653
654 self.check('1' * (maxdigits + 1))
655 self.check(' ' + '1' * (maxdigits + 1))
656 self.check('1' * (maxdigits + 1) + ' ')
657 self.check('+' + '1' * (maxdigits + 1))
658 self.check('-' + '1' * (maxdigits + 1))
659 self.check('1' * (maxdigits + 1))
660
661 i = 10 ** maxdigits
662 with self.assertRaises(ValueError):
663 str(i)
664
665 def test_denial_of_service_prevented_int_to_str(self):
666 """Regression test: ensure we fail before performing O(N**2) work."""
667 maxdigits = sys.get_int_max_str_digits()
668 assert maxdigits < 50_000, maxdigits # A test prerequisite.
669
670 huge_int = int(f'0x{"c"*65_000}', base=16) # 78268 decimal digits.
671 digits = 78_268
672 with (
673 support.adjust_int_max_str_digits(digits),
674 support.CPUStopwatch() as sw_convert):
675 huge_decimal = str(huge_int)
676 self.assertEqual(len(huge_decimal), digits)
677 # Ensuring that we chose a slow enough conversion to measure.
678 # It takes 0.1 seconds on a Zen based cloud VM in an opt build.
679 # Some OSes have a low res 1/64s timer, skip if hard to measure.
680 if sw_convert.seconds < sw_convert.clock_info.resolution * 2:
681 raise unittest.SkipTest('"slow" conversion took only '
682 f'{sw_convert.seconds} seconds.')
683
684 # We test with the limit almost at the size needed to check performance.
685 # The performant limit check is slightly fuzzy, give it a some room.
686 with support.adjust_int_max_str_digits(int(.995 * digits)):
687 with (
688 self.assertRaises(ValueError) as err,
689 support.CPUStopwatch() as sw_fail_huge):
690 str(huge_int)
691 self.assertIn('conversion', str(err.exception))
692 self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)
693
694 # Now we test that a conversion that would take 30x as long also fails
695 # in a similarly fast fashion.
696 extra_huge_int = int(f'0x{"c"*500_000}', base=16) # 602060 digits.
697 with (
698 self.assertRaises(ValueError) as err,
699 support.CPUStopwatch() as sw_fail_extra_huge):
700 # If not limited, 8 seconds said Zen based cloud VM.
701 str(extra_huge_int)
702 self.assertIn('conversion', str(err.exception))
703 self.assertLess(sw_fail_extra_huge.seconds, sw_convert.seconds/2)
704
705 def test_denial_of_service_prevented_str_to_int(self):
706 """Regression test: ensure we fail before performing O(N**2) work."""
707 maxdigits = sys.get_int_max_str_digits()
708 assert maxdigits < 100_000, maxdigits # A test prerequisite.
709
710 digits = 133700
711 huge = '8'*digits
712 with (
713 support.adjust_int_max_str_digits(digits),
714 support.CPUStopwatch() as sw_convert):
715 int(huge)
716 # Ensuring that we chose a slow enough conversion to measure.
717 # It takes 0.1 seconds on a Zen based cloud VM in an opt build.
718 # Some OSes have a low res 1/64s timer, skip if hard to measure.
719 if sw_convert.seconds < sw_convert.clock_info.resolution * 2:
720 raise unittest.SkipTest('"slow" conversion took only '
721 f'{sw_convert.seconds} seconds.')
722
723 with support.adjust_int_max_str_digits(digits - 1):
724 with (
725 self.assertRaises(ValueError) as err,
726 support.CPUStopwatch() as sw_fail_huge):
727 int(huge)
728 self.assertIn('conversion', str(err.exception))
729 self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)
730
731 # Now we test that a conversion that would take 30x as long also fails
732 # in a similarly fast fashion.
733 extra_huge = '7'*1_200_000
734 with (
735 self.assertRaises(ValueError) as err,
736 support.CPUStopwatch() as sw_fail_extra_huge):
737 # If not limited, 8 seconds in the Zen based cloud VM.
738 int(extra_huge)
739 self.assertIn('conversion', str(err.exception))
740 self.assertLessEqual(sw_fail_extra_huge.seconds, sw_convert.seconds/2)
741
742 def test_power_of_two_bases_unlimited(self):
743 """The limit does not apply to power of 2 bases."""
744 maxdigits = sys.get_int_max_str_digits()
745
746 for base in (2, 4, 8, 16, 32):
747 with self.subTest(base=base):
748 self.int_class('1' * (maxdigits + 1), base)
749 assert maxdigits < 100_000
750 self.int_class('1' * 100_000, base)
751
752 def test_underscores_ignored(self):
753 maxdigits = sys.get_int_max_str_digits()
754
755 triples = maxdigits // 3
756 s = '111' * triples
757 s_ = '1_11' * triples
758 self.int_class(s) # succeeds
759 self.int_class(s_) # succeeds
760 self.check(f'{s}111')
761 self.check(f'{s_}_111')
762
763 def test_sign_not_counted(self):
764 int_class = self.int_class
765 max_digits = sys.get_int_max_str_digits()
766 s = '5' * max_digits
767 i = int_class(s)
768 pos_i = int_class(f'+{s}')
769 assert i == pos_i
770 neg_i = int_class(f'-{s}')
771 assert -pos_i == neg_i
772 str(pos_i)
773 str(neg_i)
774
775 def _other_base_helper(self, base):
776 int_class = self.int_class
777 max_digits = sys.get_int_max_str_digits()
778 s = '2' * max_digits
779 i = int_class(s, base)
780 if base > 10:
781 with self.assertRaises(ValueError):
782 str(i)
783 elif base < 10:
784 str(i)
785 with self.assertRaises(ValueError) as err:
786 int_class(f'{s}1', base)
787
788 def test_int_from_other_bases(self):
789 base = 3
790 with self.subTest(base=base):
791 self._other_base_helper(base)
792 base = 36
793 with self.subTest(base=base):
794 self._other_base_helper(base)
795
796 def test_int_max_str_digits_is_per_interpreter(self):
797 # Changing the limit in one interpreter does not change others.
798 code = """if 1:
799 # Subinterpreters maintain and enforce their own limit
800 import sys
801 sys.set_int_max_str_digits(2323)
802 try:
803 int('3'*3333)
804 except ValueError:
805 pass
806 else:
807 raise AssertionError('Expected a int max str digits ValueError.')
808 """
809 with support.adjust_int_max_str_digits(4000):
810 before_value = sys.get_int_max_str_digits()
811 self.assertEqual(support.run_in_subinterp(code), 0,
812 'subinterp code failure, check stderr.')
813 after_value = sys.get_int_max_str_digits()
814 self.assertEqual(before_value, after_value)
815
816
817 class IntSubclassStrDigitLimitsTests(IntStrDigitLimitsTests):
818 int_class = IntSubclass
819
820
821 class PyLongModuleTests(unittest.TestCase):
822 # Tests of the functions in _pylong.py. Those get used when the
823 # number of digits in the input values are large enough.
824
825 def setUp(self):
826 super().setUp()
827 self._previous_limit = sys.get_int_max_str_digits()
828 sys.set_int_max_str_digits(0)
829
830 def tearDown(self):
831 sys.set_int_max_str_digits(self._previous_limit)
832 super().tearDown()
833
834 def _test_pylong_int_to_decimal(self, n, suffix):
835 s = str(n)
836 self.assertEqual(s[-10:], suffix)
837 s2 = str(-n)
838 self.assertEqual(s2, '-' + s)
839 s3 = '%d' % n
840 self.assertEqual(s3, s)
841 s4 = b'%d' % n
842 self.assertEqual(s4, s.encode('ascii'))
843
844 def test_pylong_int_to_decimal(self):
845 self._test_pylong_int_to_decimal((1 << 100_000), '9883109376')
846 self._test_pylong_int_to_decimal((1 << 100_000) - 1, '9883109375')
847 self._test_pylong_int_to_decimal(10**30_000, '0000000000')
848 self._test_pylong_int_to_decimal(10**30_000 - 1, '9999999999')
849 self._test_pylong_int_to_decimal(3**60_000, '9313200001')
850
851 @support.requires_resource('cpu')
852 def test_pylong_int_to_decimal_2(self):
853 self._test_pylong_int_to_decimal(2**1_000_000, '2747109376')
854 self._test_pylong_int_to_decimal(10**300_000, '0000000000')
855 self._test_pylong_int_to_decimal(3**600_000, '3132000001')
856
857 def test_pylong_int_divmod(self):
858 n = (1 << 100_000)
859 a, b = divmod(n*3 + 1, n)
860 assert a == 3 and b == 1
861
862 @support.cpython_only # tests implementation details of CPython.
863 @unittest.skipUnless(_pylong, "_pylong module required")
864 def test_pylong_int_divmod_crash(self):
865 # Regression test for https://github.com/python/cpython/issues/142554.
866 bad_int_divmod = lambda a, b: (1,)
867 # 'k' chosen such that divmod(2**(2*k), 2**k) uses _pylong.int_divmod()
868 k = 10_000
869 a, b = (1 << (2 * k)), (1 << k)
870 with mock.patch.object(_pylong, "int_divmod", wraps=bad_int_divmod):
871 msg = r"tuple of length 2 is required from int_divmod\(\)"
872 self.assertRaisesRegex(ValueError, msg, divmod, a, b)
873
874 def test_pylong_str_to_int(self):
875 v1 = 1 << 100_000
876 s = str(v1)
877 v2 = int(s)
878 assert v1 == v2
879 v3 = int(' -' + s)
880 assert -v1 == v3
881 v4 = int(' +' + s + ' ')
882 assert v1 == v4
883 with self.assertRaises(ValueError) as err:
884 int(s + 'z')
885 with self.assertRaises(ValueError) as err:
886 int(s + '_')
887 with self.assertRaises(ValueError) as err:
888 int('_' + s)
889
890 @support.cpython_only # tests implementation details of CPython.
891 @unittest.skipUnless(_pylong, "_pylong module required")
892 @mock.patch.object(_pylong, "int_to_decimal_string")
893 def test_pylong_misbehavior_error_path_to_str(
894 self, mock_int_to_str):
895 with support.adjust_int_max_str_digits(20_000):
896 big_value = int('7'*19_999)
897 mock_int_to_str.return_value = None # not a str
898 with self.assertRaises(TypeError) as ctx:
899 str(big_value)
900 self.assertIn('_pylong.int_to_decimal_string did not',
901 str(ctx.exception))
902 mock_int_to_str.side_effect = RuntimeError("testABC")
903 with self.assertRaises(RuntimeError):
904 str(big_value)
905
906 @support.cpython_only # tests implementation details of CPython.
907 @unittest.skipUnless(_pylong, "_pylong module required")
908 @mock.patch.object(_pylong, "int_from_string")
909 def test_pylong_misbehavior_error_path_from_str(
910 self, mock_int_from_str):
911 big_value = '7'*19_999
912 with support.adjust_int_max_str_digits(20_000):
913 mock_int_from_str.return_value = b'not an int'
914 with self.assertRaises(TypeError) as ctx:
915 int(big_value)
916 self.assertIn('_pylong.int_from_string did not',
917 str(ctx.exception))
918
919 mock_int_from_str.side_effect = RuntimeError("test123")
920 with self.assertRaises(RuntimeError):
921 int(big_value)
922
923 def test_pylong_roundtrip(self):
924 from random import randrange, getrandbits
925 bits = 5000
926 while bits <= 1_000_000:
927 bits += randrange(-100, 101) # break bitlength patterns
928 hibit = 1 << (bits - 1)
929 n = hibit | getrandbits(bits - 1)
930 assert n.bit_length() == bits
931 sn = str(n)
932 self.assertFalse(sn.startswith('0'))
933 self.assertEqual(n, int(sn))
934 bits <<= 1
935
936 if __name__ == "__main__":
937 unittest.main()