Debian Codegraph @

Lib/test/test_class.py

raw
1 "Test the functionality of Python classes implementing operators."
2
3 import unittest
4 from test.support import cpython_only, import_helper, script_helper
5
6 testmeths = [
7
8 # Binary operations
9 "add",
10 "radd",
11 "sub",
12 "rsub",
13 "mul",
14 "rmul",
15 "matmul",
16 "rmatmul",
17 "truediv",
18 "rtruediv",
19 "floordiv",
20 "rfloordiv",
21 "mod",
22 "rmod",
23 "divmod",
24 "rdivmod",
25 "pow",
26 "rpow",
27 "rshift",
28 "rrshift",
29 "lshift",
30 "rlshift",
31 "and",
32 "rand",
33 "or",
34 "ror",
35 "xor",
36 "rxor",
37
38 # List/dict operations
39 "contains",
40 "getitem",
41 "setitem",
42 "delitem",
43
44 # Unary operations
45 "neg",
46 "pos",
47 "abs",
48
49 # generic operations
50 "init",
51 ]
52
53 # These need to return something other than None
54 # "hash",
55 # "str",
56 # "repr",
57 # "int",
58 # "float",
59
60 # These are separate because they can influence the test of other methods.
61 # "getattr",
62 # "setattr",
63 # "delattr",
64
65 callLst = []
66 def trackCall(f):
67 def track(*args, **kwargs):
68 callLst.append((f.__name__, args))
69 return f(*args, **kwargs)
70 return track
71
72 statictests = """
73 @trackCall
74 def __hash__(self, *args):
75 return hash(id(self))
76
77 @trackCall
78 def __str__(self, *args):
79 return "AllTests"
80
81 @trackCall
82 def __repr__(self, *args):
83 return "AllTests"
84
85 @trackCall
86 def __int__(self, *args):
87 return 1
88
89 @trackCall
90 def __index__(self, *args):
91 return 1
92
93 @trackCall
94 def __float__(self, *args):
95 return 1.0
96
97 @trackCall
98 def __eq__(self, *args):
99 return True
100
101 @trackCall
102 def __ne__(self, *args):
103 return False
104
105 @trackCall
106 def __lt__(self, *args):
107 return False
108
109 @trackCall
110 def __le__(self, *args):
111 return True
112
113 @trackCall
114 def __gt__(self, *args):
115 return False
116
117 @trackCall
118 def __ge__(self, *args):
119 return True
120 """
121
122 # Synthesize all the other AllTests methods from the names in testmeths.
123
124 method_template = """\
125 @trackCall
126 def __%s__(self, *args):
127 pass
128 """
129
130 d = {}
131 exec(statictests, globals(), d)
132 for method in testmeths:
133 exec(method_template % method, globals(), d)
134 AllTests = type("AllTests", (object,), d)
135 del d, statictests, method, method_template
136
137 class ClassTests(unittest.TestCase):
138 def setUp(self):
139 callLst[:] = []
140
141 def assertCallStack(self, expected_calls):
142 actualCallList = callLst[:] # need to copy because the comparison below will add
143 # additional calls to callLst
144 if expected_calls != actualCallList:
145 self.fail("Expected call list:\n %s\ndoes not match actual call list\n %s" %
146 (expected_calls, actualCallList))
147
148 def testInit(self):
149 foo = AllTests()
150 self.assertCallStack([("__init__", (foo,))])
151
152 def testBinaryOps(self):
153 testme = AllTests()
154 # Binary operations
155
156 callLst[:] = []
157 testme + 1
158 self.assertCallStack([("__add__", (testme, 1))])
159
160 callLst[:] = []
161 1 + testme
162 self.assertCallStack([("__radd__", (testme, 1))])
163
164 callLst[:] = []
165 testme - 1
166 self.assertCallStack([("__sub__", (testme, 1))])
167
168 callLst[:] = []
169 1 - testme
170 self.assertCallStack([("__rsub__", (testme, 1))])
171
172 callLst[:] = []
173 testme * 1
174 self.assertCallStack([("__mul__", (testme, 1))])
175
176 callLst[:] = []
177 1 * testme
178 self.assertCallStack([("__rmul__", (testme, 1))])
179
180 callLst[:] = []
181 testme @ 1
182 self.assertCallStack([("__matmul__", (testme, 1))])
183
184 callLst[:] = []
185 1 @ testme
186 self.assertCallStack([("__rmatmul__", (testme, 1))])
187
188 callLst[:] = []
189 testme / 1
190 self.assertCallStack([("__truediv__", (testme, 1))])
191
192
193 callLst[:] = []
194 1 / testme
195 self.assertCallStack([("__rtruediv__", (testme, 1))])
196
197 callLst[:] = []
198 testme // 1
199 self.assertCallStack([("__floordiv__", (testme, 1))])
200
201
202 callLst[:] = []
203 1 // testme
204 self.assertCallStack([("__rfloordiv__", (testme, 1))])
205
206 callLst[:] = []
207 testme % 1
208 self.assertCallStack([("__mod__", (testme, 1))])
209
210 callLst[:] = []
211 1 % testme
212 self.assertCallStack([("__rmod__", (testme, 1))])
213
214
215 callLst[:] = []
216 divmod(testme,1)
217 self.assertCallStack([("__divmod__", (testme, 1))])
218
219 callLst[:] = []
220 divmod(1, testme)
221 self.assertCallStack([("__rdivmod__", (testme, 1))])
222
223 callLst[:] = []
224 testme ** 1
225 self.assertCallStack([("__pow__", (testme, 1))])
226
227 callLst[:] = []
228 1 ** testme
229 self.assertCallStack([("__rpow__", (testme, 1))])
230
231 callLst[:] = []
232 testme >> 1
233 self.assertCallStack([("__rshift__", (testme, 1))])
234
235 callLst[:] = []
236 1 >> testme
237 self.assertCallStack([("__rrshift__", (testme, 1))])
238
239 callLst[:] = []
240 testme << 1
241 self.assertCallStack([("__lshift__", (testme, 1))])
242
243 callLst[:] = []
244 1 << testme
245 self.assertCallStack([("__rlshift__", (testme, 1))])
246
247 callLst[:] = []
248 testme & 1
249 self.assertCallStack([("__and__", (testme, 1))])
250
251 callLst[:] = []
252 1 & testme
253 self.assertCallStack([("__rand__", (testme, 1))])
254
255 callLst[:] = []
256 testme | 1
257 self.assertCallStack([("__or__", (testme, 1))])
258
259 callLst[:] = []
260 1 | testme
261 self.assertCallStack([("__ror__", (testme, 1))])
262
263 callLst[:] = []
264 testme ^ 1
265 self.assertCallStack([("__xor__", (testme, 1))])
266
267 callLst[:] = []
268 1 ^ testme
269 self.assertCallStack([("__rxor__", (testme, 1))])
270
271 def testListAndDictOps(self):
272 testme = AllTests()
273
274 # List/dict operations
275
276 class Empty: pass
277
278 try:
279 1 in Empty()
280 self.fail('failed, should have raised TypeError')
281 except TypeError:
282 pass
283
284 callLst[:] = []
285 1 in testme
286 self.assertCallStack([('__contains__', (testme, 1))])
287
288 callLst[:] = []
289 testme[1]
290 self.assertCallStack([('__getitem__', (testme, 1))])
291
292 callLst[:] = []
293 testme[1] = 1
294 self.assertCallStack([('__setitem__', (testme, 1, 1))])
295
296 callLst[:] = []
297 del testme[1]
298 self.assertCallStack([('__delitem__', (testme, 1))])
299
300 callLst[:] = []
301 testme[:42]
302 self.assertCallStack([('__getitem__', (testme, slice(None, 42)))])
303
304 callLst[:] = []
305 testme[:42] = "The Answer"
306 self.assertCallStack([('__setitem__', (testme, slice(None, 42),
307 "The Answer"))])
308
309 callLst[:] = []
310 del testme[:42]
311 self.assertCallStack([('__delitem__', (testme, slice(None, 42)))])
312
313 callLst[:] = []
314 testme[2:1024:10]
315 self.assertCallStack([('__getitem__', (testme, slice(2, 1024, 10)))])
316
317 callLst[:] = []
318 testme[2:1024:10] = "A lot"
319 self.assertCallStack([('__setitem__', (testme, slice(2, 1024, 10),
320 "A lot"))])
321 callLst[:] = []
322 del testme[2:1024:10]
323 self.assertCallStack([('__delitem__', (testme, slice(2, 1024, 10)))])
324
325 callLst[:] = []
326 testme[:42, ..., :24:, 24, 100]
327 self.assertCallStack([('__getitem__', (testme, (slice(None, 42, None),
328 Ellipsis,
329 slice(None, 24, None),
330 24, 100)))])
331 callLst[:] = []
332 testme[:42, ..., :24:, 24, 100] = "Strange"
333 self.assertCallStack([('__setitem__', (testme, (slice(None, 42, None),
334 Ellipsis,
335 slice(None, 24, None),
336 24, 100), "Strange"))])
337 callLst[:] = []
338 del testme[:42, ..., :24:, 24, 100]
339 self.assertCallStack([('__delitem__', (testme, (slice(None, 42, None),
340 Ellipsis,
341 slice(None, 24, None),
342 24, 100)))])
343
344 def testUnaryOps(self):
345 testme = AllTests()
346
347 callLst[:] = []
348 -testme
349 self.assertCallStack([('__neg__', (testme,))])
350 callLst[:] = []
351 +testme
352 self.assertCallStack([('__pos__', (testme,))])
353 callLst[:] = []
354 abs(testme)
355 self.assertCallStack([('__abs__', (testme,))])
356 callLst[:] = []
357 int(testme)
358 self.assertCallStack([('__int__', (testme,))])
359 callLst[:] = []
360 float(testme)
361 self.assertCallStack([('__float__', (testme,))])
362 callLst[:] = []
363 oct(testme)
364 self.assertCallStack([('__index__', (testme,))])
365 callLst[:] = []
366 hex(testme)
367 self.assertCallStack([('__index__', (testme,))])
368
369
370 def testMisc(self):
371 testme = AllTests()
372
373 callLst[:] = []
374 hash(testme)
375 self.assertCallStack([('__hash__', (testme,))])
376
377 callLst[:] = []
378 repr(testme)
379 self.assertCallStack([('__repr__', (testme,))])
380
381 callLst[:] = []
382 str(testme)
383 self.assertCallStack([('__str__', (testme,))])
384
385 callLst[:] = []
386 testme == 1
387 self.assertCallStack([('__eq__', (testme, 1))])
388
389 callLst[:] = []
390 testme < 1
391 self.assertCallStack([('__lt__', (testme, 1))])
392
393 callLst[:] = []
394 testme > 1
395 self.assertCallStack([('__gt__', (testme, 1))])
396
397 callLst[:] = []
398 testme != 1
399 self.assertCallStack([('__ne__', (testme, 1))])
400
401 callLst[:] = []
402 1 == testme
403 self.assertCallStack([('__eq__', (1, testme))])
404
405 callLst[:] = []
406 1 < testme
407 self.assertCallStack([('__gt__', (1, testme))])
408
409 callLst[:] = []
410 1 > testme
411 self.assertCallStack([('__lt__', (1, testme))])
412
413 callLst[:] = []
414 1 != testme
415 self.assertCallStack([('__ne__', (1, testme))])
416
417
418 def testGetSetAndDel(self):
419 # Interfering tests
420 class ExtraTests(AllTests):
421 @trackCall
422 def __getattr__(self, *args):
423 return "SomeVal"
424
425 @trackCall
426 def __setattr__(self, *args):
427 pass
428
429 @trackCall
430 def __delattr__(self, *args):
431 pass
432
433 testme = ExtraTests()
434
435 callLst[:] = []
436 testme.spam
437 self.assertCallStack([('__getattr__', (testme, "spam"))])
438
439 callLst[:] = []
440 testme.eggs = "spam, spam, spam and ham"
441 self.assertCallStack([('__setattr__', (testme, "eggs",
442 "spam, spam, spam and ham"))])
443
444 callLst[:] = []
445 del testme.cardinal
446 self.assertCallStack([('__delattr__', (testme, "cardinal"))])
447
448 def testHasAttrString(self):
449 import sys
450 from test.support import import_helper
451 _testlimitedcapi = import_helper.import_module('_testlimitedcapi')
452
453 class A:
454 def __init__(self):
455 self.attr = 1
456
457 a = A()
458 self.assertEqual(_testlimitedcapi.object_hasattrstring(a, b"attr"), 1)
459 self.assertEqual(_testlimitedcapi.object_hasattrstring(a, b"noattr"), 0)
460 self.assertIsNone(sys.exception())
461
462 def testDel(self):
463 x = []
464
465 class DelTest:
466 def __del__(self):
467 x.append("crab people, crab people")
468 testme = DelTest()
469 del testme
470 import gc
471 gc.collect()
472 self.assertEqual(["crab people, crab people"], x)
473
474 def testBadTypeReturned(self):
475 # return values of some method are type-checked
476 class BadTypeClass:
477 def __int__(self):
478 return None
479 __float__ = __int__
480 __complex__ = __int__
481 __str__ = __int__
482 __repr__ = __int__
483 __bytes__ = __int__
484 __bool__ = __int__
485 __index__ = __int__
486 def index(x):
487 return [][x]
488
489 for f in [float, complex, str, repr, bytes, bin, oct, hex, bool, index]:
490 self.assertRaises(TypeError, f, BadTypeClass())
491
492 def testHashStuff(self):
493 # Test correct errors from hash() on objects with comparisons but
494 # no __hash__
495
496 class C0:
497 pass
498
499 hash(C0()) # This should work; the next two should raise TypeError
500
501 class C2:
502 def __eq__(self, other): return 1
503
504 self.assertRaises(TypeError, hash, C2())
505
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__"))
556
557 def testSFBug532646(self):
558 # Test for SF bug 532646
559
560 class A:
561 pass
562 A.__call__ = A()
563 a = A()
564
565 try:
566 a() # This should not segfault
567 except RecursionError:
568 pass
569 else:
570 self.fail("Failed to raise RecursionError")
571
572 def testForExceptionsRaisedInInstanceGetattr2(self):
573 # Tests for exceptions raised in instance_getattr2().
574
575 def booh(self):
576 raise AttributeError("booh")
577
578 class A:
579 a = property(booh)
580 try:
581 A().a # Raised AttributeError: A instance has no attribute 'a'
582 except AttributeError as x:
583 if str(x) != "booh":
584 self.fail("attribute error for A().a got masked: %s" % x)
585
586 class E:
587 __eq__ = property(booh)
588 E() == E() # In debug mode, caused a C-level assert() to fail
589
590 class I:
591 __init__ = property(booh)
592 try:
593 # In debug mode, printed XXX undetected error and
594 # raises AttributeError
595 I()
596 except AttributeError:
597 pass
598 else:
599 self.fail("attribute error for I.__init__ got masked")
600
601 def assertNotOrderable(self, a, b):
602 with self.assertRaises(TypeError):
603 a < b
604 with self.assertRaises(TypeError):
605 a > b
606 with self.assertRaises(TypeError):
607 a <= b
608 with self.assertRaises(TypeError):
609 a >= b
610
611 def testHashComparisonOfMethods(self):
612 # Test comparison and hash of methods
613 class A:
614 def __init__(self, x):
615 self.x = x
616 def f(self):
617 pass
618 def g(self):
619 pass
620 def __eq__(self, other):
621 return True
622 def __hash__(self):
623 raise TypeError
624 class B(A):
625 pass
626
627 a1 = A(1)
628 a2 = A(1)
629 self.assertTrue(a1.f == a1.f)
630 self.assertFalse(a1.f != a1.f)
631 self.assertFalse(a1.f == a2.f)
632 self.assertTrue(a1.f != a2.f)
633 self.assertFalse(a1.f == a1.g)
634 self.assertTrue(a1.f != a1.g)
635 self.assertNotOrderable(a1.f, a1.f)
636 self.assertEqual(hash(a1.f), hash(a1.f))
637
638 self.assertFalse(A.f == a1.f)
639 self.assertTrue(A.f != a1.f)
640 self.assertFalse(A.f == A.g)
641 self.assertTrue(A.f != A.g)
642 self.assertTrue(B.f == A.f)
643 self.assertFalse(B.f != A.f)
644 self.assertNotOrderable(A.f, A.f)
645 self.assertEqual(hash(B.f), hash(A.f))
646
647 # the following triggers a SystemError in 2.4
648 a = A(hash(A.f)^(-1))
649 hash(a.f)
650
651 def testSetattrWrapperNameIntern(self):
652 # Issue #25794: __setattr__ should intern the attribute name
653 class A:
654 pass
655
656 def add(self, other):
657 return 'summa'
658
659 name = str(b'__add__', 'ascii') # shouldn't be optimized
660 self.assertIsNot(name, '__add__') # not interned
661 type.__setattr__(A, name, add)
662 self.assertEqual(A() + 1, 'summa')
663
664 name2 = str(b'__add__', 'ascii')
665 self.assertIsNot(name2, '__add__')
666 self.assertIsNot(name2, name)
667 type.__delattr__(A, name2)
668 with self.assertRaises(TypeError):
669 A() + 1
670
671 def testSetattrNonStringName(self):
672 class A:
673 pass
674
675 with self.assertRaises(TypeError):
676 type.__setattr__(A, b'x', None)
677
678 def testTypeAttributeAccessErrorMessages(self):
679 class A:
680 pass
681
682 error_msg = "type object 'A' has no attribute 'x'"
683 with self.assertRaisesRegex(AttributeError, error_msg):
684 A.x
685 with self.assertRaisesRegex(AttributeError, error_msg):
686 del A.x
687
688 def testObjectAttributeAccessErrorMessages(self):
689 class A:
690 pass
691 class B:
692 y = 0
693 __slots__ = ('z',)
694 class C:
695 __slots__ = ("y",)
696
697 def __setattr__(self, name, value) -> None:
698 if name == "z":
699 super().__setattr__("y", 1)
700 else:
701 super().__setattr__(name, value)
702
703 error_msg = "'A' object has no attribute 'x'"
704 with self.assertRaisesRegex(AttributeError, error_msg):
705 A().x
706 with self.assertRaisesRegex(AttributeError, error_msg):
707 del A().x
708
709 error_msg = "'B' object has no attribute 'x'"
710 with self.assertRaisesRegex(AttributeError, error_msg):
711 B().x
712 with self.assertRaisesRegex(AttributeError, error_msg):
713 del B().x
714 with self.assertRaisesRegex(
715 AttributeError,
716 "'B' object has no attribute 'x' and no __dict__ for setting new attributes"
717 ):
718 B().x = 0
719 with self.assertRaisesRegex(
720 AttributeError,
721 "'C' object has no attribute 'x'"
722 ):
723 C().x = 0
724
725 error_msg = "'B' object attribute 'y' is read-only"
726 with self.assertRaisesRegex(AttributeError, error_msg):
727 del B().y
728 with self.assertRaisesRegex(AttributeError, error_msg):
729 B().y = 0
730
731 error_msg = 'z'
732 with self.assertRaisesRegex(AttributeError, error_msg):
733 B().z
734 with self.assertRaisesRegex(AttributeError, error_msg):
735 del B().z
736
737 def testConstructorErrorMessages(self):
738 # bpo-31506: Improves the error message logic for object_new & object_init
739
740 # Class without any method overrides
741 class C:
742 pass
743
744 error_msg = r'C.__init__\(\) takes exactly one argument \(the instance to initialize\)'
745
746 with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'):
747 C(42)
748
749 with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'):
750 C.__new__(C, 42)
751
752 with self.assertRaisesRegex(TypeError, error_msg):
753 C().__init__(42)
754
755 with self.assertRaisesRegex(TypeError, r'C\(\) takes no arguments'):
756 object.__new__(C, 42)
757
758 with self.assertRaisesRegex(TypeError, error_msg):
759 object.__init__(C(), 42)
760
761 # Class with both `__init__` & `__new__` method overridden
762 class D:
763 def __new__(cls, *args, **kwargs):
764 super().__new__(cls, *args, **kwargs)
765 def __init__(self, *args, **kwargs):
766 super().__init__(*args, **kwargs)
767
768 error_msg = r'object.__new__\(\) takes exactly one argument \(the type to instantiate\)'
769
770 with self.assertRaisesRegex(TypeError, error_msg):
771 D(42)
772
773 with self.assertRaisesRegex(TypeError, error_msg):
774 D.__new__(D, 42)
775
776 with self.assertRaisesRegex(TypeError, error_msg):
777 object.__new__(D, 42)
778
779 # Class that only overrides __init__
780 class E:
781 def __init__(self, *args, **kwargs):
782 super().__init__(*args, **kwargs)
783
784 error_msg = r'object.__init__\(\) takes exactly one argument \(the instance to initialize\)'
785
786 with self.assertRaisesRegex(TypeError, error_msg):
787 E().__init__(42)
788
789 with self.assertRaisesRegex(TypeError, error_msg):
790 object.__init__(E(), 42)
791
792 def testClassWithExtCall(self):
793 class Meta(int):
794 def __init__(*args, **kwargs):
795 pass
796
797 def __new__(cls, name, bases, attrs, **kwargs):
798 return bases, kwargs
799
800 d = {'metaclass': Meta}
801
802 class A(**d): pass
803 self.assertEqual(A, ((), {}))
804 class A(0, 1, 2, 3, 4, 5, 6, 7, **d): pass
805 self.assertEqual(A, (tuple(range(8)), {}))
806 class A(0, *range(1, 8), **d, foo='bar'): pass
807 self.assertEqual(A, (tuple(range(8)), {'foo': 'bar'}))
808
809 def testClassCallRecursionLimit(self):
810 class C:
811 def __init__(self):
812 self.c = C()
813
814 with self.assertRaises(RecursionError):
815 C()
816
817 def add_one_level():
818 #Each call to C() consumes 2 levels, so offset by 1.
819 C()
820
821 with self.assertRaises(RecursionError):
822 add_one_level()
823
824 def testMetaclassCallOptimization(self):
825 calls = 0
826
827 class TypeMetaclass(type):
828 def __call__(cls, *args, **kwargs):
829 nonlocal calls
830 calls += 1
831 return type.__call__(cls, *args, **kwargs)
832
833 class Type(metaclass=TypeMetaclass):
834 def __init__(self, obj):
835 self._obj = obj
836
837 for i in range(100):
838 Type(i)
839 self.assertEqual(calls, 100)
840
841
842 from _testinternalcapi import has_inline_values
843
844 Py_TPFLAGS_INLINE_VALUES = (1 << 2)
845 Py_TPFLAGS_MANAGED_DICT = (1 << 4)
846
847 class NoManagedDict:
848 __slots__ = ('a',)
849
850
851 class Plain:
852 pass
853
854
855 class WithAttrs:
856
857 def __init__(self):
858 self.a = 1
859 self.b = 2
860 self.c = 3
861 self.d = 4
862
863
864 class VarSizedSubclass(tuple):
865 pass
866
867
868 class TestInlineValues(unittest.TestCase):
869
870 def test_no_flags_for_slots_class(self):
871 flags = NoManagedDict.__flags__
872 self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, 0)
873 self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, 0)
874 self.assertFalse(has_inline_values(NoManagedDict()))
875
876 def test_both_flags_for_regular_class(self):
877 for cls in (Plain, WithAttrs):
878 with self.subTest(cls=cls.__name__):
879 flags = cls.__flags__
880 self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, Py_TPFLAGS_MANAGED_DICT)
881 self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, Py_TPFLAGS_INLINE_VALUES)
882 self.assertTrue(has_inline_values(cls()))
883
884 def test_managed_dict_only_for_varsized_subclass(self):
885 flags = VarSizedSubclass.__flags__
886 self.assertEqual(flags & Py_TPFLAGS_MANAGED_DICT, Py_TPFLAGS_MANAGED_DICT)
887 self.assertEqual(flags & Py_TPFLAGS_INLINE_VALUES, 0)
888 self.assertFalse(has_inline_values(VarSizedSubclass()))
889
890 def test_has_inline_values(self):
891 c = Plain()
892 self.assertTrue(has_inline_values(c))
893 del c.__dict__
894 self.assertFalse(has_inline_values(c))
895
896 def test_instances(self):
897 self.assertTrue(has_inline_values(Plain()))
898 self.assertTrue(has_inline_values(WithAttrs()))
899
900 def test_inspect_dict(self):
901 for cls in (Plain, WithAttrs):
902 c = cls()
903 c.__dict__
904 self.assertTrue(has_inline_values(c))
905
906 def test_update_dict(self):
907 d = { "e": 5, "f": 6 }
908 for cls in (Plain, WithAttrs):
909 c = cls()
910 c.__dict__.update(d)
911 self.assertTrue(has_inline_values(c))
912
913 @staticmethod
914 def set_100(obj):
915 for i in range(100):
916 setattr(obj, f"a{i}", i)
917
918 def check_100(self, obj):
919 for i in range(100):
920 self.assertEqual(getattr(obj, f"a{i}"), i)
921
922 def test_many_attributes(self):
923 class C: pass
924 c = C()
925 self.assertTrue(has_inline_values(c))
926 self.set_100(c)
927 self.assertFalse(has_inline_values(c))
928 self.check_100(c)
929 c = C()
930 self.assertTrue(has_inline_values(c))
931
932 def test_many_attributes_with_dict(self):
933 class C: pass
934 c = C()
935 d = c.__dict__
936 self.assertTrue(has_inline_values(c))
937 self.set_100(c)
938 self.assertFalse(has_inline_values(c))
939 self.check_100(c)
940
941 def test_bug_117750(self):
942 "Aborted on 3.13a6"
943 class C:
944 def __init__(self):
945 self.__dict__.clear()
946
947 obj = C()
948 self.assertEqual(obj.__dict__, {})
949 obj.foo = None # Aborted here
950 self.assertEqual(obj.__dict__, {"foo":None})
951
952 def test_store_attr_deleted_dict(self):
953 class Foo:
954 pass
955
956 f = Foo()
957 del f.__dict__
958 f.a = 3
959 self.assertEqual(f.a, 3)
960
961 def test_rematerialize_object_dict(self):
962 # gh-121860: rematerializing an object's managed dictionary after it
963 # had been deleted caused a crash.
964 class Foo: pass
965 f = Foo()
966 f.__dict__["attr"] = 1
967 del f.__dict__
968
969 # Using a str subclass is a way to trigger the re-materialization
970 class StrSubclass(str): pass
971 self.assertFalse(hasattr(f, StrSubclass("attr")))
972
973 # Changing the __class__ also triggers the re-materialization
974 class Bar: pass
975 f.__class__ = Bar
976 self.assertIsInstance(f, Bar)
977 self.assertEqual(f.__dict__, {})
978
979 def test_store_attr_type_cache(self):
980 """Verifies that the type cache doesn't provide a value which is
981 inconsistent from the dict."""
982 class X:
983 def __del__(inner_self):
984 v = C.a
985 self.assertEqual(v, C.__dict__['a'])
986
987 class C:
988 a = X()
989
990 # prime the cache
991 C.a
992 C.a
993
994 # destructor shouldn't be able to see inconsistent state
995 C.a = X()
996 C.a = X()
997
998 @cpython_only
999 def test_detach_materialized_dict_no_memory(self):
1000 # Skip test if _testcapi is not available:
1001 import_helper.import_module('_testcapi')
1002
1003 code = """if 1:
1004 import test.support
1005 import _testcapi
1006
1007 class A:
1008 def __init__(self):
1009 self.a = 1
1010 self.b = 2
1011 a = A()
1012 d = a.__dict__
1013 with test.support.catch_unraisable_exception() as ex:
1014 _testcapi.set_nomemory(0, 1)
1015 del a
1016 assert ex.unraisable.exc_type is MemoryError
1017 try:
1018 d["a"]
1019 except KeyError:
1020 pass
1021 else:
1022 assert False, "KeyError not raised"
1023 """
1024 rc, out, err = script_helper.assert_python_ok("-c", code)
1025 self.assertEqual(rc, 0)
1026 self.assertFalse(out, msg=out.decode('utf-8'))
1027 self.assertFalse(err, msg=err.decode('utf-8'))
1028
1029 if __name__ == '__main__':
1030 unittest.main()