11"Test the functionality of Python classes implementing operators."
22
33import unittest
4-
4+ from test . support import cpython_only , import_helper , script_helper
55
66testmeths = [
77
@@ -448,15 +448,15 @@ def __delattr__(self, *args):
448448 def testHasAttrString (self ):
449449 import sys
450450 from test .support import import_helper
451- _testcapi = import_helper .import_module ('_testcapi ' )
451+ _testlimitedcapi = import_helper .import_module ('_testlimitedcapi ' )
452452
453453 class A :
454454 def __init__ (self ):
455455 self .attr = 1
456456
457457 a = A ()
458- self .assertEqual (_testcapi .object_hasattrstring (a , b"attr" ), 1 )
459- self .assertEqual (_testcapi .object_hasattrstring (a , b"noattr" ), 0 )
458+ self .assertEqual (_testlimitedcapi .object_hasattrstring (a , b"attr" ), 1 )
459+ self .assertEqual (_testlimitedcapi .object_hasattrstring (a , b"noattr" ), 0 )
460460 self .assertIsNone (sys .exception ())
461461
462462 def testDel (self ):
@@ -503,6 +503,56 @@ def __eq__(self, other): return 1
503503
504504 self .assertRaises (TypeError , hash , C2 ())
505505
506+ def testPredefinedAttrs (self ):
507+ o = object ()
508+
509+ class Custom :
510+ pass
511+
512+ c = Custom ()
513+
514+ methods = (
515+ '__class__' , '__delattr__' , '__dir__' , '__eq__' , '__format__' ,
516+ '__ge__' , '__getattribute__' , '__getstate__' , '__gt__' , '__hash__' ,
517+ '__init__' , '__init_subclass__' , '__le__' , '__lt__' , '__ne__' ,
518+ '__new__' , '__reduce__' , '__reduce_ex__' , '__repr__' ,
519+ '__setattr__' , '__sizeof__' , '__str__' , '__subclasshook__'
520+ )
521+ for name in methods :
522+ with self .subTest (name ):
523+ self .assertTrue (callable (getattr (object , name , None )))
524+ self .assertTrue (callable (getattr (o , name , None )))
525+ self .assertTrue (callable (getattr (Custom , name , None )))
526+ self .assertTrue (callable (getattr (c , name , None )))
527+
528+ not_defined = [
529+ '__abs__' , '__aenter__' , '__aexit__' , '__aiter__' , '__anext__' ,
530+ '__await__' , '__bool__' , '__bytes__' , '__ceil__' ,
531+ '__complex__' , '__contains__' , '__del__' , '__delete__' ,
532+ '__delitem__' , '__divmod__' , '__enter__' , '__exit__' ,
533+ '__float__' , '__floor__' , '__get__' , '__getattr__' , '__getitem__' ,
534+ '__index__' , '__int__' , '__invert__' , '__iter__' , '__len__' ,
535+ '__length_hint__' , '__missing__' , '__neg__' , '__next__' ,
536+ '__objclass__' , '__pos__' , '__rdivmod__' , '__reversed__' ,
537+ '__round__' , '__set__' , '__setitem__' , '__trunc__'
538+ ]
539+ augment = (
540+ 'add' , 'and' , 'floordiv' , 'lshift' , 'matmul' , 'mod' , 'mul' , 'pow' ,
541+ 'rshift' , 'sub' , 'truediv' , 'xor'
542+ )
543+ not_defined .extend (map ("__{}__" .format , augment ))
544+ not_defined .extend (map ("__r{}__" .format , augment ))
545+ not_defined .extend (map ("__i{}__" .format , augment ))
546+ for name in not_defined :
547+ with self .subTest (name ):
548+ self .assertFalse (hasattr (object , name ))
549+ self .assertFalse (hasattr (o , name ))
550+ self .assertFalse (hasattr (Custom , name ))
551+ self .assertFalse (hasattr (c , name ))
552+
553+ # __call__() is defined on the metaclass but not the class
554+ self .assertFalse (hasattr (o , "__call__" ))
555+ self .assertFalse (hasattr (c , "__call__" ))
506556
507557 @unittest .skip ("TODO: RUSTPYTHON, segmentation fault" )
508558 def testSFBug532646 (self ):
@@ -647,6 +697,14 @@ class A:
647697 class B :
648698 y = 0
649699 __slots__ = ('z' ,)
700+ class C :
701+ __slots__ = ("y" ,)
702+
703+ def __setattr__ (self , name , value ) -> None :
704+ if name == "z" :
705+ super ().__setattr__ ("y" , 1 )
706+ else :
707+ super ().__setattr__ (name , value )
650708
651709 error_msg = "'A' object has no attribute 'x'"
652710 with self .assertRaisesRegex (AttributeError , error_msg ):
@@ -659,8 +717,16 @@ class B:
659717 B ().x
660718 with self .assertRaisesRegex (AttributeError , error_msg ):
661719 del B ().x
662- with self .assertRaisesRegex (AttributeError , error_msg ):
720+ with self .assertRaisesRegex (
721+ AttributeError ,
722+ "'B' object has no attribute 'x' and no __dict__ for setting new attributes"
723+ ):
663724 B ().x = 0
725+ with self .assertRaisesRegex (
726+ AttributeError ,
727+ "'C' object has no attribute 'x'"
728+ ):
729+ C ().x = 0
664730
665731 error_msg = "'B' object attribute 'y' is read-only"
666732 with self .assertRaisesRegex (AttributeError , error_msg ):
@@ -748,6 +814,192 @@ class A(0, 1, 2, 3, 4, 5, 6, 7, **d): pass
748814 class A (0 , * range (1 , 8 ), ** d , foo = 'bar' ): pass
749815 self .assertEqual (A , (tuple (range (8 )), {'foo' : 'bar' }))
750816
817+ def testClassCallRecursionLimit (self ):
818+ class C :
819+ def __init__ (self ):
820+ self .c = C ()
821+
822+ with self .assertRaises (RecursionError ):
823+ C ()
824+
825+ def add_one_level ():
826+ #Each call to C() consumes 2 levels, so offset by 1.
827+ C ()
828+
829+ with self .assertRaises (RecursionError ):
830+ add_one_level ()
831+
832+ def testMetaclassCallOptimization (self ):
833+ calls = 0
834+
835+ class TypeMetaclass (type ):
836+ def __call__ (cls , * args , ** kwargs ):
837+ nonlocal calls
838+ calls += 1
839+ return type .__call__ (cls , * args , ** kwargs )
840+
841+ class Type (metaclass = TypeMetaclass ):
842+ def __init__ (self , obj ):
843+ self ._obj = obj
844+
845+ for i in range (100 ):
846+ Type (i )
847+ self .assertEqual (calls , 100 )
751848
849+
850+ from _testinternalcapi import has_inline_values
851+
852+ Py_TPFLAGS_MANAGED_DICT = (1 << 2 )
853+
854+ class Plain :
855+ pass
856+
857+
858+ class WithAttrs :
859+
860+ def __init__ (self ):
861+ self .a = 1
862+ self .b = 2
863+ self .c = 3
864+ self .d = 4
865+
866+
867+ class TestInlineValues (unittest .TestCase ):
868+
869+ def test_flags (self ):
870+ self .assertEqual (Plain .__flags__ & Py_TPFLAGS_MANAGED_DICT , Py_TPFLAGS_MANAGED_DICT )
871+ self .assertEqual (WithAttrs .__flags__ & Py_TPFLAGS_MANAGED_DICT , Py_TPFLAGS_MANAGED_DICT )
872+ def test_has_inline_values (self ):
873+ c = Plain ()
874+ self .assertTrue (has_inline_values (c ))
875+ del c .__dict__
876+ self .assertFalse (has_inline_values (c ))
877+
878+ def test_instances (self ):
879+ self .assertTrue (has_inline_values (Plain ()))
880+ self .assertTrue (has_inline_values (WithAttrs ()))
881+ def test_inspect_dict (self ):
882+ for cls in (Plain , WithAttrs ):
883+ c = cls ()
884+ c .__dict__
885+ self .assertTrue (has_inline_values (c ))
886+ def test_update_dict (self ):
887+ d = { "e" : 5 , "f" : 6 }
888+ for cls in (Plain , WithAttrs ):
889+ c = cls ()
890+ c .__dict__ .update (d )
891+ self .assertTrue (has_inline_values (c ))
892+
893+ @staticmethod
894+ def set_100 (obj ):
895+ for i in range (100 ):
896+ setattr (obj , f"a{ i } " , i )
897+
898+ def check_100 (self , obj ):
899+ for i in range (100 ):
900+ self .assertEqual (getattr (obj , f"a{ i } " ), i )
901+ def test_many_attributes (self ):
902+ class C : pass
903+ c = C ()
904+ self .assertTrue (has_inline_values (c ))
905+ self .set_100 (c )
906+ self .assertFalse (has_inline_values (c ))
907+ self .check_100 (c )
908+ c = C ()
909+ self .assertTrue (has_inline_values (c ))
910+ def test_many_attributes_with_dict (self ):
911+ class C : pass
912+ c = C ()
913+ d = c .__dict__
914+ self .assertTrue (has_inline_values (c ))
915+ self .set_100 (c )
916+ self .assertFalse (has_inline_values (c ))
917+ self .check_100 (c )
918+
919+ def test_bug_117750 (self ):
920+ "Aborted on 3.13a6"
921+ class C :
922+ def __init__ (self ):
923+ self .__dict__ .clear ()
924+
925+ obj = C ()
926+ self .assertEqual (obj .__dict__ , {})
927+ obj .foo = None # Aborted here
928+ self .assertEqual (obj .__dict__ , {"foo" :None })
929+
930+ def test_store_attr_deleted_dict (self ):
931+ class Foo :
932+ pass
933+
934+ f = Foo ()
935+ del f .__dict__
936+ f .a = 3
937+ self .assertEqual (f .a , 3 )
938+
939+ def test_rematerialize_object_dict (self ):
940+ # gh-121860: rematerializing an object's managed dictionary after it
941+ # had been deleted caused a crash.
942+ class Foo : pass
943+ f = Foo ()
944+ f .__dict__ ["attr" ] = 1
945+ del f .__dict__
946+
947+ # Using a str subclass is a way to trigger the re-materialization
948+ class StrSubclass (str ): pass
949+ self .assertFalse (hasattr (f , StrSubclass ("attr" )))
950+
951+ # Changing the __class__ also triggers the re-materialization
952+ class Bar : pass
953+ f .__class__ = Bar
954+ self .assertIsInstance (f , Bar )
955+ self .assertEqual (f .__dict__ , {})
956+
957+ def test_store_attr_type_cache (self ):
958+ """Verifies that the type cache doesn't provide a value which is
959+ inconsistent from the dict."""
960+ class X :
961+ def __del__ (inner_self ):
962+ v = C .a
963+ self .assertEqual (v , C .__dict__ ['a' ])
964+
965+ class C :
966+ a = X ()
967+
968+ # prime the cache
969+ C .a
970+ C .a
971+
972+ # destructor shouldn't be able to see inconsistent state
973+ C .a = X ()
974+ C .a = X ()
975+ def test_detach_materialized_dict_no_memory (self ):
976+ # Skip test if _testcapi is not available:
977+ import_helper .import_module ('_testcapi' )
978+
979+ code = """if 1:
980+ import test.support
981+ import _testcapi
982+
983+ class A:
984+ def __init__(self):
985+ self.a = 1
986+ self.b = 2
987+ a = A()
988+ d = a.__dict__
989+ with test.support.catch_unraisable_exception() as ex:
990+ _testcapi.set_nomemory(0, 1)
991+ del a
992+ assert ex.unraisable.exc_type is MemoryError
993+ try:
994+ d["a"]
995+ except KeyError:
996+ pass
997+ else:
998+ assert False, "KeyError not raised"
999+ """
1000+ rc , out , err = script_helper .assert_python_ok ("-c" , code )
1001+ self .assertEqual (rc , 0 )
1002+ self .assertFalse (out , msg = out .decode ('utf-8' ))
1003+ self .assertFalse (err , msg = err .decode ('utf-8' ))
7521004if __name__ == '__main__' :
7531005 unittest .main ()
0 commit comments