Debian Codegraph @

pypy/objspace/std/test/test_intobject.py

raw symbols SCIP
1 # encoding: utf-8
2 import sys
3 from pypy.interpreter.error import OperationError
4 from pypy.objspace.std import intobject as iobj
5 from rpython.rlib.rarithmetic import r_uint, is_valid_int, intmask
6 from rpython.rlib.rbigint import rbigint
7
8 from rpython.jit.metainterp.test.support import LLJitMixin, noConst
9
10 from hypothesis import given, strategies
11
12 class TestW_IntObject:
13
14 def _longshiftresult(self, x):
15 """ calculate an overflowing shift """
16 n = 1
17 l = long(x)
18 while 1:
19 ires = x << n
20 lres = l << n
21 if not is_valid_int(ires) or lres != ires:
22 return n
23 n += 1
24
25 def test_int_w(self):
26 assert self.space.int_w(self.space.wrap(42)) == 42
27
28 def test_uint_w(self):
29 space = self.space
30 assert space.uint_w(space.wrap(42)) == 42
31 assert isinstance(space.uint_w(space.wrap(42)), r_uint)
32 space.raises_w(space.w_ValueError, space.uint_w, space.wrap(-1))
33
34 def test_bigint_w(self):
35 space = self.space
36 assert isinstance(space.bigint_w(space.wrap(42)), rbigint)
37 assert space.bigint_w(space.wrap(42)).eq(rbigint.fromint(42))
38
39 def test_repr(self):
40 x = 1
41 f1 = iobj.W_IntObject(x)
42 result = f1.descr_repr(self.space)
43 assert self.space.unwrap(result) == repr(x)
44
45 def test_str(self):
46 x = 12345
47 f1 = iobj.W_IntObject(x)
48 result = f1.descr_str(self.space)
49 assert self.space.unwrap(result) == str(x)
50
51 def test_hash(self):
52 x = 42
53 f1 = iobj.W_IntObject(x)
54 result = f1.descr_hash(self.space)
55 assert result.intval == hash(x)
56
57 def test_compare(self):
58 import operator
59 optab = ['lt', 'le', 'eq', 'ne', 'gt', 'ge']
60 for x in (-10, -1, 0, 1, 2, 1000, sys.maxint):
61 for y in (-sys.maxint-1, -11, -9, -2, 0, 1, 3, 1111, sys.maxint):
62 for op in optab:
63 wx = iobj.W_IntObject(x)
64 wy = iobj.W_IntObject(y)
65 res = getattr(operator, op)(x, y)
66 method = getattr(wx, 'descr_%s' % op)
67 myres = method(self.space, wy)
68 assert self.space.unwrap(myres) == res
69
70 def test_add(self):
71 space = self.space
72 x = 1
73 y = 2
74 f1 = iobj.W_IntObject(x)
75 f2 = iobj.W_IntObject(y)
76 result = f1.descr_add(space, f2)
77 assert result.intval == x+y
78 x = sys.maxint
79 y = 1
80 f1 = iobj.W_IntObject(x)
81 f2 = iobj.W_IntObject(y)
82 v = f1.descr_add(space, f2)
83 assert space.isinstance_w(v, space.w_int)
84 assert space.bigint_w(v).eq(rbigint.fromlong(x + y))
85
86 def test_add_ovf_int_op_shortcut(self, monkeypatch):
87 from pypy.objspace.std.longobject import W_LongObject, rbigint
88 monkeypatch.setattr(W_LongObject, 'fromint', None)
89
90 space = self.space
91 x = sys.maxint
92 y = 1
93 f1 = iobj.W_IntObject(x)
94 f2 = iobj.W_IntObject(y)
95 v = f1.descr_add(space, f2)
96 assert space.isinstance_w(v, space.w_long)
97 assert space.bigint_w(v).eq(rbigint.fromlong(x + y))
98
99 def test_lt_int_long_no_conversion(self, monkeypatch):
100 from pypy.objspace.std.longobject import W_LongObject, rbigint
101
102 space = self.space
103 x = sys.maxint
104 y = 1
105 f1 = iobj.W_IntObject(x)
106 f2 = iobj.W_IntObject(y).as_w_long(space)
107
108 monkeypatch.setattr(iobj.W_IntObject, 'as_w_long', None)
109 v = f1.descr_gt(space, f2) # does *not* convert f1 to a bigint
110 assert space.is_true(v)
111
112 def test_mul_int_long_no_conversion(self, monkeypatch):
113 from pypy.objspace.std.longobject import W_LongObject, rbigint
114
115 space = self.space
116 x = sys.maxint
117 y = 1
118 f1 = iobj.W_IntObject(x)
119 f2 = iobj.W_IntObject(y).as_w_long(space)
120
121 monkeypatch.setattr(iobj.W_IntObject, 'as_w_long', None)
122 v = f1.descr_mul(space, f2) # does *not* convert f1 to a bigint
123
124 def test_sub(self):
125 space = self.space
126 x = 1
127 y = 2
128 f1 = iobj.W_IntObject(x)
129 f2 = iobj.W_IntObject(y)
130 result = f1.descr_sub(space, f2)
131 assert result.intval == x-y
132 x = sys.maxint
133 y = -1
134 f1 = iobj.W_IntObject(x)
135 f2 = iobj.W_IntObject(y)
136 v = f1.descr_sub(space, f2)
137 assert space.isinstance_w(v, space.w_int)
138 assert space.bigint_w(v).eq(rbigint.fromlong(sys.maxint - -1))
139
140 def test_sub_ovf_int_op_shortcut(self, monkeypatch):
141 from pypy.objspace.std.longobject import W_LongObject, rbigint
142 monkeypatch.setattr(W_LongObject, 'fromint', None)
143
144 space = self.space
145 x = sys.maxint
146 y = -1
147 f1 = iobj.W_IntObject(x)
148 f2 = iobj.W_IntObject(y)
149 v = f1.descr_sub(space, f2)
150 assert space.isinstance_w(v, space.w_long)
151 assert space.bigint_w(v).eq(rbigint.fromlong(x - y))
152
153 def test_mul(self):
154 space = self.space
155 x = 2
156 y = 3
157 f1 = iobj.W_IntObject(x)
158 f2 = iobj.W_IntObject(y)
159 result = f1.descr_mul(space, f2)
160 assert result.intval == x*y
161 x = -sys.maxint-1
162 y = -1
163 f1 = iobj.W_IntObject(x)
164 f2 = iobj.W_IntObject(y)
165 v = f1.descr_mul(space, f2)
166 assert space.isinstance_w(v, space.w_int)
167 assert space.bigint_w(v).eq(rbigint.fromlong(x * y))
168 x = sys.maxint // 4
169 y = sys.maxint // 8
170 f1 = iobj.W_IntObject(x)
171 f2 = iobj.W_IntObject(y)
172 v = f1.descr_mul(space, f2)
173 assert space.isinstance_w(v, space.w_long)
174 assert space.bigint_w(v).eq(rbigint.fromlong(x * y))
175
176 def test_mod(self):
177 x = 1
178 y = 2
179 f1 = iobj.W_IntObject(x)
180 f2 = iobj.W_IntObject(y)
181 v = f1.descr_mod(self.space, f2)
182 assert v.intval == x % y
183 # not that mod cannot overflow
184
185 def test_divmod(self):
186 space = self.space
187 x = 1
188 y = 2
189 f1 = iobj.W_IntObject(x)
190 f2 = iobj.W_IntObject(y)
191 ret = f1.descr_divmod(space, f2)
192 v, w = space.unwrap(ret)
193 assert (v, w) == divmod(x, y)
194 x = -sys.maxint-1
195 y = -1
196 f1 = iobj.W_IntObject(x)
197 f2 = iobj.W_IntObject(y)
198 v = f1.descr_divmod(space, f2)
199 w_q, w_r = space.fixedview(v, 2)
200 assert space.isinstance_w(w_q, space.w_int)
201 expected = divmod(x, y)
202 assert space.bigint_w(w_q).eq(rbigint.fromlong(expected[0]))
203 # no overflow possible
204 assert space.unwrap(w_r) == expected[1]
205
206 def test_pow_iii(self):
207 x = 10
208 y = 2
209 z = 13
210 f1 = iobj.W_IntObject(x)
211 f2 = iobj.W_IntObject(y)
212 f3 = iobj.W_IntObject(z)
213 v = f1.descr_pow(self.space, f2, f3)
214 assert v.intval == pow(x, y, z)
215 f1, f2, f3 = [iobj.W_IntObject(i) for i in (10, -1, 42)]
216 self.space.raises_w(self.space.w_ValueError,
217 f1.descr_pow, self.space, f2, f3)
218 f1, f2, f3 = [iobj.W_IntObject(i) for i in (10, 5, 0)]
219 self.space.raises_w(self.space.w_ValueError,
220 f1.descr_pow, self.space, f2, f3)
221
222 def test_pow_iin(self):
223 space = self.space
224 x = 10
225 y = 2
226 f1 = iobj.W_IntObject(x)
227 f2 = iobj.W_IntObject(y)
228 v = f1.descr_pow(space, f2, space.w_None)
229 assert v.intval == x ** y
230 f1, f2 = [iobj.W_IntObject(i) for i in (10, 20)]
231 v = f1.descr_pow(space, f2, space.w_None)
232 assert space.isinstance_w(v, space.w_int)
233 assert space.bigint_w(v).eq(rbigint.fromlong(pow(10, 20)))
234
235 def test_pow_ovf_without_fromint(self, monkeypatch):
236 space = self.space
237 orig = rbigint.fromint
238 def fromint(x):
239 assert x == sys.maxint // 4 # it's not called for 16
240 return orig(x)
241 monkeypatch.setattr(rbigint, 'fromint', staticmethod(fromint))
242 x = sys.maxint // 4
243 y = 16
244 f1 = iobj.W_IntObject(x)
245 f2 = iobj.W_IntObject(y)
246 v = f1.descr_pow(space, f2)
247 assert space.bigint_w(v).eq(rbigint.fromlong(x ** y))
248
249
250 try:
251 from hypothesis import given, strategies, example
252 except ImportError:
253 pass
254 else:
255 @given(
256 a=strategies.integers(min_value=-sys.maxint-1, max_value=sys.maxint),
257 b=strategies.integers(min_value=0, max_value=sys.maxint),
258 c=strategies.integers(min_value=-sys.maxint-1, max_value=sys.maxint))
259 @example(0, 0, -sys.maxint-1)
260 @example(0, 1, -sys.maxint-1)
261 @example(1, 0, -sys.maxint-1)
262 def test_hypot_pow(self, a, b, c):
263 if c == 0:
264 return
265 #
266 # "pow(a, b, c)": if b < 0, should get an app-level ValueError.
267 # Otherwise, should always work except if c == -maxint-1
268 if b < 0:
269 expected = "app-level ValueError"
270 elif b > 0 and c == -sys.maxint-1:
271 expected = OverflowError
272 else:
273 expected = pow(a, b, c)
274
275 try:
276 result = iobj._pow(self.space, a, b, c)
277 except OperationError as e:
278 assert ('ValueError: pow() 2nd argument cannot be negative '
279 'when 3rd argument specified' == e.errorstr(self.space))
280 result = "app-level ValueError"
281 except OverflowError:
282 result = OverflowError
283 assert result == expected
284
285 # check exponent -1
286 if isinstance(expected, int):
287 try:
288 result = iobj._pow(self.space, a, -1, c)
289 except OperationError as e:
290 pass
291 except OverflowError:
292 pass
293 else:
294 assert (a * result % c) == 1 % c
295
296
297 @given(
298 a=strategies.integers(min_value=-sys.maxint-1, max_value=sys.maxint),
299 b=strategies.integers(min_value=-sys.maxint-1, max_value=sys.maxint))
300 def test_hypot_pow_nomod(self, a, b):
301 # "a ** b": detect overflows and ValueErrors
302 if b < 0:
303 expected = ValueError
304 elif b > 128 and not (-1 <= a <= 1):
305 expected = OverflowError
306 else:
307 expected = a ** b
308 if expected != intmask(expected):
309 expected = OverflowError
310
311 try:
312 result = iobj._pow(self.space, a, b, 0)
313 except ValueError:
314 result = ValueError
315 except OverflowError:
316 result = OverflowError
317 assert result == expected
318
319 def test_neg(self):
320 space = self.space
321 x = 42
322 f1 = iobj.W_IntObject(x)
323 v = f1.descr_neg(space)
324 assert v.intval == -x
325 x = -sys.maxint-1
326 f1 = iobj.W_IntObject(x)
327 v = f1.descr_neg(space)
328 assert space.isinstance_w(v, space.w_int)
329 assert space.bigint_w(v).eq(rbigint.fromlong(-x))
330
331 def test_pos(self):
332 x = 42
333 f1 = iobj.W_IntObject(x)
334 v = f1.descr_pos(self.space)
335 assert v.intval == +x
336 x = -42
337 f1 = iobj.W_IntObject(x)
338 v = f1.descr_pos(self.space)
339 assert v.intval == +x
340
341 def test_abs(self):
342 space = self.space
343 x = 42
344 f1 = iobj.W_IntObject(x)
345 v = f1.descr_abs(space)
346 assert v.intval == abs(x)
347 x = -42
348 f1 = iobj.W_IntObject(x)
349 v = f1.descr_abs(space)
350 assert v.intval == abs(x)
351 x = -sys.maxint-1
352 f1 = iobj.W_IntObject(x)
353 v = f1.descr_abs(space)
354 assert space.isinstance_w(v, space.w_int)
355 assert space.bigint_w(v).eq(rbigint.fromlong(abs(x)))
356
357 def test_invert(self):
358 x = 42
359 f1 = iobj.W_IntObject(x)
360 v = f1.descr_invert(self.space)
361 assert v.intval == ~x
362
363 def test_lshift(self):
364 space = self.space
365 x = 12345678
366 y = 2
367 f1 = iobj.W_IntObject(x)
368 f2 = iobj.W_IntObject(y)
369 v = f1.descr_lshift(space, f2)
370 assert v.intval == x << y
371 y = self._longshiftresult(x)
372 f1 = iobj.W_IntObject(x)
373 f2 = iobj.W_IntObject(y)
374 v = f1.descr_lshift(space, f2)
375 assert space.isinstance_w(v, space.w_int)
376 assert space.bigint_w(v).eq(rbigint.fromlong(x << y))
377
378 def test_lshift_without_fromint(self, monkeypatch):
379 space = self.space
380 monkeypatch.setattr(rbigint, 'fromint', None)
381 x = sys.maxint // 4
382 y = 16
383 f1 = iobj.W_IntObject(x)
384 f2 = iobj.W_IntObject(y)
385 v = f1.descr_lshift(space, f2)
386 assert space.bigint_w(v).eq(rbigint.fromlong(x << y))
387
388 def test_rshift(self):
389 x = 12345678
390 y = 2
391 f1 = iobj.W_IntObject(x)
392 f2 = iobj.W_IntObject(y)
393 v = f1.descr_rshift(self.space, f2)
394 assert v.intval == x >> y
395
396 def test_and(self):
397 x = 12345678
398 y = 2
399 f1 = iobj.W_IntObject(x)
400 f2 = iobj.W_IntObject(y)
401 v = f1.descr_and(self.space, f2)
402 assert v.intval == x & y
403
404 def test_xor(self):
405 x = 12345678
406 y = 2
407 f1 = iobj.W_IntObject(x)
408 f2 = iobj.W_IntObject(y)
409 v = f1.descr_xor(self.space, f2)
410 assert v.intval == x ^ y
411
412 def test_or(self):
413 x = 12345678
414 y = 2
415 f1 = iobj.W_IntObject(x)
416 f2 = iobj.W_IntObject(y)
417 v = f1.descr_or(self.space, f2)
418 assert v.intval == x | y
419
420 def test_int(self):
421 f1 = iobj.W_IntObject(1)
422 result = f1.int(self.space)
423 assert result == f1
424
425 class AppTestInt(object):
426 def test_hash(self):
427 assert hash(-1) == (-1).__hash__() == -2
428 assert hash(-2) == (-2).__hash__() == -2
429
430 def test_conjugate(self):
431 assert (1).conjugate() == 1
432 assert (-1).conjugate() == -1
433
434 class I(int):
435 pass
436 assert I(1).conjugate() == 1
437
438 class I(int):
439 def __pos__(self):
440 return 42
441 assert I(1).conjugate() == 1
442
443 def test_inplace(self):
444 a = 1
445 a += 1
446 assert a == 2
447 a -= 1
448 assert a == 1
449 e = raises(TypeError, "a += 'aa'")
450 assert "+=" in str(e.value)
451
452
453 def test_trunc(self):
454 import math
455 assert math.trunc(1) == 1
456 assert math.trunc(-1) == -1
457
458 def test_int_callable(self):
459 assert 43 == int(43)
460
461 def test_numerator_denominator(self):
462 assert (1).numerator == 1
463 assert (1).denominator == 1
464 assert (42).numerator == 42
465 assert (42).denominator == 1
466
467 def test_int_string(self):
468 assert 42 == int("42")
469 assert 10000000000 == int("10000000000")
470
471 def test_int_no_whitespace_after_sign(self):
472 raises(ValueError, int, '+ 42')
473 raises(ValueError, int, '- 42')
474
475 def test_int_string_limit(self):
476 import sys
477 max_str_digits = sys.get_int_max_str_digits()
478 raises(ValueError, int, '1' * (max_str_digits + 1))
479 # should not fail
480 x = int(' ' + '1' * max_str_digits)
481 sys.set_int_max_str_digits(0)
482 try:
483 x = int('1' * (max_str_digits + 1))
484 finally:
485 sys.set_int_max_str_digits(max_str_digits)
486
487 def test_int_float(self):
488 assert 4 == int(4.2)
489
490 def test_int_str_repr(self):
491 assert "42" == str(42)
492 assert "42" == repr(42)
493 raises(ValueError, int, '0x2A')
494
495 def test_int_two_param(self):
496 assert 42 == int('0x2A', 0)
497 assert 42 == int('2A', 16)
498 assert 42 == int('42', 10)
499 raises(TypeError, int, 1, 10)
500 raises(TypeError, int, '5', '9')
501
502 def test_int_largenums(self):
503 import sys
504 for x in [-sys.maxsize-1, -1, sys.maxsize]:
505 y = int(str(x))
506 assert y == x
507 assert type(y) is int
508
509 def test_shift_zeros(self):
510 assert (1 << 0) == 1
511 assert (1 >> 0) == 1
512
513 def test_overflow(self):
514 import sys
515 n = sys.maxsize + 1
516 assert isinstance(n, int)
517
518 def test_pow(self):
519 assert pow(2, -10) == 1/1024.
520
521 def test_int_w_long_arg(self):
522 assert int(10000000000) == 10000000000
523 assert int("10000000000") == 10000000000
524 raises(ValueError, int, "10000000000JUNK")
525 raises(ValueError, int, "10000000000JUNK", 10)
526
527 def test_int_subclass_ctr(self):
528 import sys
529 class j(int):
530 pass
531 assert j(100) == 100
532 assert isinstance(j(100),j)
533 assert j(100) == 100
534 assert j("100") == 100
535 assert j("100",2) == 4
536 assert isinstance(j("100",2),j)
537
538 def test_int_subclass_ops(self):
539 import sys
540 class j(int):
541 def __add__(self, other):
542 return "add."
543 def __iadd__(self, other):
544 return "iadd."
545 def __sub__(self, other):
546 return "sub."
547 def __isub__(self, other):
548 return "isub."
549 def __mul__(self, other):
550 return "mul."
551 def __imul__(self, other):
552 return "imul."
553 def __lshift__(self, other):
554 return "lshift."
555 def __ilshift__(self, other):
556 return "ilshift."
557 assert j(100) + 5 == "add."
558 assert j(100) + str == "add."
559 assert j(100) - 5 == "sub."
560 assert j(100) - str == "sub."
561 assert j(100) * 5 == "mul."
562 assert j(100) * str == "mul."
563 assert j(100) << 5 == "lshift."
564 assert j(100) << str == "lshift."
565 assert (5 + j(100), type(5 + j(100))) == ( 105, int)
566 assert (5 - j(100), type(5 - j(100))) == ( -95, int)
567 assert (5 * j(100), type(5 * j(100))) == ( 500, int)
568 assert (5 << j(100), type(5 << j(100))) == (5 << 100, int)
569 assert (j(100) >> 2, type(j(100) >> 2)) == ( 25, int)
570
571 def test_int_subclass_int(self):
572 class j(int):
573 def __int__(self):
574 return value
575 def __repr__(self):
576 return '<instance of j>'
577 class subint(int):
578 pass
579 value = 42
580 assert int(j()) == 42
581 value = 4200000000000000000000000000000000
582 assert int(j()) == 4200000000000000000000000000000000
583 value = subint(42)
584 assert int(j()) == 42 and type(int(j())) is int
585 value = subint(4200000000000000000000000000000000)
586 assert (int(j()) == 4200000000000000000000000000000000
587 and type(int(j())) is int)
588 value = 42.0
589 raises(TypeError, int, j())
590 value = "foo"
591 raises(TypeError, int, j())
592
593 def test_special_int(self):
594 class a(object):
595 def __int__(self):
596 self.ar = True
597 return None
598 inst = a()
599 raises(TypeError, int, inst)
600 assert inst.ar == True
601
602 class b(object):
603 pass
604 raises((AttributeError,TypeError), int, b())
605
606 def test_special_long(self):
607 class a(object):
608 def __int__(self):
609 self.ar = True
610 return None
611 inst = a()
612 raises(TypeError, int, inst)
613 assert inst.ar == True
614
615 class b(object):
616 pass
617 raises((AttributeError,TypeError), int, b())
618
619 def test_just_trunc(self):
620 import warnings
621 class myint(object):
622 def __trunc__(self):
623 return 42
624 with warnings.catch_warnings(record=True) as log:
625 warnings.simplefilter("always", DeprecationWarning)
626 assert int(myint()) == 42
627 assert log[0].category == DeprecationWarning
628
629 def test_override___int__(self):
630 class myint(int):
631 def __int__(self):
632 return 42
633 assert int(myint(21)) == 42
634 class myotherint(int):
635 pass
636 assert int(myotherint(21)) == 21
637
638 def test_trunc_returns_non_int(self):
639 import warnings
640 class Integral(object):
641 def __int__(self):
642 return 42
643 class TruncReturnsNonInt(object):
644 def __trunc__(self):
645 return Integral()
646 with warnings.catch_warnings(record=True) as log:
647 warnings.simplefilter("always", DeprecationWarning)
648 with raises(TypeError):
649 int(TruncReturnsNonInt())
650 assert log[0].category == DeprecationWarning
651
652 def test_trunc_returns_int_subclass(self):
653 import warnings
654 class TruncReturnsNonInt:
655 def __trunc__(self):
656 return True
657 with warnings.catch_warnings(record=True) as log:
658 warnings.simplefilter("always", DeprecationWarning)
659 n = int(TruncReturnsNonInt())
660 assert log[0].category == DeprecationWarning
661 assert n == 1
662 assert type(n) is int
663
664 def test_trunc_returns_int_subclass_2(self):
665 import warnings
666 class BadInt:
667 def __int__(self):
668 return True
669 class TruncReturnsBadInt:
670 def __trunc__(self):
671 return BadInt()
672 bad_int = TruncReturnsBadInt()
673 with warnings.catch_warnings(record=True) as log:
674 warnings.simplefilter("always", DeprecationWarning)
675 with raises(TypeError):
676 int(bad_int)
677 assert log[0].category == DeprecationWarning
678
679 def test_trunc_returns_index(self):
680 import warnings
681 class Index:
682 def __index__(self):
683 return 17
684 class TruncReturnsIndex:
685 def __trunc__(self):
686 return Index()
687 with warnings.catch_warnings(record=True) as log:
688 warnings.simplefilter("always", DeprecationWarning)
689 assert int(TruncReturnsIndex()) == 17
690 assert log[0].category == DeprecationWarning
691
692 def test_int_before_string(self):
693 class Integral(str):
694 def __int__(self):
695 return 42
696 assert int(Integral('abc')) == 42
697
698 def test_getnewargs(self):
699 assert 0 .__getnewargs__() == (0,)
700
701 def test_bit_length(self):
702 for val, bits in [
703 (0, 0),
704 (1, 1),
705 (10, 4),
706 (150, 8),
707 (-1, 1),
708 (-2, 2),
709 (-3, 2),
710 (-4, 3),
711 (-10, 4),
712 (-150, 8),
713 ]:
714 assert val.bit_length() == bits
715
716 def test_bit_length_max(self):
717 import sys
718 val = -sys.maxsize-1
719 bits = 32 if val == -2147483648 else 64
720 assert val.bit_length() == bits
721
722 def test_int_real(self):
723 class A(int): pass
724 b = A(5).real
725 assert type(b) is int
726
727 def test_int_error_msg(self):
728 e = raises(TypeError, int, [])
729 assert str(e.value) == ("int() argument must be a string, a bytes-"
730 "like object or a number, not 'list'")
731
732 def test_invalid_literal_message(self):
733 import sys
734 if '__pypy__' not in sys.builtin_module_names:
735 skip('PyPy 2.x/CPython 3.4 only')
736 for value in b' 1j ', ' 1٢٣٤j ':
737 try:
738 int(value)
739 except ValueError as e:
740 assert repr(value) in str(e)
741 else:
742 assert False, value
743
744 def test_int_error_msg_surrogate(self):
745 value = u'123\ud800'
746 e = raises(ValueError, int, value)
747 assert str(e.value) == u"invalid literal for int() with base 10: %r" % value
748 e = raises(ValueError, int, value, 10)
749 assert str(e.value) == u"invalid literal for int() with base 10: %r" % value
750
751 def test_non_numeric_input_types(self):
752 # Test possible non-numeric types for the argument x, including
753 # subclasses of the explicitly documented accepted types.
754 class CustomStr(str): pass
755 class CustomBytes(bytes): pass
756 class CustomByteArray(bytearray): pass
757
758 factories = [
759 bytes,
760 bytearray,
761 lambda b: CustomStr(b.decode()),
762 CustomBytes,
763 CustomByteArray,
764 memoryview,
765 ]
766 try:
767 from array import array
768 except ImportError:
769 pass
770 else:
771 factories.append(lambda b: array('B', b))
772
773 for f in factories:
774 x = f(b'100')
775 assert int(x) == 100
776 if isinstance(x, (str, bytes, bytearray)):
777 assert int(x, 2) == 4
778 else:
779 try:
780 int(x, 2)
781 except TypeError as e:
782 assert "can't convert non-string" in str(e)
783 else:
784 assert False, 'did not raise'
785 try:
786 int(f(b'A' * 0x10))
787 except ValueError as e:
788 assert "invalid literal" in str(e)
789 else:
790 assert False, 'did not raise'
791
792 def test_fake_int_as_base(self):
793 class MyInt(object):
794 def __init__(self, x):
795 self.x = x
796 def __index__(self):
797 return self.x
798
799 base = MyInt(24)
800 assert int('10', base) == 24
801
802 class MyNonIndexable(object):
803 def __init__(self, x):
804 self.x = x
805 def __int__(self):
806 return self.x
807
808 base = MyNonIndexable(24)
809 e = raises(TypeError, int, '10', base)
810 assert str(e.value) == ("'MyNonIndexable' object cannot be interpreted "
811 "as an integer")
812
813 def test_truediv(self):
814 import operator
815 x = 1000000
816 a = x / 2
817 assert a == 500000
818 a = operator.truediv(x, 2)
819 assert a == 500000.0
820
821 x = 63050394783186940
822 a = x / 7
823 assert a == 9007199254740991
824 a = operator.truediv(x, 7)
825 assert a == 9007199254740991.0
826
827 def test_truediv_future(self):
828 ns = dict(x=63050394783186940)
829 exec("from __future__ import division; import operator; "
830 "a = x / 7; b = operator.truediv(x, 7)", ns)
831 assert ns['a'] == 9007199254740991.0
832 assert ns['b'] == 9007199254740991.0
833
834 def test_int_of_bool(self):
835 x = int(False)
836 assert x == 0
837 assert type(x) is int
838 assert str(x) == "0"
839
840 def test_binop_overflow(self):
841 x = int(2)
842 assert x.__lshift__(128) == 680564733841876926926749214863536422912
843
844 def test_rbinop_overflow(self):
845 x = int(321)
846 assert x.__rlshift__(333) == 1422567365923326114875084456308921708325401211889530744784729710809598337369906606315292749899759616
847
848 def test_ceil(self):
849 assert 8 .__ceil__() == 8
850
851 def test_floor(self):
852 assert 8 .__floor__() == 8
853
854 def test_deprecation_warning_1(self):
855 import warnings, _operator
856 class BadInt:
857 def __int__(self):
858 return True
859 def __index__(self):
860 return False
861 bad = BadInt()
862 with warnings.catch_warnings(record=True) as log:
863 warnings.simplefilter("always", DeprecationWarning)
864 n = int(bad)
865 m = _operator.index(bad)
866 assert n == 1 and type(n) is int
867 assert m == 0 and type(m) is int
868 assert len(log) == 2
869
870 def test_deprecation_warning_2(self):
871 import warnings, _operator
872 class BadInt(int):
873 def __int__(self):
874 return self
875 def __index__(self):
876 return self
877 bad = BadInt(1)
878 with warnings.catch_warnings(record=True) as log:
879 warnings.simplefilter("always", DeprecationWarning)
880 n = int(bad)
881 m = _operator.index(bad) # no warning
882 assert n == 1 and type(n) is int
883 print(m, type(m))
884 assert m == 1 and type(m) is int
885 assert len(log) == 1
886 assert log[0].message.args[0].startswith('__int__')
887
888 def test_deprecation_warning_3(self):
889 import warnings, _operator
890 class BadInt(int):
891 def __int__(self):
892 return self
893 def __index__(self):
894 return self
895 bad = BadInt(2**100)
896 with warnings.catch_warnings(record=True) as log:
897 warnings.simplefilter("always", DeprecationWarning)
898 n = int(bad)
899 m = _operator.index(bad) # no warning
900 assert n == bad and type(n) is int
901 assert m == bad and type(m) is int
902 assert len(log) == 1
903 assert log[0].message.args[0].startswith('__int__')
904
905 def test_int_nonstr_with_base(self):
906 assert int(b'100', 2) == 4
907 assert int(bytearray(b'100'), 2) == 4
908 raises(TypeError, int, memoryview(b'100'), 2)
909
910 def test_from_bytes(self):
911 called = []
912 class X(int):
913 def __init__(self, val):
914 called.append(val)
915 x = X.from_bytes(b"", 'little')
916 assert type(x) is X and x == 0
917 assert called == [0]
918 x = X.from_bytes(b"*" * 100, 'little')
919 assert type(x) is X
920 expected = sum(256 ** i for i in range(100)) * ord('*')
921 assert x == expected
922 assert called == [0, expected]
923
924 def test_from_to_bytes_text_signature(self):
925 assert int.from_bytes.__text_signature__ == "($type, /, bytes, byteorder='big', *, signed=False)"
926 assert int.to_bytes.__text_signature__ == "($self, /, length=1, byteorder='big', *, signed=False)"
927
928 def test_leading_zero_literal(self):
929 assert eval("00") == 0
930 raises(SyntaxError, eval, '07')
931 assert int("00", 0) == 0
932 raises(ValueError, int, '07', 0)
933 assert int("07", 10) == 7
934 raises(ValueError, int, '07777777777777777777777777777777777777', 0)
935 raises(ValueError, int, '00000000000000000000000000000000000007', 0)
936 raises(ValueError, int, '00000000000000000077777777777777777777', 0)
937
938 def test_some_rops(self):
939 b = 2 ** 31
940 x = -b
941 assert x.__rsub__(2) == (2 + b)
942
943 def test_round_special_method(self):
944 assert 567 .__round__(-1) == 570
945 assert 567 .__round__() == 567
946 import sys
947 if '__pypy__' in sys.builtin_module_names:
948 assert 567 .__round__(None) == 567 # fails on CPython
949
950
951 def test_error_message_wrong_self(self):
952 unboundmeth = int.__str__
953 e = raises(TypeError, unboundmeth, "!")
954 assert "int" in str(e.value)
955 if hasattr(unboundmeth, 'im_func'):
956 e = raises(TypeError, unboundmeth.im_func, "!")
957 assert "'int'" in str(e.value)
958
959 def test_int_new_pos_only(self):
960 with raises(TypeError) as info:
961 int(x=1)
962 assert "got some positional-only arguments passed as keyword arguments: 'x'" in str(info.value)
963
964 def test_int_as_integer_ratio(self):
965 assert 4 .as_integer_ratio() == (4, 1)
966 assert (-1).as_integer_ratio() == (-1, 1)
967 assert (2 ** 100).as_integer_ratio() == (2 ** 100).as_integer_ratio()
968
969 d, n = True.as_integer_ratio()
970 assert (d, n) == (1, 1)
971 assert type(d) is int
972 d, n = False.as_integer_ratio()
973 assert (d, n) == (0, 1)
974 assert type(d) is int
975
976 class X(int): pass
977 a = X(5)
978 n, d = a.as_integer_ratio()
979 assert n == 5 and d == 1
980 assert type(n) is int
981
982 def test_pow_negative_exponent_mod(self):
983 import math
984 for i in range(1, 7):
985 for j in range(2, 7):
986 for sign in [1, -1]:
987 i = i * sign
988 if math.gcd(i, j) != 1:
989 with raises(ValueError):
990 pow(i, -1, j)
991 continue
992 x = pow(i, -1, j)
993 assert (x * i) % j == 1 % j
994
995 for k in range(2, 4):
996 y = pow(i, -k, j)
997 assert y == pow(x, k, j)
998
999 def test_int_constructor_calls_index(self):
1000 class A:
1001 def __index__(self):
1002 return 25
1003 assert int(A()) == 25
1004 reallybig = 1 << 1000
1005 class A:
1006 def __index__(self):
1007 return reallybig
1008 assert int(A()) == reallybig
1009
1010 class A:
1011 def __index__(self):
1012 return "abc"
1013 with raises(TypeError):
1014 int(A())
1015
1016 class subint(int):
1017 pass
1018 class A:
1019 def __index__(self):
1020 return subint(12)
1021 x = int(A())
1022 assert x == 12
1023 assert type(x) is int
1024
1025 def test_bit_count(self):
1026 for x in (42, 2**100, 2**63, 2**63-1, 2**31-1, 2**31):
1027 assert x.bit_count() == bin(x).count("1")
1028 assert (-x).bit_count() == bin(x).count("1")
1029
1030 def test_rpow_bug(self):
1031 assert (1).__rpow__(2 ** 100) == 2 ** 100
1032
1033
1034 def test_hash_examples():
1035 for i in range(1000):
1036 assert iobj._hash_int(i) == i
1037 assert iobj._hash_int(-i-2) == -i-2
1038 assert iobj._hash_int(-1) == -2
1039
1040 # now bigger/smaller than HASH_MODULUS
1041 for i in range(1000):
1042 input = iobj.HASH_MODULUS + i
1043 assert iobj._hash_int(input) == i
1044
1045 input = -iobj.HASH_MODULUS-i-1
1046 if -i-1 == -1:
1047 assert iobj._hash_int(input) == -2
1048 else:
1049 assert iobj._hash_int(input) == -i-1
1050 if sys.maxsize > 2**31 - 1:
1051 assert iobj._hash_int(-sys.maxsize-1) == -4
1052 else:
1053 assert iobj._hash_int(-sys.maxsize-1) == -2
1054
1055 @given(strategies.integers(min_value=-sys.maxsize-1, max_value=sys.maxsize))
1056 def test_agreement_rbigint_hash(x):
1057 from pypy.objspace.std.longobject import _hash_long
1058 assert iobj._hash_int(x) == _hash_long(rbigint.fromint(x))
1059
1060 class TestHashNoBranch(LLJitMixin):
1061 def test_int_hash_no_guards(self):
1062 res = self.interp_operations(iobj._hash_int, [123])
1063 assert res == 123
1064 self.check_operations_history(guard_true=0, guard_false=0)
1065
1066
1067 class AppTestIntShortcut(AppTestInt):
1068 spaceconfig = {"objspace.std.intshortcut": True}
1069
1070 def test_inplace(self):
1071 # ensure other inplace ops still work
1072 l = []
1073 l += range(5)
1074 assert l == list(range(5))
1075 a = 8.5
1076 a -= .5
1077 assert a == 8