Debian Codegraph @

pypy/objspace/test/apptest_descroperation.py

raw symbols SCIP
1 from pytest import raises
2 import sys
3 import operator
4
5 def test_special_methods():
6 class A:
7 def __lt__(self, other):
8 return "lt"
9 def __imul__(self, other):
10 return "imul"
11 def __sub__(self, other):
12 return "sub"
13 def __rsub__(self, other):
14 return "rsub"
15 def __pow__(self, other):
16 return "pow"
17 def __rpow__(self, other):
18 return "rpow"
19 def __neg__(self):
20 return "neg"
21 a = A()
22 assert (a < 5) == "lt"
23 assert (object() > a) == "lt"
24 a1 = a
25 a1 *= 4
26 assert a1 == "imul"
27 assert a - 2 == "sub"
28 assert a - object() == "sub"
29 assert 2 - a == "rsub"
30 assert object() - a == "rsub"
31 assert a ** 2 == "pow"
32 assert a ** object() == "pow"
33 assert 2 ** a == "rpow"
34 assert object() ** a == "rpow"
35 assert -a == "neg"
36
37 class B(A):
38 def __lt__(self, other):
39 return "B's lt"
40 def __imul__(self, other):
41 return "B's imul"
42 def __sub__(self, other):
43 return "B's sub"
44 def __rsub__(self, other):
45 return "B's rsub"
46 def __pow__(self, other):
47 return "B's pow"
48 def __rpow__(self, other):
49 return "B's rpow"
50 def __neg__(self):
51 return "B's neg"
52
53 b = B()
54 assert (a < b) == "lt"
55 assert (b > a) == "lt"
56 b1 = b
57 b1 *= a
58 assert b1 == "B's imul"
59 a1 = a
60 a1 *= b
61 assert a1 == "imul"
62
63 assert a - b == "B's rsub"
64 assert b - a == "B's sub"
65 assert b - b == "B's sub"
66 assert a ** b == "B's rpow"
67 assert b ** a == "B's pow"
68 assert b ** b == "B's pow"
69 assert -b == "B's neg"
70
71 class C(B):
72 pass
73 c = C()
74 assert c - 1 == "B's sub"
75 assert 1 - c == "B's rsub"
76 assert c - b == "B's sub"
77 assert b - c == "B's sub"
78
79 assert c ** 1 == "B's pow"
80 assert 1 ** c == "B's rpow"
81 assert c ** b == "B's pow"
82 assert b ** c == "B's pow"
83
84 def test_getslice():
85 class Sq(object):
86 def __getitem__(self, key):
87 return key.start, key.stop
88 def __len__(self):
89 return 100
90
91 sq = Sq()
92
93 assert sq[1:3] == (1,3)
94 assert sq[:] == (None, None)
95 assert sq[1:] == (1, None)
96 assert sq[:3] == (None, 3)
97 assert sq[:] == (None, None)
98 # negative indices
99 assert sq[-1:3] == (-1, 3)
100 assert sq[1:-3] == (1, -3)
101 assert sq[-1:-3] == (-1, -3)
102 # extended slice syntax also uses __getitem__()
103 assert sq[::] == (None, None)
104
105 def test_setslice():
106 class Sq(object):
107 def __setitem__(self, key, value):
108 ops.append((key.start, key.stop, value))
109 def __len__(self):
110 return 100
111
112 sq = Sq()
113 ops = []
114 sq[-5:3] = 'hello'
115 sq[12:] = 'world'
116 sq[:-1] = 'spam'
117 sq[:] = 'egg'
118
119 assert ops == [
120 (-5, 3, 'hello'),
121 (12, None, 'world'),
122 (None, -1, 'spam'),
123 (None, None, 'egg'),
124 ]
125
126 def test_delslice():
127 class Sq(object):
128 def __delitem__(self, key):
129 ops.append((key.start, key.stop))
130 def __len__(self):
131 return 100
132
133 sq = Sq()
134 ops = []
135 del sq[5:-3]
136 del sq[-12:]
137 del sq[:1]
138 del sq[:]
139
140 assert ops == [
141 (5, -3),
142 (-12, None),
143 (None,1),
144 (None,None),
145 ]
146
147 def test_getslice_nolength():
148 class Sq(object):
149 def __getitem__(self, key):
150 return key.start, key.stop
151
152 sq = Sq()
153
154 assert sq[1:3] == (1,3)
155 assert sq[:] == (None, None)
156 assert sq[1:] == (1, None)
157 assert sq[:3] == (None, 3)
158 assert sq[:] == (None, None)
159 # negative indices, but no __len__
160 assert sq[-1:3] == (-1, 3)
161 assert sq[1:-3] == (1, -3)
162 assert sq[-1:-3] == (-1, -3)
163 # extended slice syntax also uses __getitem__()
164 assert sq[::] == (None, None)
165
166 def test_ipow():
167 x = 2
168 x **= 5
169 assert x == 32
170
171 def test_typechecks():
172 class myint(int):
173 pass
174 class X(object):
175 def __bool__(self):
176 return myint(1)
177 with raises(TypeError):
178 not X()
179
180 def test_string_subclass():
181 class S(str):
182 def __hash__(self):
183 return 123
184 s = S("abc")
185 setattr(s, s, s)
186 assert len(s.__dict__) == 1
187 # this behavior changed in 2.4
188 #assert type(s.__dict__.keys()[0]) is str # don't store S keys
189 #assert s.abc is s
190 assert getattr(s,s) is s
191
192 def test_notimplemented():
193 #import types
194
195 def specialmethod(self, other):
196 return NotImplemented
197
198 def check(expr, x, y, operator=operator):
199 with raises(TypeError):
200 exec(expr, locals={"x":x, "y":y})
201
202 for metaclass in [type]: # [type, types.ClassType]:
203 for name, expr, iexpr in [
204 ('__add__', 'x + y', 'x += y'),
205 ('__sub__', 'x - y', 'x -= y'),
206 ('__mul__', 'x * y', 'x *= y'),
207 ('__truediv__', 'operator.truediv(x, y)', None),
208 ('__floordiv__', 'operator.floordiv(x, y)', None),
209 ('__div__', 'x / y', 'x /= y'),
210 ('__mod__', 'x % y', 'x %= y'),
211 ('__divmod__', 'divmod(x, y)', None),
212 ('__pow__', 'x ** y', 'x **= y'),
213 ('__lshift__', 'x << y', 'x <<= y'),
214 ('__rshift__', 'x >> y', 'x >>= y'),
215 ('__and__', 'x & y', 'x &= y'),
216 ('__or__', 'x | y', 'x |= y'),
217 ('__xor__', 'x ^ y', 'x ^= y'),
218 ]:
219 rname = '__r' + name[2:]
220 A = metaclass('A', (), {name: specialmethod})
221 B = metaclass('B', (), {rname: specialmethod})
222 a = A()
223 b = B()
224 check(expr, a, a)
225 check(expr, a, b)
226 check(expr, b, a)
227 check(expr, b, b)
228 check(expr, a, 5)
229 check(expr, 5, b)
230 if iexpr:
231 check(iexpr, a, a)
232 check(iexpr, a, b)
233 check(iexpr, b, a)
234 check(iexpr, b, b)
235 check(iexpr, a, 5)
236 iname = '__i' + name[2:]
237 C = metaclass('C', (), {iname: specialmethod})
238 c = C()
239 check(iexpr, c, a)
240 check(iexpr, c, b)
241 check(iexpr, c, 5)
242
243 def test_string_results():
244 class A(object):
245 def __str__(self):
246 return answer * 2
247 def __repr__(self):
248 return answer * 3
249
250 for operate, n in [(str, 2), (repr, 3)]:
251 answer = "hello"
252 assert operate(A()) == "hello" * n
253 assert type(operate(A())) is str
254 answer = 42
255 excinfo = raises(TypeError, operate, A())
256 assert "returned non-string (type 'int')" in str(excinfo.value)
257
258 def test_string_results_unicode():
259 class A(object):
260 def __str__(self):
261 return 'àèì'
262 def __repr__(self):
263 return 'àèì'
264
265 for operate in (str, repr):
266 x = operate(A())
267 assert x == 'àèì'
268 assert type(x) is str
269
270
271 def test_byte_results_unicode():
272 class A(object):
273 def __str__(self):
274 return b'foo'
275 def __repr__(self):
276 return b'bar'
277
278 for operate in (str, repr):
279 raises(TypeError, operate, A())
280
281 def test_missing_getattribute():
282 """
283 class X(object):
284 pass
285
286 class metaclass(type):
287 def mro(cls):
288 return [cls, X]
289 class Y(X, metaclass=metaclass):
290 pass
291
292 x = X()
293 x.__class__ = Y
294 raises(AttributeError, getattr, x, 'a')
295 """
296
297 def test_unordeable_types():
298 class A(object): pass
299 class zz(object): pass
300 with raises(TypeError):
301 A() < zz()
302 with raises(TypeError):
303 zz() > A()
304 with raises(TypeError):
305 A() < A()
306 with raises(TypeError):
307 A() < None
308 with raises(TypeError):
309 None < A()
310 with raises(TypeError):
311 0 < ()
312 with raises(TypeError):
313 0.0 < ()
314 with raises(TypeError):
315 0j < ()
316 with raises(TypeError):
317 0 < []
318 with raises(TypeError):
319 0.0 < []
320 with raises(TypeError):
321 0j < []
322 with raises(TypeError):
323 0 < A()
324 with raises(TypeError):
325 0.0 < A()
326 with raises(TypeError):
327 0j < A()
328 with raises(TypeError):
329 0 < zz()
330 with raises(TypeError):
331 0.0 < zz()
332 with raises(TypeError):
333 0j < zz()
334
335 def test_correct_order_error_msg():
336 class A(object):
337 def __lt__(self, other):
338 return NotImplemented
339 __gt__ = __lt__
340
341 class B(A):
342 pass
343
344 with raises(TypeError) as e:
345 A() < B()
346 assert str(e.value) == "'<' not supported between instances of 'A' and 'B'"
347
348 def test_equality_among_different_types():
349 class A(object): pass
350 class zz(object): pass
351 a = A()
352 assert a == a
353 for x, y in [(A(), A()),
354 (A(), zz()),
355 (A(), A()),
356 (A(), None),
357 (None, A()),
358 (0, ()),
359 (0.0, ()),
360 (0j, ()),
361 (0, []),
362 (0.0, []),
363 (0j, []),
364 (0, A()),
365 (0.0, A()),
366 (0j, A()),
367 ]:
368 assert not x == y
369 assert x != y
370
371
372 def test_setattrweakref():
373 skip("fails, works in cpython")
374 # The issue is that in CPython, none of the built-in types have
375 # a __weakref__ descriptor, even if their instances are weakrefable.
376 # Should we emulate this?
377 class P(object):
378 pass
379
380 setattr(P, "__weakref__", 0)
381
382 def test_subclass_addition():
383 # the __radd__ is never called (compare with the next test)
384 l = []
385 class A(object):
386 def __add__(self, other):
387 l.append(self.__class__)
388 l.append(other.__class__)
389 return 123
390 def __radd__(self, other):
391 # should never be called!
392 return 456
393 class B(A):
394 pass
395 res1 = A() + B()
396 res2 = B() + A()
397 assert res1 == res2 == 123
398 assert l == [A, B, B, A]
399
400 def test__eq__called():
401 l = []
402 class A(object):
403 def __eq__(self, other):
404 l.append((self, other))
405 return True
406 a = A()
407 a == a
408 assert l == [(a, a)]
409
410 def test_subclass_comparison():
411 # the __eq__ *is* called with reversed arguments
412 l = []
413 class A(object):
414 def __eq__(self, other):
415 l.append(self.__class__)
416 l.append(other.__class__)
417 return False
418
419 def __lt__(self, other):
420 l.append(self.__class__)
421 l.append(other.__class__)
422 return False
423
424 class B(A):
425 pass
426
427 A() == B()
428 A() < B()
429 B() < A()
430 assert l == [B, A, A, B, B, A]
431
432 def test_subclass_comparison_more():
433 # similarly, __gt__(b,a) is called instead of __lt__(a,b)
434 l = []
435 class A(object):
436 def __lt__(self, other):
437 l.append(self.__class__)
438 l.append(other.__class__)
439 return '<'
440 def __gt__(self, other):
441 l.append(self.__class__)
442 l.append(other.__class__)
443 return '>'
444 class B(A):
445 pass
446 res1 = A() < B()
447 res2 = B() < A()
448 assert res1 == '>' and res2 == '<'
449 assert l == [B, A, B, A]
450
451 def test_rich_comparison():
452 class A:
453 def __init__(self, a):
454 self.a = a
455 def __eq__(self, other):
456 return self.a == other.a
457 class B:
458 def __init__(self, a):
459 self.a = a
460
461 assert A(1) == B(1)
462 assert B(1) == A(1)
463 assert not(A(1) == B(2))
464 assert not(B(1) == A(2))
465 assert A(1) != B(2)
466 assert B(1) != A(2)
467 assert not(A(1) != B(1))
468 assert not(B(1) != A(1))
469
470 def test_ne_high_priority():
471 """object.__ne__() should allow reflected __ne__() to be tried"""
472 calls = []
473 class Left:
474 # Inherits object.__ne__()
475 def __eq__(*args):
476 calls.append('Left.__eq__')
477 return NotImplemented
478 class Right:
479 def __eq__(*args):
480 calls.append('Right.__eq__')
481 return NotImplemented
482 def __ne__(*args):
483 calls.append('Right.__ne__')
484 return NotImplemented
485 Left() != Right()
486 assert calls == ['Left.__eq__', 'Right.__ne__']
487
488 def test_ne_low_priority():
489 """object.__ne__() should not invoke reflected __eq__()"""
490 calls = []
491 class Base:
492 # Inherits object.__ne__()
493 def __eq__(*args):
494 calls.append('Base.__eq__')
495 return NotImplemented
496 class Derived(Base): # Subclassing forces higher priority
497 def __eq__(*args):
498 calls.append('Derived.__eq__')
499 return NotImplemented
500 def __ne__(*args):
501 calls.append('Derived.__ne__')
502 return NotImplemented
503 Base() != Derived()
504 assert calls == ['Derived.__ne__', 'Base.__eq__']
505
506 def test_partial_ordering():
507 class A(object):
508 def __lt__(self, other):
509 return self
510 a1 = A()
511 a2 = A()
512 assert (a1 < a2) is a1
513 assert (a1 > a2) is a2
514
515 def test_eq_order():
516 class A(object):
517 def __eq__(self, other): return self.__class__.__name__+':A.eq'
518 def __ne__(self, other): return self.__class__.__name__+':A.ne'
519 def __lt__(self, other): return self.__class__.__name__+':A.lt'
520 def __le__(self, other): return self.__class__.__name__+':A.le'
521 def __gt__(self, other): return self.__class__.__name__+':A.gt'
522 def __ge__(self, other): return self.__class__.__name__+':A.ge'
523 class B(object):
524 def __eq__(self, other): return self.__class__.__name__+':B.eq'
525 def __ne__(self, other): return self.__class__.__name__+':B.ne'
526 def __lt__(self, other): return self.__class__.__name__+':B.lt'
527 def __le__(self, other): return self.__class__.__name__+':B.le'
528 def __gt__(self, other): return self.__class__.__name__+':B.gt'
529 def __ge__(self, other): return self.__class__.__name__+':B.ge'
530 #
531 assert (A() == B()) == 'A:A.eq'
532 assert (A() != B()) == 'A:A.ne'
533 assert (A() < B()) == 'A:A.lt'
534 assert (A() <= B()) == 'A:A.le'
535 assert (A() > B()) == 'A:A.gt'
536 assert (A() >= B()) == 'A:A.ge'
537 #
538 assert (B() == A()) == 'B:B.eq'
539 assert (B() != A()) == 'B:B.ne'
540 assert (B() < A()) == 'B:B.lt'
541 assert (B() <= A()) == 'B:B.le'
542 assert (B() > A()) == 'B:B.gt'
543 assert (B() >= A()) == 'B:B.ge'
544 #
545 class C(A):
546 def __eq__(self, other): return self.__class__.__name__+':C.eq'
547 def __ne__(self, other): return self.__class__.__name__+':C.ne'
548 def __lt__(self, other): return self.__class__.__name__+':C.lt'
549 def __le__(self, other): return self.__class__.__name__+':C.le'
550 def __gt__(self, other): return self.__class__.__name__+':C.gt'
551 def __ge__(self, other): return self.__class__.__name__+':C.ge'
552 #
553 assert (A() == C()) == 'C:C.eq'
554 assert (A() != C()) == 'C:C.ne'
555 assert (A() < C()) == 'C:C.gt'
556 assert (A() <= C()) == 'C:C.ge'
557 assert (A() > C()) == 'C:C.lt'
558 assert (A() >= C()) == 'C:C.le'
559 #
560 assert (C() == A()) == 'C:C.eq'
561 assert (C() != A()) == 'C:C.ne'
562 assert (C() < A()) == 'C:C.lt'
563 assert (C() <= A()) == 'C:C.le'
564 assert (C() > A()) == 'C:C.gt'
565 assert (C() >= A()) == 'C:C.ge'
566 #
567 class D(A):
568 pass
569 #
570 assert (A() == D()) == 'D:A.eq'
571 assert (A() != D()) == 'D:A.ne'
572 assert (A() < D()) == 'D:A.gt'
573 assert (A() <= D()) == 'D:A.ge'
574 assert (A() > D()) == 'D:A.lt'
575 assert (A() >= D()) == 'D:A.le'
576 #
577 assert (D() == A()) == 'D:A.eq'
578 assert (D() != A()) == 'D:A.ne'
579 assert (D() < A()) == 'D:A.lt'
580 assert (D() <= A()) == 'D:A.le'
581 assert (D() > A()) == 'D:A.gt'
582 assert (D() >= A()) == 'D:A.ge'
583
584 def test_binop_rule():
585 called = []
586 class A:
587 def __eq__(self, other):
588 called.append(self)
589 return NotImplemented
590 a1 = A()
591 a2 = A()
592 a1 == a2
593 assert called == [a1, a2]
594
595 def test_addition():
596 class A:
597 def __init__(self, a):
598 self.a = a
599 def __add__(self, other):
600 return self.a + other.a
601 __radd__ = __add__
602 class B:
603 def __init__(self, a):
604 self.a = a
605
606 assert A(1) + B(2) == 3
607 assert B(1) + A(2) == 3
608
609 def test_mod_failure():
610 try:
611 [] % 3
612 except TypeError as e:
613 assert '%' in str(e)
614 else:
615 assert False, "did not raise"
616
617 def test_invalid_iterator():
618 class x(object):
619 def __iter__(self):
620 return self
621 raises(TypeError, iter, x())
622
623 def test_iterator_is_None():
624 class x(object):
625 __iter__ = None
626 with raises(TypeError) as info:
627 iter(x())
628 assert str(info.value) == "'x' object is not iterable"
629
630
631 def test_attribute_error():
632 class classmethodonly(classmethod):
633 def __get__(self, instance, type):
634 if instance is not None:
635 raise AttributeError("Must be called on a class, not an instance.")
636 return super(classmethodonly, self).__get__(instance, type)
637
638 class A(object):
639 @classmethodonly
640 def a(cls):
641 return 3
642
643 raises(AttributeError, lambda: A().a)
644
645 def test_attribute_error2():
646 class A(object):
647 def __eq__(self, other):
648 raise AttributeError('doh')
649 raises(AttributeError, operator.eq, A(), A())
650
651 class E(object):
652 @property
653 def __eq__(self):
654 raise AttributeError('doh')
655 assert not (E() == E())
656
657 def test_delete_descriptor():
658 class Prop(object):
659 def __get__(self, obj, cls):
660 return 42
661 def __delete__(self, obj):
662 obj.deleted = True
663 class C(object):
664 x = Prop()
665 obj = C()
666 del obj.x
667 assert obj.deleted
668
669 def test_non_callable():
670 meth = classmethod(1).__get__(1)
671 raises(TypeError, meth)
672
673 def test_isinstance_and_issubclass():
674 class Meta(type):
675 def __instancecheck__(cls, instance):
676 if cls is A:
677 return True
678 return False
679 def __subclasscheck__(cls, sub):
680 if cls is B:
681 return True
682 return False
683 A = Meta('A', (), {}) # like "class A(metaclass=Meta)", but
684 # Python2 cannot parse this
685 class B(A):
686 pass
687 a = A()
688 b = B()
689 assert isinstance(a, A) # "shortcut" does not go through metaclass
690 assert not isinstance(a, B)
691 assert isinstance(b, A)
692 assert isinstance(b, B) # "shortcut" does not go through metaclass
693 assert isinstance(4, A)
694 assert not issubclass(A, A)
695 assert not issubclass(B, A)
696 assert issubclass(A, B)
697 assert issubclass(B, B)
698 assert issubclass(23, B)
699
700 def test_rebind_method():
701 # No check is done on a method copied to another type
702 class A:
703 def method(self):
704 return 42
705 class Dict:
706 method = A.method
707 assert Dict().method() == 42
708
709 def test_len_overflow():
710 class X(object):
711 def __len__(self):
712 return sys.maxsize + 1
713 raises(OverflowError, len, X())
714 raises(OverflowError, bool, X())
715
716 def test_len_underflow():
717 class X(object):
718 def __len__(self):
719 return -1
720 raises(ValueError, len, X())
721 raises(ValueError, bool, X())
722
723 def test_len_custom__int__():
724 class X(object):
725 def __init__(self, x):
726 self.x = x
727 def __len__(self):
728 return self.x
729 def __int__(self):
730 return self.x
731
732 raises(TypeError, len, X(3.0))
733 raises(TypeError, len, X(X(2)))
734 raises(TypeError, bool, X(3.0))
735 raises(TypeError, bool, X(X(2)))
736 raises(OverflowError, len, X(sys.maxsize + 1))
737
738 def test_len_index():
739 class Index(object):
740 def __index__(self):
741 return 42
742 class X(object):
743 def __len__(self):
744 return Index()
745 n = len(X())
746 assert type(n) is int
747 assert n == 42
748
749 class BadIndex(object):
750 def __index__(self):
751 return 'foo'
752 class Y(object):
753 def __len__(self):
754 return BadIndex()
755 excinfo = raises(TypeError, len, Y())
756 assert excinfo.value.args[0].startswith("__index__ returned non-")
757
758 class BadIndex2(object):
759 def __index__(self):
760 return 2**100
761 class Z(object):
762 def __len__(self):
763 return BadIndex2()
764 excinfo = raises(OverflowError, len, Z())
765
766 def test_sane_len():
767 # this test just tests our assumptions about __len__
768 # this will start failing if __len__ changes assertions
769 for badval in ['illegal', -1, 1 << 32]:
770 class A:
771 def __len__(self):
772 return badval
773 try:
774 bool(A())
775 except (Exception) as e_bool:
776 try:
777 len(A())
778 except (Exception) as e_len:
779 assert str(e_bool) == str(e_len)
780
781 def test_bool___contains__():
782 class X(object):
783 def __contains__(self, item):
784 if item == 'foo':
785 return 42
786 else:
787 return 'hello world'
788 x = X()
789 res = 'foo' in x
790 assert res is True
791 res = 'bar' in x
792 assert res is True
793 #
794 class MyError(Exception):
795 pass
796 class CannotConvertToBool(object):
797 def __bool__(self):
798 raise MyError
799 class X(object):
800 def __contains__(self, item):
801 return CannotConvertToBool()
802 x = X()
803 with raises(MyError):
804 'foo' in x
805
806 def test_sequence_rmul_overrides():
807 class oops(object):
808 def __rmul__(self, other):
809 return 42
810 def __index__(self):
811 return 3
812 assert b'2' * oops() == 42
813 assert [2] * oops() == 42
814 assert (2,) * oops() == 42
815 assert u'2' * oops() == 42
816 assert bytearray(b'2') * oops() == 42
817 assert 1000 * oops() == 42
818 assert b'2'.__mul__(oops()) == b'222'
819 x = '2'
820 x *= oops()
821 assert x == 42
822 x = [2]
823 x *= oops()
824 assert x == 42
825
826 def test_sequence_rmul_overrides_oldstyle():
827 class oops:
828 def __rmul__(self, other):
829 return 42
830 def __index__(self):
831 return 3
832 assert b'2' * oops() == 42
833 assert [2] * oops() == 42
834 assert (2,) * oops() == 42
835 assert u'2' * oops() == 42
836 assert bytearray(b'2') * oops() == 42
837 assert 1000 * oops() == 42
838 assert b'2'.__mul__(oops()) == b'222'
839
840 def test_sequence_radd_overrides():
841 class A1(list):
842 pass
843 class A2(list):
844 def __radd__(self, other):
845 return 42
846 assert [2] + A1([3]) == [2, 3]
847 assert type([2] + A1([3])) is list
848 assert [2] + A2([3]) == 42
849 x = "2"
850 x += A2([3])
851 assert x == 42
852 x = [2]
853 x += A2([3])
854 assert x == 42
855
856 def test_data_descriptor_without_delete():
857 class D(object):
858 def __set__(self, x, y):
859 pass
860 class A(object):
861 d = D()
862 with raises(AttributeError):
863 del A().d
864
865 def test_data_descriptor_without_set():
866 class D(object):
867 def __delete__(self, x):
868 pass
869 class A(object):
870 d = D()
871 with raises(AttributeError):
872 A().d = 5
873
874 def test_not_subscriptable_error_gives_keys():
875 d = {'key1': {'key2': {'key3': None}}}
876 with raises(TypeError) as excinfo:
877 d['key1']['key2']['key3']['key4']['key5']
878 assert "key4" in str(excinfo.value)
879
880 def test_64bit_hash():
881 class BigHash(object):
882 def __hash__(self):
883 return sys.maxsize + 2
884 def __eq__(self, other):
885 return isinstance(other, BigHash)
886 # previously triggered an OverflowError
887 d = {BigHash(): None}
888 assert BigHash() in d
889
890 def test_class_getitem():
891 with raises(TypeError) as excinfo:
892 int[int]
893 assert "type 'int' is not subscriptable" in str(excinfo.value)
894
895 def test_error_ipow():
896 with raises(TypeError) as info:
897 x = None
898 x **= 2
899 assert "unsupported operand type(s) for **=: 'NoneType' and 'int'" in str(info.value)
900
901 def test_error_pow():
902 with raises(TypeError) as info:
903 None ** 2
904 assert "unsupported operand type(s) for ** or pow(): 'NoneType' and 'int'" in str(info.value)
905 with raises(TypeError) as info:
906 pow(None, 2, 2.1)
907 assert "unsupported operand type(s) for pow(): 'NoneType', 'int', 'float'" in str(info.value)
908
909 def test_type_subscription_message():
910 with raises(TypeError) as info:
911 Exception[int]
912 assert "type 'Exception' is not subscriptable" in str(info.value)
913
914 def test_rpow_not_used_when_third_argument():
915 class RPOW(object):
916 def __pow__(self, other, mod=None):
917 print("__pow__")
918 return 123
919 def __rpow__(self, other, mod=None):
920 print("__rpow__")
921 return 321
922
923 a = RPOW()
924 with raises(TypeError):
925 pow(1, a, a)