Debian Codegraph @

Lib/test/test_super.py

raw
1 """Unit tests for zero-argument super() & related machinery."""
2
3 import textwrap
4 import threading
5 import unittest
6 from unittest.mock import patch
7 from test.support import import_helper, threading_helper
8
9
10 ADAPTIVE_WARMUP_DELAY = 2
11
12
13 class A:
14 def f(self):
15 return 'A'
16 @classmethod
17 def cm(cls):
18 return (cls, 'A')
19
20 class B(A):
21 def f(self):
22 return super().f() + 'B'
23 @classmethod
24 def cm(cls):
25 return (cls, super().cm(), 'B')
26
27 class C(A):
28 def f(self):
29 return super().f() + 'C'
30 @classmethod
31 def cm(cls):
32 return (cls, super().cm(), 'C')
33
34 class D(C, B):
35 def f(self):
36 return super().f() + 'D'
37 def cm(cls):
38 return (cls, super().cm(), 'D')
39
40 class E(D):
41 pass
42
43 class F(E):
44 f = E.f
45
46 class G(A):
47 pass
48
49
50 class TestSuper(unittest.TestCase):
51
52 def tearDown(self):
53 # This fixes the damage that test_various___class___pathologies does.
54 nonlocal __class__
55 __class__ = TestSuper
56
57 def test_basics_working(self):
58 self.assertEqual(D().f(), 'ABCD')
59
60 def test_class_getattr_working(self):
61 self.assertEqual(D.f(D()), 'ABCD')
62
63 def test_subclass_no_override_working(self):
64 self.assertEqual(E().f(), 'ABCD')
65 self.assertEqual(E.f(E()), 'ABCD')
66
67 def test_unbound_method_transfer_working(self):
68 self.assertEqual(F().f(), 'ABCD')
69 self.assertEqual(F.f(F()), 'ABCD')
70
71 def test_class_methods_still_working(self):
72 self.assertEqual(A.cm(), (A, 'A'))
73 self.assertEqual(A().cm(), (A, 'A'))
74 self.assertEqual(G.cm(), (G, 'A'))
75 self.assertEqual(G().cm(), (G, 'A'))
76
77 def test_super_in_class_methods_working(self):
78 d = D()
79 self.assertEqual(d.cm(), (d, (D, (D, (D, 'A'), 'B'), 'C'), 'D'))
80 e = E()
81 self.assertEqual(e.cm(), (e, (E, (E, (E, 'A'), 'B'), 'C'), 'D'))
82
83 def test_super_with_closure(self):
84 # Issue4360: super() did not work in a function that
85 # contains a closure
86 class E(A):
87 def f(self):
88 def nested():
89 self
90 return super().f() + 'E'
91
92 self.assertEqual(E().f(), 'AE')
93
94 def test_various___class___pathologies(self):
95 # See issue #12370
96 class X(A):
97 def f(self):
98 return super().f()
99 __class__ = 413
100 x = X()
101 self.assertEqual(x.f(), 'A')
102 self.assertEqual(x.__class__, 413)
103 class X:
104 x = __class__
105 def f():
106 __class__
107 self.assertIs(X.x, type(self))
108 with self.assertRaises(NameError) as e:
109 exec("""class X:
110 __class__
111 def f():
112 __class__""", globals(), {})
113 self.assertIs(type(e.exception), NameError) # Not UnboundLocalError
114 class X:
115 global __class__
116 __class__ = 42
117 def f():
118 __class__
119 self.assertEqual(globals()["__class__"], 42)
120 del globals()["__class__"]
121 self.assertNotIn("__class__", X.__dict__)
122 class X:
123 nonlocal __class__
124 __class__ = 42
125 def f():
126 __class__
127 self.assertEqual(__class__, 42)
128
129 def test___class___instancemethod(self):
130 # See issue #14857
131 class X:
132 def f(self):
133 return __class__
134 self.assertIs(X().f(), X)
135
136 def test___class___classmethod(self):
137 # See issue #14857
138 class X:
139 @classmethod
140 def f(cls):
141 return __class__
142 self.assertIs(X.f(), X)
143
144 def test___class___staticmethod(self):
145 # See issue #14857
146 class X:
147 @staticmethod
148 def f():
149 return __class__
150 self.assertIs(X.f(), X)
151
152 def test___class___new(self):
153 # See issue #23722
154 # Ensure zero-arg super() works as soon as type.__new__() is completed
155 test_class = None
156
157 class Meta(type):
158 def __new__(cls, name, bases, namespace):
159 nonlocal test_class
160 self = super().__new__(cls, name, bases, namespace)
161 test_class = self.f()
162 return self
163
164 class A(metaclass=Meta):
165 @staticmethod
166 def f():
167 return __class__
168
169 self.assertIs(test_class, A)
170
171 def test___class___delayed(self):
172 # See issue #23722
173 test_namespace = None
174
175 class Meta(type):
176 def __new__(cls, name, bases, namespace):
177 nonlocal test_namespace
178 test_namespace = namespace
179 return None
180
181 class A(metaclass=Meta):
182 @staticmethod
183 def f():
184 return __class__
185
186 self.assertIs(A, None)
187
188 B = type("B", (), test_namespace)
189 self.assertIs(B.f(), B)
190
191 def test___class___mro(self):
192 # See issue #23722
193 test_class = None
194
195 class Meta(type):
196 def mro(self):
197 # self.f() doesn't work yet...
198 self.__dict__["f"]()
199 return super().mro()
200
201 class A(metaclass=Meta):
202 def f():
203 nonlocal test_class
204 test_class = __class__
205
206 self.assertIs(test_class, A)
207
208 def test___classcell___expected_behaviour(self):
209 # See issue #23722
210 class Meta(type):
211 def __new__(cls, name, bases, namespace):
212 nonlocal namespace_snapshot
213 namespace_snapshot = namespace.copy()
214 return super().__new__(cls, name, bases, namespace)
215
216 # __classcell__ is injected into the class namespace by the compiler
217 # when at least one method needs it, and should be omitted otherwise
218 namespace_snapshot = None
219 class WithoutClassRef(metaclass=Meta):
220 pass
221 self.assertNotIn("__classcell__", namespace_snapshot)
222
223 # With zero-arg super() or an explicit __class__ reference,
224 # __classcell__ is the exact cell reference to be populated by
225 # type.__new__
226 namespace_snapshot = None
227 class WithClassRef(metaclass=Meta):
228 def f(self):
229 return __class__
230
231 class_cell = namespace_snapshot["__classcell__"]
232 method_closure = WithClassRef.f.__closure__
233 self.assertEqual(len(method_closure), 1)
234 self.assertIs(class_cell, method_closure[0])
235 # Ensure the cell reference *doesn't* get turned into an attribute
236 with self.assertRaises(AttributeError):
237 WithClassRef.__classcell__
238
239 def test___classcell___missing(self):
240 # See issue #23722
241 # Some metaclasses may not pass the original namespace to type.__new__
242 # We test that case here by forcibly deleting __classcell__
243 class Meta(type):
244 def __new__(cls, name, bases, namespace):
245 namespace.pop('__classcell__', None)
246 return super().__new__(cls, name, bases, namespace)
247
248 # The default case should continue to work without any errors
249 class WithoutClassRef(metaclass=Meta):
250 pass
251
252 # With zero-arg super() or an explicit __class__ reference, we expect
253 # __build_class__ to raise a RuntimeError complaining that
254 # __class__ was not set, and asking if __classcell__ was propagated
255 # to type.__new__.
256 expected_error = '__class__ not set.*__classcell__ propagated'
257 with self.assertRaisesRegex(RuntimeError, expected_error):
258 class WithClassRef(metaclass=Meta):
259 def f(self):
260 return __class__
261
262 def test___classcell___overwrite(self):
263 # See issue #23722
264 # Overwriting __classcell__ with nonsense is explicitly prohibited
265 class Meta(type):
266 def __new__(cls, name, bases, namespace, cell):
267 namespace['__classcell__'] = cell
268 return super().__new__(cls, name, bases, namespace)
269
270 for bad_cell in (None, 0, "", object()):
271 with self.subTest(bad_cell=bad_cell):
272 with self.assertRaises(TypeError):
273 class A(metaclass=Meta, cell=bad_cell):
274 pass
275
276 def test___classcell___wrong_cell(self):
277 # See issue #23722
278 # Pointing the cell reference at the wrong class is also prohibited
279 class Meta(type):
280 def __new__(cls, name, bases, namespace):
281 cls = super().__new__(cls, name, bases, namespace)
282 B = type("B", (), namespace)
283 return cls
284
285 with self.assertRaises(TypeError):
286 class A(metaclass=Meta):
287 def f(self):
288 return __class__
289
290 def test_obscure_super_errors(self):
291 def f():
292 super()
293 with self.assertRaisesRegex(RuntimeError, r"no arguments"):
294 f()
295
296 class C:
297 def f():
298 super()
299 with self.assertRaisesRegex(RuntimeError, r"no arguments"):
300 C.f()
301
302 def f(x):
303 del x
304 super()
305 with self.assertRaisesRegex(RuntimeError, r"arg\[0\] deleted"):
306 f(None)
307
308 class X:
309 def f(x):
310 nonlocal __class__
311 del __class__
312 super()
313 with self.assertRaisesRegex(RuntimeError, r"empty __class__ cell"):
314 X().f()
315
316 def test_cell_as_self(self):
317 class X:
318 def meth(self):
319 super()
320
321 def f():
322 k = X()
323 def g():
324 return k
325 return g
326 c = f().__closure__[0]
327 self.assertRaises(TypeError, X.meth, c)
328
329 def test_super_init_leaks(self):
330 # Issue #26718: super.__init__ leaked memory if called multiple times.
331 # This will be caught by regrtest.py -R if this leak.
332 # NOTE: Despite the use in the test a direct call of super.__init__
333 # is not endorsed.
334 sp = super(float, 1.0)
335 for i in range(1000):
336 super.__init__(sp, int, i)
337
338 def test_super_argcount(self):
339 with self.assertRaisesRegex(TypeError, "expected at most"):
340 super(int, int, int)
341
342 def test_super_argtype(self):
343 with self.assertRaisesRegex(TypeError, "argument 1 must be a type"):
344 super(1, int)
345
346 def test_shadowed_global(self):
347 source = textwrap.dedent(
348 """
349 class super:
350 msg = "truly super"
351
352 class C:
353 def method(self):
354 return super().msg
355 """,
356 )
357 with import_helper.ready_to_import(name="shadowed_super", source=source):
358 import shadowed_super
359 self.assertEqual(shadowed_super.C().method(), "truly super")
360 import_helper.unload("shadowed_super")
361
362 def test_shadowed_local(self):
363 class super:
364 msg = "quite super"
365
366 class C:
367 def method(self):
368 return super().msg
369
370 self.assertEqual(C().method(), "quite super")
371
372 def test_shadowed_dynamic(self):
373 class MySuper:
374 msg = "super super"
375
376 class C:
377 def method(self):
378 return super().msg
379
380 with patch(f"{__name__}.super", MySuper) as m:
381 self.assertEqual(C().method(), "super super")
382
383 def test_shadowed_dynamic_two_arg(self):
384 call_args = []
385 class MySuper:
386 def __init__(self, *args):
387 call_args.append(args)
388 msg = "super super"
389
390 class C:
391 def method(self):
392 return super(1, 2).msg
393
394 with patch(f"{__name__}.super", MySuper) as m:
395 self.assertEqual(C().method(), "super super")
396 self.assertEqual(call_args, [(1, 2)])
397
398 def test_attribute_error(self):
399 class C:
400 def method(self):
401 return super().msg
402
403 with self.assertRaisesRegex(AttributeError, "'super' object has no attribute 'msg'"):
404 C().method()
405
406 def test_bad_first_arg(self):
407 class C:
408 def method(self):
409 return super(1, self).method()
410
411 with self.assertRaisesRegex(TypeError, "argument 1 must be a type"):
412 C().method()
413
414 def test_supercheck_fail(self):
415 class C:
416 def method(self, type_, obj):
417 return super(type_, obj).method()
418
419 c = C()
420 err_msg = (
421 r"super\(type, obj\): obj \({} {}\) is not "
422 r"an instance or subtype of type \({}\)."
423 )
424
425 cases = (
426 (int, c, int.__name__, C.__name__, "instance of"),
427 # obj is instance of type
428 (C, list(), C.__name__, list.__name__, "instance of"),
429 # obj is type itself
430 (C, list, C.__name__, list.__name__, "type"),
431 )
432
433 for case in cases:
434 with self.subTest(case=case):
435 type_, obj, type_str, obj_str, instance_or_type = case
436 regex = err_msg.format(instance_or_type, obj_str, type_str)
437
438 with self.assertRaisesRegex(TypeError, regex):
439 c.method(type_, obj)
440
441 def test_super___class__(self):
442 class C:
443 def method(self):
444 return super().__class__
445
446 self.assertEqual(C().method(), super)
447
448 def test_super_subclass___class__(self):
449 class mysuper(super):
450 pass
451
452 class C:
453 def method(self):
454 return mysuper(C, self).__class__
455
456 self.assertEqual(C().method(), mysuper)
457
458 def test_unusual_getattro(self):
459 class MyType(type):
460 pass
461
462 def test(name):
463 mytype = MyType(name, (MyType,), {})
464 super(MyType, type(mytype)).__setattr__(mytype, "bar", 1)
465 self.assertEqual(mytype.bar, 1)
466
467 for _ in range(ADAPTIVE_WARMUP_DELAY):
468 test("foo1")
469
470 def test_reassigned_new(self):
471 class A:
472 def __new__(cls):
473 pass
474
475 def __init_subclass__(cls):
476 if "__new__" not in cls.__dict__:
477 cls.__new__ = cls.__new__
478
479 class B(A):
480 pass
481
482 class C(B):
483 def __new__(cls):
484 return super().__new__(cls)
485
486 for _ in range(ADAPTIVE_WARMUP_DELAY):
487 C()
488
489 def test_mixed_staticmethod_hierarchy(self):
490 # This test is just a desugared version of `test_reassigned_new`
491 class A:
492 @staticmethod
493 def some(cls, *args, **kwargs):
494 self.assertFalse(args)
495 self.assertFalse(kwargs)
496
497 class B(A):
498 def some(cls, *args, **kwargs):
499 return super().some(cls, *args, **kwargs)
500
501 class C(B):
502 @staticmethod
503 def some(cls):
504 return super().some(cls)
505
506 for _ in range(ADAPTIVE_WARMUP_DELAY):
507 C.some(C)
508
509 @threading_helper.requires_working_threading()
510 def test___class___modification_multithreaded(self):
511 """ Note: this test isn't actually testing anything on its own.
512 It requires a sys audithook to be set to crash on older Python.
513 This should be the case anyways as our test suite sets
514 an audit hook.
515 """
516
517 class Foo:
518 pass
519
520 class Bar:
521 pass
522
523 thing = Foo()
524 def work():
525 foo = thing
526 for _ in range(200):
527 foo.__class__ = Bar
528 type(foo)
529 foo.__class__ = Foo
530 type(foo)
531
532
533 threads = []
534 for _ in range(6):
535 thread = threading.Thread(target=work)
536 thread.start()
537 threads.append(thread)
538
539 for thread in threads:
540 thread.join()
541
542
543 if __name__ == "__main__":
544 unittest.main()