Debian Codegraph @

pypy/objspace/std/test/test_typeobject.py

raw symbols SCIP
1 # encoding: utf-8
2 import py
3 from pypy.interpreter.baseobjspace import W_Root
4 from pypy.interpreter.gateway import interp2app
5 from pypy.interpreter.typedef import TypeDef
6
7
8 class TestTypeObject:
9 def test_not_acceptable_as_base_class(self):
10 space = self.space
11 class W_Stuff(W_Root):
12 pass
13 def descr__new__(space, w_subtype):
14 return space.allocate_instance(W_Stuff, w_subtype)
15 W_Stuff.typedef = TypeDef("stuff",
16 __new__ = interp2app(descr__new__))
17 W_Stuff.typedef.acceptable_as_base_class = False
18 w_stufftype = space.gettypeobject(W_Stuff.typedef)
19 space.appexec([w_stufftype], """(stufftype):
20 x = stufftype.__new__(stufftype)
21 assert type(x) is stufftype
22 raises(TypeError, stufftype.__new__)
23 raises(TypeError, stufftype.__new__, int)
24 raises(TypeError, stufftype.__new__, 42)
25 raises(TypeError, stufftype.__new__, stufftype, 511)
26 raises(TypeError, type, 'sub', (stufftype,), {})
27 """)
28
29 def test_del_warning(self):
30 warnings = []
31 def my_warn(msg, warningscls):
32 warnings.append(msg)
33 prev_warn(msg, warningscls)
34 space = self.space
35 prev_warn = space.warn
36 try:
37 space.warn = my_warn
38 space.appexec([], """():
39 class X(object):
40 pass
41 X.__del__ = 5
42 X.__del__ = 6
43 X.__del__ = 7
44 class Y(object):
45 pass
46 Y.__del__ = 8
47 Y.__del__ = 9
48 Y.__del__ = 0
49 class Z(object):
50 pass
51 Z._foobar_ = 3
52 Z._foobar_ = 4
53 class U(object):
54 def __del__(self):
55 pass
56 U.__del__ = lambda self: 42 # no warning here
57 """)
58 finally:
59 space.warn = prev_warn
60 assert len(warnings) == 2
61
62 def test_setattr_if_not_from_object(self):
63 space = self.space
64 w_A, w_B = space.unpackiterable(space.appexec([], """():
65 class A(object):
66 pass
67 class B(object):
68 def __setattr__(self, obj, name, value):
69 pass
70 return A, B
71 """))
72 assert w_A.uses_object_setattr is False
73 w_res = w_A.setattr_if_not_from_object()
74 assert w_res is None
75 assert w_A.uses_object_setattr is True
76
77 assert w_B.uses_object_setattr is False
78 w_res = w_B.setattr_if_not_from_object()
79 assert w_res is not None
80 assert w_B.uses_object_setattr is False
81
82 # check invalidation
83 space.setattr(w_A, space.newtext("__setattr__"), space.newint(1))
84 assert w_A.uses_object_setattr is False
85 w_res = w_A.setattr_if_not_from_object()
86 assert w_res is not None
87 assert w_A.uses_object_setattr is False
88
89
90 class AppTestTypeObject:
91 def test_abstract_methods(self):
92 class X(object):
93 pass
94 X.__abstractmethods__ = ("meth",)
95 raises(TypeError, X)
96 del X.__abstractmethods__
97 X()
98 raises(AttributeError, getattr, type, "__abstractmethods__")
99 raises(TypeError, "int.__abstractmethods__ = ('abc', )")
100
101 def test_method_descriptor_flag(self):
102 # Replicates test.test_call.TestPEP590.test_method_descriptor_flag
103 Py_TPFLAGS_METHOD_DESCRIPTOR = 1 << 17
104 # function type: method descriptor (list.append is a Function in PyPy)
105 assert type(list.append).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR
106 assert type(list.__add__).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR
107 assert type(lambda: None).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR
108 # builtin_function type: NOT a method descriptor
109 # (if this were True, LOAD_METHOD would prepend self to builtin calls)
110 assert not (type(repr).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
111 assert not (type(len).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
112 # staticmethod and classmethod: NOT method descriptors
113 assert not (type(staticmethod(lambda: None)).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
114 assert not (type(classmethod(lambda: None)).__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
115 # Heap types should not have Py_TPFLAGS_METHOD_DESCRIPTOR
116 assert not (type.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
117 class Foo:
118 pass
119 assert not (Foo.__flags__ & Py_TPFLAGS_METHOD_DESCRIPTOR)
120
121 def test_is_abstract_flag(self):
122 # IS_ABSTRACT flag should always be in sync with
123 # cls.__dict__['__abstractmethods__']
124 FLAG_IS_ABSTRACT = 1 << 20
125
126 class Base:
127 pass
128 Base.__abstractmethods__ = {'x'}
129 assert Base.__flags__ & FLAG_IS_ABSTRACT
130
131 class Derived(Base):
132 pass
133 assert not (Derived.__flags__ & FLAG_IS_ABSTRACT)
134 Derived.__abstractmethods__ = {'x'}
135 assert Derived.__flags__ & FLAG_IS_ABSTRACT
136
137 def test_attribute_error(self):
138 class X(object):
139 __module__ = 'test'
140 x = X()
141 exc = raises(AttributeError, "x.a")
142 assert str(exc.value) == "'X' object has no attribute 'a'"
143 assert exc.value.name == "a"
144 exc = raises(AttributeError, "X.a")
145 assert str(exc.value) == "type object 'X' has no attribute 'a'"
146 assert exc.value.name == "a"
147 exc = raises(AttributeError, "del x.a")
148 assert str(exc.value) == "'X' object has no attribute 'a'"
149 assert exc.value.name == "a"
150 exc = raises(AttributeError, "del X.a")
151 assert str(exc.value) == "type object 'X' has no attribute 'a'"
152 assert exc.value.name == "a"
153
154 def test_call_type(self):
155 assert type(42) is int
156 C = type('C', (object,), {'x': lambda: 42})
157 func = C.x
158 assert func() == 42
159 raises(TypeError, type)
160 raises(TypeError, type, 'test', (object,))
161 raises(TypeError, type, 'test', (object,), {}, 42)
162 raises(TypeError, type, 42, (object,), {})
163 raises(TypeError, type, 'test', 42, {})
164 raises(TypeError, type, 'test', (object,), 42)
165
166 def test_call_type_subclass(self):
167 """
168 class A(type):
169 pass
170
171 # Make sure type(x) doesn't call x.__class__.__init__
172 class T(type):
173 counter = 0
174 def __init__(self, *args):
175 T.counter += 1
176 class C(metaclass=T):
177 pass
178 assert T.counter == 1
179 a = C()
180 assert T.counter == 1
181 assert type(a) is C
182 assert T.counter == 1
183 """
184
185 def test_bases(self):
186 """
187 assert int.__bases__ == (object,)
188 class X(metaclass=type):
189 pass
190 assert X.__bases__ == (object,)
191 class Y(X): pass
192 assert Y.__bases__ == (X,)
193 class Z(Y,X): pass
194 assert Z.__bases__ == (Y, X)
195
196 Z.__bases__ = (X,)
197 #print Z.__bases__
198 assert Z.__bases__ == (X,)
199 """
200
201 def test_mutable_bases(self):
202 # from CPython's test_descr
203 class C(object):
204 pass
205 class C2(object):
206 def __getattribute__(self, attr):
207 if attr == 'a':
208 return 2
209 else:
210 return super(C2, self).__getattribute__(attr)
211 def meth(self):
212 return 1
213 class D(C):
214 pass
215 class E(D):
216 pass
217 d = D()
218 e = E()
219 D.__bases__ = (C,)
220 D.__bases__ = (C2,)
221 assert d.meth() == 1
222 assert e.meth() == 1
223 assert d.a == 2
224 assert e.a == 2
225 assert C2.__subclasses__() == [D]
226
227 # stuff that shouldn't:
228 class L(list):
229 pass
230
231 try:
232 L.__bases__ = (dict,)
233 except TypeError:
234 pass
235 else:
236 assert 0, "shouldn't turn list subclass into dict subclass"
237
238 try:
239 list.__bases__ = (dict,)
240 except TypeError:
241 pass
242 else:
243 assert 0, "shouldn't be able to assign to list.__bases__"
244
245 try:
246 D.__bases__ = (C2, list)
247 except TypeError:
248 pass
249 else:
250 assert 0, "best_base calculation found wanting"
251
252 try:
253 del D.__bases__
254 except (TypeError, AttributeError):
255 pass
256 else:
257 assert 0, "shouldn't be able to delete .__bases__"
258
259 try:
260 D.__bases__ = ()
261 except TypeError as msg:
262 if str(msg) == "a new-style class can't have only classic bases":
263 assert 0, "wrong error message for .__bases__ = ()"
264 else:
265 assert 0, "shouldn't be able to set .__bases__ to ()"
266
267 try:
268 D.__bases__ = (D,)
269 except TypeError:
270 pass
271 else:
272 # actually, we'll have crashed by here...
273 assert 0, "shouldn't be able to create inheritance cycles"
274
275 try:
276 D.__bases__ = (C, C)
277 except TypeError:
278 pass
279 else:
280 assert 0, "didn't detect repeated base classes"
281
282 try:
283 D.__bases__ = (E,)
284 except TypeError:
285 pass
286 else:
287 assert 0, "shouldn't be able to create inheritance cycles"
288
289 def test_mutable_bases_with_failing_mro(self):
290 """
291 class WorkOnce(type):
292 def __new__(self, name, bases, ns):
293 self.flag = 0
294 return super(WorkOnce, self).__new__(WorkOnce, name, bases, ns)
295 def mro(instance):
296 if instance.flag > 0:
297 raise RuntimeError("bozo")
298 else:
299 instance.flag += 1
300 return type.mro(instance)
301
302 class WorkAlways(type):
303 def mro(self):
304 # this is here to make sure that .mro()s aren't called
305 # with an exception set (which was possible at one point).
306 # An error message will be printed in a debug build.
307 # What's a good way to test for this?
308 return type.mro(self)
309
310 class C(object):
311 pass
312
313 class C2(object):
314 pass
315
316 class D(C):
317 pass
318
319 class E(D):
320 pass
321
322 class F(D, metaclass=WorkOnce):
323 pass
324
325 class G(D, metaclass=WorkAlways):
326 pass
327
328 # Immediate subclasses have their mro's adjusted in alphabetical
329 # order, so E's will get adjusted before adjusting F's fails. We
330 # check here that E's gets restored.
331
332 E_mro_before = E.__mro__
333 D_mro_before = D.__mro__
334
335 try:
336 D.__bases__ = (C2,)
337 except RuntimeError:
338 assert D.__mro__ == D_mro_before
339 assert E.__mro__ == E_mro_before
340 else:
341 assert 0, "exception not propagated"
342 """
343
344 def test_mutable_bases_with_failing_mro_2(self): """
345 class E(Exception):
346 pass
347 class M(type):
348 def mro(cls):
349 if cls.__name__ == 'Sub' and A.__bases__ == (Base1,):
350 A.__bases__ = (Base2,)
351 raise E
352 return type.mro(cls)
353
354 class Base0:
355 pass
356 class Base1:
357 pass
358 class Base2:
359 pass
360 class A(Base0, metaclass=M):
361 pass
362 class Sub(A):
363 pass
364
365 try:
366 A.__bases__ = (Base1,)
367 except E:
368 assert A.__bases__ == (Base2,)
369 assert A.__mro__ == (A, Base2, object)
370 assert Sub.__mro__ == (Sub, A, Base2, object)
371 else:
372 assert 0
373 """
374
375 def test_mutable_bases_catch_mro_conflict(self):
376 class A(object):
377 pass
378
379 class B(object):
380 pass
381
382 class C(A, B):
383 pass
384
385 class D(A, B):
386 pass
387
388 class E(C, D):
389 pass
390
391 try:
392 C.__bases__ = (B, A)
393 except TypeError:
394 pass
395 else:
396 raise TestFailed("didn't catch MRO conflict")
397
398 def test_mutable_bases_versus_nonheap_types(self):
399 class A(int):
400 pass
401 class B(int):
402 __slots__ = ['b']
403 class C(int):
404 pass
405 raises(TypeError, 'C.__bases__ = (A,)')
406 raises(TypeError, 'C.__bases__ = (B,)')
407 raises(TypeError, 'C.__bases__ = (C,)')
408 raises(TypeError, 'int.__bases__ = (object,)')
409 C.__bases__ = (int,)
410 #--- the following raises on CPython but works on PyPy.
411 #--- I don't see an obvious reason why it should fail...
412 import sys
413 if '__pypy__' not in sys.builtin_module_names:
414 skip("works on PyPy only")
415 class MostlyLikeInt(int):
416 __slots__ = []
417 C.__bases__ = (MostlyLikeInt,)
418
419 def test_mutable_bases_versus_slots(self):
420 class A(object):
421 __slots__ = ['a']
422 class B(A):
423 __slots__ = ['b1', 'b2']
424 class C(B):
425 pass
426 raises(TypeError, 'C.__bases__ = (A,)')
427
428 def test_mutable_bases_versus_weakref(self):
429 class A(object):
430 __slots__ = ['a']
431 class B(A):
432 __slots__ = ['__weakref__']
433 class C(B):
434 pass
435 raises(TypeError, 'C.__bases__ = (A,)')
436
437 def test_mutable_bases_same_slots(self):
438 class A(object):
439 __slots__ = ['a']
440 class B(A):
441 __slots__ = []
442 class C(B):
443 pass
444 c = C()
445 c.a = 42
446 assert C.__mro__ == (C, B, A, object)
447 C.__bases__ = (A,)
448 assert C.__mro__ == (C, A, object)
449 assert c.a == 42
450
451 def test_mutable_bases_versus_slots_2(self):
452 class A(object):
453 __slots__ = ['a']
454 class B(A):
455 __slots__ = ['b1', 'b2']
456 class C(B):
457 __slots__ = ['c']
458 raises(TypeError, 'C.__bases__ = (A,)')
459
460 def test_mutable_bases_keeping_slots(self):
461 class A(object):
462 __slots__ = ['a']
463 class B(A):
464 __slots__ = []
465 class C(B):
466 __slots__ = ['c']
467 c = C()
468 c.a = 42
469 c.c = 85
470 assert C.__mro__ == (C, B, A, object)
471 C.__bases__ = (A,)
472 assert C.__mro__ == (C, A, object)
473 assert c.a == 42
474 assert c.c == 85
475
476 class D(A):
477 __slots__ = []
478 C.__bases__ = (B, D)
479 assert C.__mro__ == (C, B, D, A, object)
480 assert c.a == 42
481 assert c.c == 85
482 raises(TypeError, 'C.__bases__ = (B, D, B)')
483
484 class E(A):
485 __slots__ = ['e']
486 raises(TypeError, 'C.__bases__ = (B, E)')
487 raises(TypeError, 'C.__bases__ = (E, B)')
488 raises(TypeError, 'C.__bases__ = (E,)')
489
490 def test_compatible_slot_layout(self):
491 class A(object):
492 __slots__ = ['a']
493 class B(A):
494 __slots__ = ['b1', 'b2']
495 class C(A):
496 pass
497 class D(B, C): # assert does not raise TypeError
498 pass
499
500 def test_method_qualname(self):
501 assert dict.copy.__qualname__ == 'dict.copy'
502
503 def test_staticmethod_qualname(self):
504 assert dict.__new__.__qualname__ == 'dict.__new__'
505 class A:
506 @staticmethod
507 def stat():
508 pass
509 assert A.stat.__qualname__.endswith('A.stat')
510
511 def test_builtin_add(self):
512 x = 5
513 assert x.__add__(6) == 11
514 x = 3.5
515 assert x.__add__(2) == 5.5
516 assert x.__add__(2.0) == 5.5
517
518 def test_builtin_call(self):
519 def f(*args):
520 return args
521 assert f.__call__() == ()
522 assert f.__call__(5) == (5,)
523 assert f.__call__("hello", "world") == ("hello", "world")
524
525 def test_builtin_call_kwds(self):
526 def f(*args, **kwds):
527 return args, kwds
528 assert f.__call__() == ((), {})
529 assert f.__call__("hello", "world") == (("hello", "world"), {})
530 assert f.__call__(5, bla=6) == ((5,), {"bla": 6})
531 assert f.__call__(a=1, b=2, c=3) == ((), {"a": 1, "b": 2, "c": 3})
532
533 def test_multipleinheritance_fail(self):
534 try:
535 class A(int, dict):
536 pass
537 except TypeError:
538 pass
539 else:
540 raise AssertionError("this multiple inheritance should fail")
541
542 def test_outer_metaclass(self):
543 """
544 class OuterMetaClass(type):
545 pass
546
547 class HasOuterMetaclass(metaclass=OuterMetaClass):
548 pass
549
550 assert type(HasOuterMetaclass) == OuterMetaClass
551 """
552
553 def test_mro(self):
554 """
555 class A_mro(object):
556 a = 1
557
558 class mymeta(type):
559 def mro(self, ignore=False):
560 assert ignore or self.__mro__ is None
561 return [self, object]
562
563 class B_mro(A_mro, metaclass=mymeta):
564 b = 1
565
566 assert B_mro.__bases__ == (A_mro,)
567 assert B_mro.__mro__ == (B_mro, object)
568 assert B_mro.mro(ignore=True) == [B_mro, object]
569 assert B_mro.b == 1
570 assert B_mro().b == 1
571 assert getattr(B_mro, 'a', None) == None
572 assert getattr(B_mro(), 'a', None) == None
573 # also check what the built-in mro() method would return for 'B_mro'
574 assert type.mro(B_mro) == [B_mro, A_mro, object]
575 """
576
577 def test_mro_mutation_interaction_bug(self):
578 """
579 class Base(object):
580 value = 1
581
582 class Meta(type):
583 def mro(cls):
584 return (cls, Base, object)
585
586 class WeirdClass(metaclass=Meta):
587 pass
588
589 assert Base.value == 1
590 assert WeirdClass.value == 1
591
592 Base.value = 2
593 assert Base.value == 2
594 assert WeirdClass.value == 2
595
596 Base.value = 3
597 assert Base.value == 3
598 assert WeirdClass.value == 3
599
600 assert len(Base.__subclasses__()) == 0
601 """
602
603 def test_abstract_mro(self):
604 """
605 class A1: # in py3k is a new-style class
606 pass
607 class B1(A1):
608 pass
609 class C1(A1):
610 pass
611 class D1(B1, C1):
612 pass
613 class E1(D1, object, metaclass=type):
614 pass
615 # new-style MRO, contrarily to python2
616 assert E1.__mro__ == (E1, D1, B1, C1, A1, object)
617 """
618
619 def test_metaclass_conflict(self):
620 """
621 class T1(type):
622 pass
623 class T2(type):
624 pass
625 class D1(metaclass=T1):
626 pass
627 class D2(metaclass=T2):
628 pass
629 def conflict():
630 class C(D1,D2):
631 pass
632 raises(TypeError, conflict)
633 """
634
635 def test_metaclass_choice(self):
636 """
637 events = []
638
639 class T1(type):
640 def __new__(*args):
641 events.append(args)
642 return type.__new__(*args)
643
644 class D1(metaclass=T1):
645 pass
646
647 class C(D1):
648 pass
649
650 class F(object):
651 pass
652
653 class G(F,D1):
654 pass
655
656 assert len(events) == 3
657 assert type(D1) is T1
658 assert type(C) is T1
659 assert type(G) is T1
660 """
661
662 def test_descr_typecheck(self):
663 raises(TypeError,type.__dict__['__name__'].__get__,1)
664 raises(TypeError,type.__dict__['__mro__'].__get__,1)
665
666 def test_slots_simple(self):
667 class A(object):
668 __slots__ = ('x',)
669 a = A()
670 raises(AttributeError, getattr, a, 'x')
671 raises(AttributeError, delattr, a, 'x')
672 a.x = 1
673 assert a.x == 1
674 assert A.__dict__['x'].__get__(a) == 1
675 del a.x
676 raises(AttributeError, getattr, a, 'x')
677 raises(AttributeError, delattr, a, 'x')
678 class B(A):
679 pass
680 b = B()
681 raises(AttributeError, getattr, b, 'x')
682 raises(AttributeError, delattr, b, 'x')
683 b.x = 1
684 assert b.x == 1
685 assert A.__dict__['x'].__get__(b) == 1
686 del b.x
687 raises(AttributeError, getattr, b, 'x')
688 raises(AttributeError, delattr, b, 'x')
689 class Z(object):
690 pass
691 z = Z()
692 raises(TypeError, A.__dict__['x'].__get__, z)
693 raises(TypeError, A.__dict__['x'].__set__, z, 1)
694 raises(TypeError, A.__dict__['x'].__delete__, z)
695
696 def test_slot_mangling(self):
697 class A(object):
698 __slots__ = ('x', '__x','__xxx__','__','__dict__')
699 a = A()
700 assert '__dict__' in A.__dict__
701 assert '__' in A.__dict__
702 assert '__xxx__' in A.__dict__
703 assert 'x' in A.__dict__
704 assert '_A__x' in A.__dict__
705 a.x = 1
706 a._A__x = 2
707 a.__xxx__ = 3
708 a.__ = 4
709 assert a.x == 1
710 assert a._A__x == 2
711 assert a.__xxx__ == 3
712 assert a.__ == 4
713 assert a.__dict__ == {}
714
715 def test_slots_multiple_inheritance(self):
716 class A(object):
717 __slots__ = ['a']
718 class B(A):
719 __slots__ = []
720 class E(A):
721 __slots__ = ['e']
722 class C(B, E):
723 pass
724 c = C()
725 c.a = 42
726 c.e = 85
727 assert c.a == 42
728 assert c.e == 85
729
730 def test_string_slots(self):
731 class A(object):
732 __slots__ = "abc"
733
734 class B(object):
735 __slots__ = "abc"
736
737 a = A()
738 a.abc = "awesome"
739 assert a.abc == "awesome"
740 b = B()
741 b.abc = "awesomer"
742 assert b.abc == "awesomer"
743
744 def test_bad_slots(self):
745 raises(TypeError, type, 'A', (), {'__slots__': b'x'})
746 raises(TypeError, type, 'A', (), {'__slots__': 42})
747 raises(TypeError, type, 'A', (), {'__slots__': '2_x'})
748
749 def test_base_attr(self):
750 # check the '__base__'
751 class A(object):
752 __slots__ = ['a']
753 class B(A):
754 __slots__ = []
755 class E(A):
756 __slots__ = ['e']
757 class C(B, E):
758 pass
759 class D(A):
760 __slots__ = []
761 class F(B, D):
762 pass
763 assert C.__base__ is E
764 assert F.__base__ is B
765 assert bool.__base__ is int
766 assert int.__base__ is object
767 assert object.__base__ is None
768
769 def test_cannot_subclass(self):
770 raises(TypeError, type, 'A', (bool,), {})
771
772 def test_slot_conflict(self):
773 class A(object):
774 __slots__ = ['a']
775 class B(A):
776 __slots__ = ['b']
777 class E(A):
778 __slots__ = ['e']
779 raises(TypeError, type, 'C', (B, E), {})
780
781 def test_repr(self):
782 globals()['__name__'] = 'a'
783 class A(object):
784 pass
785 assert repr(A) == "<class 'a.test_repr.<locals>.A'>"
786 A.__module__ = 123
787 assert repr(A) == "<class 'A'>"
788 assert repr(type(type)) == "<class 'type'>"
789 assert repr(complex) == "<class 'complex'>"
790 assert repr(property) == "<class 'property'>"
791 assert repr(TypeError) == "<class 'TypeError'>"
792
793 def test_repr_issue1292(self):
794 d = {'object': object} # no __name__
795 exec("class A(object): pass\n", d)
796 assert d['A'].__module__ == 'builtins' # obscure, follows CPython
797 assert repr(d['A']) == "<class 'A'>"
798
799 def test_repr_nonascii(self):
800 assert repr(type('日本', (), {})) == "<class '%s.日本'>" % __name__
801
802 def test_name_nonascii(self):
803 assert type('日本', (), {}).__name__ == '日本'
804
805 def test_errors_nonascii(self):
806 # Check some arbitrary error messages
807 Japan = type('日本', (), {})
808 obj = Japan()
809 for f in hex, int, len, next, open, set, 'foo'.startswith:
810 try:
811 f(obj)
812 except TypeError as e:
813 assert '日本' in str(e)
814 else:
815 assert False, 'Expected TypeError'
816
817 def test_invalid_mro(self):
818 class A(object):
819 pass
820 raises(TypeError, "class B(A, A): pass")
821 class C(A):
822 pass
823 raises(TypeError, "class D(A, C): pass")
824
825 def test_dir(self):
826 class A(object):
827 a_var = None
828 def a_meth(self):
829 pass
830
831 class C(A):
832 c_var = None
833 def c_meth(self):
834 pass
835
836 C_items = dir(C)
837 assert C_items != C.__dir__(C) # as in cpython
838
839 assert 'a_var' in C_items
840 assert 'c_var' in C_items
841 assert 'a_meth' in C_items
842 assert 'c_meth' in C_items
843
844 def test_data_descriptor_without_get(self):
845 """
846 class Descr(object):
847 def __init__(self, name):
848 self.name = name
849 def __set__(self, obj, what):
850 pass
851 class Meta(type):
852 pass
853 class X(object, metaclass=Meta):
854 pass
855 X.a = 42
856 Meta.a = Descr("a")
857 assert X.a == 42
858 """
859
860 def test_user_defined_mro_cls_access(self):
861 """
862 d = []
863 class T(type):
864 def mro(cls):
865 d.append(cls.__dict__)
866 return type.mro(cls)
867 class C(metaclass=T):
868 pass
869 assert d
870 assert sorted(d[0].keys()) == ['__dict__', '__doc__', '__module__', '__weakref__']
871 d = []
872 class T(type):
873 def mro(cls):
874 try:
875 cls.x()
876 except AttributeError:
877 d.append('miss')
878 return type.mro(cls)
879 class C(metaclass=T):
880 def x(cls):
881 return 1
882 x = classmethod(x)
883 assert d == ['miss']
884 assert C.x() == 1
885 """
886
887 def test_set___class__(self):
888 raises(TypeError, "1 .__class__ = int")
889 raises(TypeError, "1 .__class__ = bool")
890 class A(object):
891 pass
892 class B(object):
893 pass
894 a = A()
895 a.__class__ = B
896 assert a.__class__ == B
897 class A(object):
898 __slots__ = ('a',)
899 class B(A):
900 pass
901 class C(B):
902 pass
903 class D(A):
904 pass
905 d = D()
906 d.__class__ = C
907 assert d.__class__ == C
908 d.__class__ = B
909 assert d.__class__ == B
910 raises(TypeError, "d.__class__ = A")
911 d.__class__ = C
912 assert d.__class__ == C
913 d.__class__ = D
914 assert d.__class__ == D
915 class AA(object):
916 __slots__ = ('a',)
917 aa = AA()
918 aa.__class__ = A
919 raises(TypeError, "aa.__class__ = object")
920 class Z1(A):
921 pass
922 class Z2(A):
923 __slots__ = ['__dict__', '__weakref__']
924 z1 = Z1()
925 z1.__class__ = Z2
926 assert z1.__class__ == Z2
927 z2 = Z2()
928 z2.__class__ = Z1
929 assert z2.__class__ == Z1
930
931 class I(int):
932 pass
933 class F(float):
934 pass
935 f = F()
936 raises(TypeError, "f.__class__ = I")
937 i = I()
938 raises(TypeError, "i.__class__ = F")
939 raises(TypeError, "i.__class__ = int")
940
941 class I2(int):
942 pass
943 class I3(I2):
944 __slots__ = ['a']
945 class I4(I3):
946 pass
947
948 i = I()
949 i2 = I()
950 i.__class__ = I2
951 i2.__class__ = I
952 assert i.__class__ == I2
953 assert i2.__class__ == I
954
955 i3 = I3()
956 raises(TypeError, "i3.__class__ = I2")
957 i3.__class__ = I4
958 assert i3.__class__ == I4
959 i3.__class__ = I3
960 assert i3.__class__ == I3
961
962 class X(object):
963 pass
964 class Y(object):
965 __slots__ = ()
966 raises(TypeError, "X().__class__ = Y")
967 raises(TypeError, "Y().__class__ = X")
968
969 raises(TypeError, "X().__class__ = object")
970 raises(TypeError, "X().__class__ = 1")
971
972 class Int(int): __slots__ = []
973
974 raises(TypeError, "Int().__class__ = int")
975
976 class Order1(object):
977 __slots__ = ['a', 'b']
978 class Order2(object):
979 __slots__ = ['b', 'a']
980 Order1().__class__ = Order2
981
982 # like CPython, the order of slot names doesn't matter
983 x = Order1()
984 x.a, x.b = 1, 2
985 x.__class__ = Order2
986 assert (x.a, x.b) == (1, 2)
987
988 class U1(object):
989 __slots__ = ['a', 'b']
990 class U2(U1):
991 __slots__ = ['c', 'd', 'e']
992 class V1(object):
993 __slots__ = ['a', 'b']
994 class V2(V1):
995 __slots__ = ['c', 'd', 'e']
996 # the following line does not work on CPython either: we can't
997 # change a class if the old and new class have different layouts
998 # that look compatible but aren't, because they don't have the
999 # same base-layout class (even if these base classes are
1000 # themselves compatible)... obscure.
1001 raises(TypeError, "U2().__class__ = V2")
1002
1003 def test_name(self):
1004 class Abc(object):
1005 pass
1006 assert Abc.__name__ == 'Abc'
1007 Abc.__name__ = 'Def'
1008 assert Abc.__name__ == 'Def'
1009 raises(TypeError, "Abc.__name__ = 42")
1010 raises(TypeError, "Abc.__name__ = b'A'")
1011 raises(UnicodeEncodeError, "Abc.__name__ = 'A\udcdcB'")
1012 for v, err in [('G\x00hi', "type name must not contain null characters"),
1013 ]:
1014 try:
1015 Abc.__name__ = v
1016 except ValueError as e:
1017 assert err in str(e)
1018 else:
1019 assert False
1020 assert Abc.__name__ == 'Def'
1021
1022 def test_qualname(self):
1023 A = type('A', (), {'__qualname__': 'B.C'})
1024 assert A.__name__ == 'A'
1025 assert A.__qualname__ == 'B.C'
1026 raises(TypeError, type, 'A', (), {'__qualname__': b'B'})
1027 assert A.__qualname__ == 'B.C'
1028
1029 A.__qualname__ = 'D.E'
1030 assert A.__name__ == 'A'
1031 assert A.__qualname__ == 'D.E'
1032
1033 C = type('C', (), {})
1034 C.__name__ = 'A'
1035 assert C.__name__ == 'A'
1036 assert C.__qualname__ == 'C'
1037
1038 e = raises(TypeError, type, 'D', (), {'__qualname__': 42})
1039 assert str(e.value) == "type __qualname__ must be a str, not int"
1040
1041 for v in (42, b'abc'):
1042 try:
1043 C.__qualname__ = v
1044 except TypeError as e:
1045 assert 'can only assign string' in str(e)
1046 else:
1047 assert False
1048
1049 def test_qualname_and_slots(self):
1050 class A:
1051 __slots__ = ['__qualname__', 'b']
1052 assert isinstance(A.__qualname__, str)
1053 assert isinstance(A.__dict__['__qualname__'], type(A.b))
1054 a = A()
1055 a.__qualname__ = 1
1056 assert a.__qualname__ == 1
1057
1058 def test_compare(self):
1059 class A(object):
1060 pass
1061 class B(A):
1062 pass
1063 assert A == A
1064 assert A != B
1065 assert not A == B
1066 assert not A != A
1067
1068 def test_compare_overridden(self):
1069 """
1070 class AMeta(type):
1071 def __eq__(self, other):
1072 return True
1073
1074 class A(metaclass=AMeta):
1075 pass
1076
1077 assert (A == 1) == True
1078 assert (1 == A) == True
1079
1080 assert (A != 1) == False
1081 assert (1 != A) == False
1082 """
1083
1084
1085 def test_class_variations(self):
1086 class A(object):
1087 pass
1088 assert '__dict__' in A.__dict__
1089 a = A()
1090 a.x = 3
1091 assert a.x == 3
1092
1093 class A(object):
1094 __slots__ = ()
1095 assert '__dict__' not in A.__dict__
1096 a = A()
1097 raises(AttributeError, setattr, a, 'x', 3)
1098
1099 class B(A):
1100 pass
1101 assert '__dict__' in B.__dict__
1102 b = B()
1103 b.x = 3
1104 assert b.x == 3
1105
1106 import sys
1107 class A(type(sys)):
1108 pass
1109 assert '__dict__' not in A.__dict__
1110 a = A("a")
1111 a.x = 3
1112 assert a.x == 3
1113
1114 class A(type(sys)):
1115 __slots__ = ()
1116 assert '__dict__' not in A.__dict__
1117 a = A("a")
1118 a.x = 3
1119 assert a.x == 3
1120
1121 class B(A):
1122 pass
1123 assert '__dict__' not in B.__dict__
1124 b = B("b")
1125 b.x = 3
1126 assert b.x == 3
1127
1128 def test_module(self):
1129 def f(): pass
1130 assert object.__module__ == 'builtins'
1131 assert int.__module__ == 'builtins'
1132 assert type.__module__ == 'builtins'
1133 assert type(f).__module__ == 'builtins'
1134 d = {'__name__': 'yay'}
1135 exec("""class A(object):\n pass\n""", d)
1136 A = d['A']
1137 assert A.__module__ == 'yay'
1138
1139 def test_immutable_builtin(self):
1140 raises(TypeError, setattr, list, 'append', 42)
1141 raises(TypeError, setattr, list, 'foobar', 42)
1142 raises(TypeError, delattr, dict, 'keys')
1143 raises(TypeError, 'int.__dict__["a"] = 1')
1144
1145 def test_nontype_in_mro(self):
1146 class OldStyle:
1147 pass
1148 class X(object):
1149 pass
1150
1151 class mymeta1(type):
1152 def mro(self):
1153 return [self, OldStyle, object]
1154 mymeta1("Foo1", (object,), {}) # works
1155
1156 class mymeta2(type):
1157 def mro(self):
1158 return [self, X(), object]
1159 raises(TypeError, mymeta2, "Foo", (object,), {})
1160
1161 def test_init_must_return_none(self):
1162 class X(object):
1163 def __init__(self):
1164 return 0
1165 raises(TypeError, X)
1166
1167 def test_dictproxy_is_updated(self):
1168 class A(object):
1169 x = 1
1170 d = A.__dict__
1171 assert d["x"] == 1
1172 A.y = 2
1173 assert d["y"] == 2
1174 assert ("x", 1) in d.items()
1175 assert ("y", 2) in d.items()
1176
1177 def test_type_descriptors_overridden(self):
1178 class A(object):
1179 __dict__ = 42
1180 assert A().__dict__ == 42
1181 #
1182 class B(object):
1183 __weakref__ = 42
1184 assert B().__weakref__ == 42
1185
1186 def test_change_dict(self):
1187 class A(object):
1188 pass
1189
1190 a = A()
1191 A.x = 1
1192 assert A.__dict__["x"] == 1
1193 raises(AttributeError, "del A.__dict__")
1194 raises((AttributeError, TypeError), "A.__dict__ = {}")
1195
1196 def test_mutate_dict(self):
1197 class A(object):
1198 pass
1199
1200 a = A()
1201 d = A.__dict__
1202 A.x = 1
1203 assert d["x"] == 1
1204
1205 def test_we_already_got_one_1(self):
1206 # Issue #2079: highly obscure: CPython complains if we say
1207 # ``__slots__="__dict__"`` and there is already a __dict__...
1208 # but from the "best base" only. If the __dict__ comes from
1209 # another base, it doesn't complain. Shrug and copy the logic.
1210 class A(object):
1211 __slots__ = ()
1212 class B(object):
1213 pass
1214 class C(A, B): # "best base" is A
1215 __slots__ = ("__dict__",)
1216 class D(A, B): # "best base" is A
1217 __slots__ = ("__weakref__",)
1218 try:
1219 class E(B, A): # "best base" is B
1220 __slots__ = ("__dict__",)
1221 except TypeError as e:
1222 assert 'we already got one' in str(e)
1223 else:
1224 raise AssertionError("TypeError not raised")
1225 try:
1226 class F(B, A): # "best base" is B
1227 __slots__ = ("__weakref__",)
1228 except TypeError as e:
1229 assert 'we already got one' in str(e)
1230 else:
1231 raise AssertionError("TypeError not raised")
1232
1233 def test_we_already_got_one_2(self):
1234 class A(object):
1235 __slots__ = ()
1236 class B(object):
1237 pass
1238 class C(A, B): # "best base" is A
1239 __slots__ = ("__dict__",)
1240 class D(A, B): # "best base" is A
1241 __slots__ = ("__weakref__",)
1242
1243 def test_slot_shadows_class_variable(self):
1244 try:
1245 class X:
1246 __slots__ = ["foo"]
1247 foo = None
1248 except ValueError as e:
1249 assert str(e) == "'foo' in __slots__ conflicts with class variable"
1250 else:
1251 assert False, "ValueError expected"
1252
1253 def test_metaclass_calc(self):
1254 """
1255 # issue1294232: correct metaclass calculation
1256 new_calls = [] # to check the order of __new__ calls
1257 class AMeta(type):
1258 @staticmethod
1259 def __new__(mcls, name, bases, ns):
1260 new_calls.append('AMeta')
1261 return super().__new__(mcls, name, bases, ns)
1262 @classmethod
1263 def __prepare__(mcls, name, bases):
1264 return {}
1265
1266 class BMeta(AMeta):
1267 @staticmethod
1268 def __new__(mcls, name, bases, ns):
1269 new_calls.append('BMeta')
1270 return super().__new__(mcls, name, bases, ns)
1271 @classmethod
1272 def __prepare__(mcls, name, bases):
1273 ns = super().__prepare__(name, bases)
1274 ns['BMeta_was_here'] = True
1275 return ns
1276
1277 class A(metaclass=AMeta):
1278 pass
1279 assert ['AMeta'] == new_calls
1280 new_calls[:] = []
1281
1282 class B(metaclass=BMeta):
1283 pass
1284 # BMeta.__new__ calls AMeta.__new__ with super:
1285 assert ['BMeta', 'AMeta'] == new_calls
1286 new_calls[:] = []
1287
1288 class C(A, B):
1289 pass
1290 # The most derived metaclass is BMeta:
1291 assert ['BMeta', 'AMeta'] == new_calls
1292 new_calls[:] = []
1293 # BMeta.__prepare__ should've been called:
1294 assert 'BMeta_was_here' in C.__dict__
1295
1296 # The order of the bases shouldn't matter:
1297 class C2(B, A):
1298 pass
1299 assert ['BMeta', 'AMeta'] == new_calls
1300 new_calls[:] = []
1301 assert 'BMeta_was_here' in C2.__dict__
1302
1303 # Check correct metaclass calculation when a metaclass is declared:
1304 class D(C, metaclass=type):
1305 pass
1306 assert ['BMeta', 'AMeta'] == new_calls
1307 new_calls[:] = []
1308 assert 'BMeta_was_here' in D.__dict__
1309
1310 class E(C, metaclass=AMeta):
1311 pass
1312 assert ['BMeta', 'AMeta'] == new_calls
1313 new_calls[:] = []
1314 assert 'BMeta_was_here' in E.__dict__
1315
1316 # Special case: the given metaclass isn't a class,
1317 # so there is no metaclass calculation.
1318 marker = object()
1319 def func(*args, **kwargs):
1320 return marker
1321 class X(metaclass=func):
1322 pass
1323 class Y(object, metaclass=func):
1324 pass
1325 class Z(D, metaclass=func):
1326 pass
1327 assert marker is X
1328 assert marker is Y
1329 assert marker is Z
1330 """
1331
1332 def test_prepare(self):
1333 """
1334 classdict = type.__prepare__()
1335 assert type(classdict) is dict
1336 assert classdict == {}
1337 assert type.__prepare__(3) == {}
1338 assert type.__prepare__(3, 4) == {}
1339 assert type.__prepare__(3, package='sqlalchemy') == {}
1340 class M(type):
1341 @classmethod
1342 def __prepare__(cls, *args, **kwds):
1343 d = super().__prepare__(*args, **kwds)
1344 d['hello'] = 42
1345 return d
1346 class C(metaclass=M):
1347 foo = hello
1348 assert C.foo == 42
1349 """
1350
1351 def test_prepare_error(self):
1352 """
1353 class BadMeta:
1354 @classmethod
1355 def __prepare__(cls, *args, **kwargs):
1356 return 42
1357 def make_class(meta):
1358 class Foo(metaclass=meta):
1359 pass
1360 excinfo = raises(TypeError, make_class, BadMeta)
1361 print(excinfo.value.args[0])
1362 assert excinfo.value.args[0].startswith('BadMeta.__prepare__')
1363 # Non-type as metaclass
1364 excinfo = raises(TypeError, make_class, BadMeta())
1365 assert excinfo.value.args[0].startswith('<metaclass>.__prepare__')
1366 """
1367
1368 def test_crash_mro_without_object_1(self):
1369 """
1370 class X(type):
1371 def mro(self):
1372 return [self]
1373 class C(metaclass=X):
1374 pass
1375 e = raises(TypeError, C) # the lookup of '__new__' fails
1376 assert str(e.value) == "cannot create 'C' instances"
1377 """
1378
1379 def test_crash_mro_without_object_2(self):
1380 """
1381 class X(type):
1382 def mro(self):
1383 return [self, int]
1384 class C(int, metaclass=X):
1385 pass
1386 C() # the lookup of '__new__' succeeds in 'int',
1387 # but the lookup of '__init__' fails
1388 """
1389
1390 def test_instancecheck(self):
1391 assert int.__instancecheck__(42) is True
1392 assert int.__instancecheck__(42.0) is False
1393 class Bar(object):
1394 __class__ = int
1395 assert int.__instancecheck__(Bar()) is True
1396
1397 def test_subclasscheck(self):
1398 assert int.__subclasscheck__(bool) is True
1399 assert int.__subclasscheck__(float) is False
1400 class Bar(object):
1401 __class__ = int
1402 assert int.__subclasscheck__(Bar) is False
1403 class AbstractClass(object):
1404 __bases__ = (int,)
1405 assert int.__subclasscheck__(AbstractClass()) is True
1406
1407 def test_bad_args(self):
1408 import collections
1409 raises(TypeError, type, 'A', (), dict={})
1410 raises(TypeError, type, 'A', [], {})
1411 raises(TypeError, type, 'A', (), collections.UserDict())
1412 raises(ValueError, type, 'A\x00B', (), {})
1413 raises(TypeError, type, b'A', (), {})
1414
1415 def test_incomplete_extend(self): """
1416 # Extending an unitialized type with type.__mro__ is None must
1417 # throw a reasonable TypeError exception, instead of failing
1418 # with a segfault.
1419 class M(type):
1420 def mro(cls):
1421 if cls.__mro__ is None and cls.__name__ != 'X':
1422 try:
1423 class X(cls):
1424 pass
1425 except TypeError:
1426 found.append(1)
1427 return type.mro(cls)
1428 found = []
1429 class A(metaclass=M):
1430 pass
1431 assert found == [1]
1432 """
1433
1434 def test_incomplete_extend_2(self): """
1435 # Same as test_incomplete_extend, with multiple inheritance
1436 class M(type):
1437 def mro(cls):
1438 if cls.__mro__ is None and cls.__name__ == 'Second':
1439 try:
1440 class X(First, cls):
1441 pass
1442 except TypeError:
1443 found.append(1)
1444 return type.mro(cls)
1445 found = []
1446 class Base(metaclass=M):
1447 pass
1448 class First(Base):
1449 pass
1450 class Second(Base):
1451 pass
1452 assert found == [1]
1453 """
1454
1455 def test_incomplete_extend_3(self): """
1456 # this case "works", but gives a slightly strange error message
1457 # on both CPython and PyPy
1458 class M(type):
1459 def mro(cls):
1460 if cls.__mro__ is None and cls.__name__ == 'A':
1461 try:
1462 Base.__new__(cls)
1463 except TypeError:
1464 found.append(1)
1465 return type.mro(cls)
1466 found = []
1467 class Base(metaclass=M):
1468 pass
1469 class A(Base):
1470 pass
1471 assert found == [1]
1472 """
1473
1474 def test_class_getitem(self):
1475 """
1476 class WithoutMetaclass:
1477 def __getitem__(self, index):
1478 return index + 1
1479 def __class_getitem__(cls, item):
1480 return "{}[{}]".format(cls.__name__, item.__name__)
1481
1482 class WithoutMetaclassSubclass(WithoutMetaclass):
1483 def __getitem__(self, index):
1484 return index + 1
1485 def __class_getitem__(cls, item):
1486 return super().__class_getitem__(item)
1487
1488 assert WithoutMetaclass()[0] == 1
1489 assert WithoutMetaclass[int] == "WithoutMetaclass[int]"
1490 assert WithoutMetaclassSubclass()[0] == 1
1491 assert WithoutMetaclassSubclass[int] == "WithoutMetaclassSubclass[int]"
1492
1493 class Metaclass(type):
1494 def __getitem__(self, item):
1495 return "Metaclass[{}]".format(item.__name__)
1496
1497 class WithMetaclass(metaclass=Metaclass):
1498 def __getitem__(self, index):
1499 return index + 1
1500 def __class_getitem__(cls, item):
1501 return super().__class_getitem__(item)
1502
1503 assert WithMetaclass()[0] == 1
1504 assert WithMetaclass[int] == "Metaclass[int]"
1505 """
1506
1507 def test_class_getitem_None(self):
1508 class DontWantToBeGeneric(tuple):
1509 __class_getitem__ = None
1510 with raises(TypeError) as info:
1511 DontWantToBeGeneric[int]
1512 assert "DontWantToBeGeneric" in str(info.value)
1513
1514 def test_mro_entries(self):
1515 """
1516 class BaseA: pass
1517 class BaseB: pass
1518 class BaseC: pass
1519 class BaseD: pass
1520
1521 class ProxyA:
1522 def __mro_entries__(self, orig_bases):
1523 return (BaseA,)
1524 class ProxyAB:
1525 def __mro_entries__(self, orig_bases):
1526 return (BaseA, BaseB)
1527 class ProxyNone:
1528 def __mro_entries__(self, orig_bases):
1529 return ()
1530
1531 class TestA(ProxyA()): pass
1532 assert TestA.__bases__ == (BaseA,)
1533 assert len(TestA.__orig_bases__) == 1
1534 assert isinstance(TestA.__orig_bases__[0], ProxyA)
1535
1536 class TestAB(ProxyAB()): pass
1537 assert TestAB.__bases__ == (BaseA, BaseB)
1538 assert len(TestAB.__orig_bases__) == 1
1539 assert isinstance(TestAB.__orig_bases__[0], ProxyAB)
1540
1541 class TestNone(ProxyNone()): pass
1542 assert TestNone.__bases__ == (object,)
1543 assert len(TestNone.__orig_bases__) == 1
1544 assert isinstance(TestNone.__orig_bases__[0], ProxyNone)
1545
1546 class TestMixed(BaseC, ProxyAB(), BaseD, ProxyNone()): pass
1547 assert TestMixed.__bases__ == (BaseC, BaseA, BaseB, BaseD)
1548 assert len(TestMixed.__orig_bases__) == 4
1549 assert isinstance(TestMixed.__orig_bases__[1], ProxyAB) and isinstance(TestMixed.__orig_bases__[3], ProxyNone)
1550
1551 with raises(TypeError) as excinfo:
1552 class TestDuplicate(BaseB, ProxyAB()): pass
1553 assert str(excinfo.value) == "duplicate base class 'BaseB'"
1554
1555 with raises(TypeError) as excinfo:
1556 type('TestType', (BaseC, ProxyAB(), BaseD, ProxyNone()), {})
1557 assert str(excinfo.value) == "type() doesn't support MRO entry resolution; use types.new_class()"
1558
1559 import types
1560 TestTypesNewClass = types.new_class('TestTypesNewClass', (BaseC, ProxyAB(), BaseD, ProxyNone()), {})
1561 assert TestMixed.__bases__ == (BaseC, BaseA, BaseB, BaseD)
1562 assert len(TestMixed.__orig_bases__) == 4
1563 assert isinstance(TestMixed.__orig_bases__[1], ProxyAB) and isinstance(TestMixed.__orig_bases__[3], ProxyNone)
1564
1565 class TestNoOrigBases(BaseA, BaseB): pass
1566 assert TestNoOrigBases.__bases__ == (BaseA, BaseB)
1567 assert not hasattr(TestNoOrigBases, '__orig_bases__')
1568 """
1569
1570 def test_mro_entries_bug(self):
1571 class A:
1572 pass
1573
1574 def f(): pass
1575 f.__mro_entries__ = lambda bases: (A, )
1576 class BuggyMcBugFace(f):
1577 pass
1578 assert BuggyMcBugFace.__base__ is A
1579
1580 def test_mro_entries_type_ignored(self):
1581 class A:
1582 def __mro_entries__(self, bases):
1583 assert 0
1584 class B(A):
1585 pass
1586 assert B.__base__ is A
1587
1588 def test_classcell_missing(self):
1589 """
1590 # Some metaclasses may not pass the original namespace to type.__new__
1591 # We test that case here by forcibly deleting __classcell__
1592 class Meta(type):
1593 def __new__(cls, name, bases, namespace):
1594 namespace.pop('__classcell__', None)
1595 return super().__new__(cls, name, bases, namespace)
1596
1597 # The default case should continue to work without any errors
1598 class WithoutClassRef(metaclass=Meta):
1599 pass
1600
1601 # With zero-arg super() or an explicit __class__ reference, we expect
1602 # __build_class__ to raise a RuntimeError complaining that
1603 # __class__ was not set, and asking if __classcell__ was propagated
1604 # to type.__new__.
1605 with raises(RuntimeError):
1606 class WithClassRef(metaclass=Meta):
1607 def f(self):
1608 return __class__
1609 """
1610
1611 def test_class_getitem(self):
1612 ga = type[int]
1613 assert ga.__origin__ is type
1614 assert ga.__args__ == (int, )
1615
1616 def test_or_types_operator(self):
1617 """
1618 class Example:
1619 pass
1620
1621 assert (int | str)
1622 assert (int | int | str) == int | str
1623 assert (int | list) != int | str
1624 assert (str | int) == int | str
1625 assert (int | None)
1626 assert (None | int) == int | None
1627 assert (int | str | list)
1628 assert (int | (str | list)) == (int | str) | list
1629 assert (list[int] | str)
1630 assert (str | list[int]) == list[int] | str
1631 assert (str | float | int | complex | int) == ((int | str) | (float | complex))
1632 assert (int | int) == int
1633
1634 with raises(TypeError):
1635 int | 3
1636
1637 with raises(TypeError):
1638 3 | int
1639
1640 with raises(TypeError):
1641 Example() | int
1642
1643 with raises(TypeError):
1644 (int | str) < (int | bool)
1645
1646 with raises(TypeError):
1647 (int | str) <= (int | str)
1648 """
1649
1650 def test_or_type_repr(self):
1651 """
1652 assert repr(int | None) == "int | None"
1653 assert repr(None | int) == "None | int"
1654 assert repr(int | list[int]) == "int | list[int]"
1655 assert repr(int | str | list[int]) == "int | str | list[int]"
1656 assert repr(int | str | int) == "int | str"
1657 """
1658
1659 def test_metaclass_new_args_when_calling_type(self):
1660 """
1661 class T1(type):
1662 def __new__(metacls, cls, bases, body, extraarg=False):
1663 assert metacls is T1
1664 assert extraarg
1665 return super().__new__(metacls, cls, bases, body)
1666
1667 class D1(metaclass=T1, extraarg=True):
1668 pass
1669
1670 type('D2', (D1, ), {}, extraarg=True)
1671 """
1672
1673 class AppTestWithMethodCacheCounter:
1674 spaceconfig = {"objspace.std.withmethodcachecounter": True}
1675
1676 def test_module_from_handbuilt_type(self):
1677 d = {'tuple': tuple, '__name__': 'foomod'}
1678 exec("""class foo(tuple): pass""", d)
1679 t = d['foo']
1680 t.__module__ = 'barmod'
1681 # this last line used to crash; see ab926f846f39
1682 assert t.__module__
1683
1684
1685 class AppTestGetattributeShortcut:
1686
1687 def test_reset_logic(self):
1688 """
1689 class X(object):
1690 pass
1691
1692 class Y(X):
1693 pass
1694
1695 y = Y()
1696 y.x = 3
1697 assert y.x == 3
1698
1699 def ga(self, name):
1700 return 'GA'
1701
1702 X.__getattribute__ = ga
1703
1704 assert y.x == 'GA'
1705
1706 class M(type):
1707 pass
1708
1709 class X(metaclass=M):
1710 pass
1711
1712 class Y(X):
1713 pass
1714
1715 y = Y()
1716 y.x = 3
1717 assert y.x == 3
1718
1719 def ga2(self, name):
1720 return 'GA2'
1721
1722 X.__getattribute__ = ga2
1723
1724 assert y.x == 'GA2'
1725 """
1726
1727 class TestNewShortcut:
1728 spaceconfig = {"objspace.std.newshortcut": True}
1729
1730 def test_mechanics(self):
1731 space = self.space
1732 w_tup = space.appexec([], """():
1733 class A(object):
1734 pass
1735 class B(object):
1736 __new__ = staticmethod(lambda t: 1)
1737 class M(type):
1738 pass
1739 return A, B, M
1740 """)
1741 w_A, w_B, w_M = space.unpackiterable(w_tup)
1742
1743 assert w_A.w_new_function is None
1744 assert w_B.w_new_function is None
1745 assert w_M.w_new_function is None
1746
1747 _, w_object_newdescr = space.lookup_in_type_where(space.w_object,
1748 '__new__')
1749 w_object___new__ = space.get(w_object_newdescr, None,
1750 w_type=space.w_object)
1751
1752 w_a = space.call_function(w_A)
1753 assert w_A.w_new_function is w_object___new__
1754
1755 # will shortcut
1756 w_a = space.call_function(w_A)
1757
1758 w_b = space.call_function(w_B)
1759 assert w_B.w_new_function is not None
1760 w_b = space.call_function(w_B)
1761
1762 w_m = space.call_function(w_M, space.wrap('C'), space.newtuple([]),
1763 space.newdict())
1764 assert w_M.w_new_function is not None
1765
1766
1767 class AppTestNewShortcut:
1768 spaceconfig = {"objspace.std.newshortcut": True}
1769
1770 def test_reset_logic(self):
1771 class X(object):
1772 pass
1773
1774 class Y(X):
1775 pass
1776
1777 y = Y()
1778
1779 assert isinstance(y, Y)
1780
1781
1782 X.__new__ = staticmethod(lambda t: 1)
1783
1784 y = Y()
1785
1786 assert y == 1
1787
1788 def test_dont_explode_on_non_types(self):
1789 class A:
1790 __new__ = staticmethod(lambda t: 1)
1791
1792 class B(A, object):
1793 pass
1794
1795 b = B()
1796
1797 assert b == 1
1798
1799 def test_eq_returns_notimplemented(self):
1800 assert type.__eq__(int, 42) is NotImplemented
1801 assert type.__ne__(dict, 42) is NotImplemented
1802 assert type.__eq__(int, int) == True
1803 assert type.__eq__(int, dict) is NotImplemented
1804
1805
1806 class AppTestComparesByIdentity:
1807
1808 def setup_class(cls):
1809 if cls.runappdirect:
1810 py.test.skip("interp2app doesn't work on appdirect")
1811
1812 def compares_by_identity(space, w_cls):
1813 return space.wrap(w_cls.compares_by_identity())
1814 cls.w_compares_by_identity = cls.space.wrap(interp2app(compares_by_identity))
1815
1816 def test_compares_by_identity(self):
1817 class Plain(object):
1818 pass
1819
1820 class CustomEq(object):
1821 def __eq__(self, other):
1822 return True
1823
1824 class CustomHash(object):
1825 def __hash__(self):
1826 return 0
1827
1828 class TypeSubclass(type):
1829 pass
1830
1831 assert self.compares_by_identity(Plain)
1832 assert not self.compares_by_identity(CustomEq)
1833 assert not self.compares_by_identity(CustomHash)
1834 assert self.compares_by_identity(type)
1835 assert self.compares_by_identity(TypeSubclass)
1836
1837 def test_modify_class(self):
1838 class X(object):
1839 pass
1840
1841 assert self.compares_by_identity(X)
1842 X.__eq__ = lambda x: None
1843 assert not self.compares_by_identity(X)
1844 del X.__eq__
1845 assert self.compares_by_identity(X)
1846
1847 def test_duplicate_slot_name(self):
1848 class X: # does not raise
1849 __slots__ = 'a', 'a'
1850
1851 def test_descriptor_objclass(self):
1852 class X(object):
1853 pass
1854 assert X.__dict__['__dict__'].__objclass__ is X
1855 assert X.__dict__['__weakref__'].__objclass__ is X
1856 assert object.__dict__['__class__'].__objclass__ is object
1857 assert int.__dict__['imag'].__objclass__ is int
1858 assert type.__dict__['__name__'].__objclass__ is type
1859 assert type.__dict__['__doc__'].__objclass__ is type
1860 #
1861 assert type.__dict__['__name__'].__name__ == '__name__'
1862 assert type.__dict__['__doc__'].__name__ == '__doc__'
1863
1864 def test_type_construct_unicode_surrogate_issue(self):
1865 raises(UnicodeEncodeError, type, 'A\udcdcb', (), {})
1866
1867 def test_set_name(self):
1868 class Descriptor:
1869 def __set_name__(self, owner, name):
1870 self.owner = owner
1871 self.name = name
1872
1873 class X:
1874 a = Descriptor()
1875 assert X.a.owner is X
1876 assert X.a.name == "a"
1877
1878 def test_set_name_error(self):
1879 class Descriptor:
1880 __set_name__ = None
1881 def make_class():
1882 class A:
1883 d = Descriptor()
1884 excinfo = raises(RuntimeError, make_class)
1885 assert isinstance(excinfo.value.__cause__, TypeError)
1886 assert str(excinfo.value) == "Error calling __set_name__ on 'Descriptor' instance 'd' in 'A'"
1887 print(excinfo.value)
1888
1889 def test_set_name_self(self):
1890 # issue 3326: modifying self.__dict__ in self.__set_name__
1891 class Descriptor:
1892 def __set_name__(self, owner, name):
1893 setattr(owner, "attr", self)
1894
1895 class Foo:
1896 desc = Descriptor()
1897 desc2 = Descriptor()
1898
1899
1900 pass # does not crash
1901
1902 def test_type_init_accepts_kwargs(self):
1903 type.__init__(type, "a", (object, ), {}, a=1)
1904
1905 def test_init_subclass_classmethod(self):
1906 assert isinstance(object.__dict__['__init_subclass__'], classmethod)
1907 class A(object):
1908 subclasses = []
1909
1910 def __init_subclass__(cls):
1911 cls.subclass.append(cls)
1912 assert isinstance(A.__dict__['__init_subclass__'], classmethod)
1913
1914 def test_init_subclass(self):
1915 class PluginBase(object):
1916 subclasses = []
1917
1918 def __init_subclass__(cls):
1919 cls.subclasses.append(cls)
1920
1921 class B(PluginBase):
1922 pass
1923
1924 class C(PluginBase):
1925 pass
1926
1927 assert PluginBase.subclasses == [B, C]
1928
1929
1930 class X(object):
1931 subclasses = []
1932
1933 def __init_subclass__(cls, **kwargs):
1934 cls.kwargs = kwargs
1935
1936 exec("""if 1:
1937 class Y(X, a=1, b=2):
1938 pass
1939
1940 assert Y.kwargs == dict(a=1, b=2)
1941 """)
1942
1943 def test_onearg_type_only_for_type(self):
1944 class Meta(type):
1945 pass
1946
1947 info = raises(TypeError, Meta, 5)
1948 assert "takes exactly 3 arguments (1 given)" in str(info.value)
1949 info = raises(TypeError, Meta, 5, 7)
1950 assert "takes exactly 3 arguments (1 given)" in str(info.value)
1951
1952 def test_hash_comparison_of_methods(self):
1953 def check_ordering(a, b):
1954 with raises(TypeError):
1955 a < b
1956 with raises(TypeError):
1957 a > b
1958 with raises(TypeError):
1959 a <= b
1960 with raises(TypeError):
1961 a >= b
1962
1963 class A:
1964 def __init__(self, x):
1965 self.x = x
1966 def f(self):
1967 pass
1968 def g(self):
1969 pass
1970 def __eq__(self, other):
1971 return True
1972 def __hash__(self):
1973 raise TypeError
1974
1975 class B(A):
1976 pass
1977
1978 a1 = A(1)
1979 a2 = A(1)
1980 assert a1.f == a1.f
1981 assert not a1.f != a1.f
1982 assert not a1.f == a2.f
1983 assert a1.f != a2.f
1984 assert not a1.f == a1.g
1985 assert a1.f != a1.g
1986 check_ordering(a1.f, a1.f)
1987 assert hash(a1.f) == hash(a1.f)
1988
1989 assert not A.f == a1.f
1990 assert A.f != a1.f
1991 assert not A.f == A.g
1992 assert A.f != A.g
1993 assert B.f == A.f
1994 assert not B.f != A.f
1995 check_ordering(A.f, A.f)
1996 assert hash(B.f) == hash(A.f)
1997
1998 # the following triggers a SystemError in 2.4
1999 a = A(hash(A.f)^(-1))
2000 hash(a.f)