Debian Codegraph @

lib-python/3/test/test_code.py

raw symbols SCIP
1 """This module includes tests of the code object representation.
2
3 >>> def f(x):
4 ... def g(y):
5 ... return x + y
6 ... return g
7 ...
8
9 >>> dump(f.__code__)
10 name: f
11 argcount: 1
12 posonlyargcount: 0
13 kwonlyargcount: 0
14 names: ()
15 varnames: ('x', 'g')
16 cellvars: ('x',)
17 freevars: ()
18 nlocals: 2
19 flags: 3
20 consts: ('None', '<code object g>')
21
22 >>> dump(f(4).__code__)
23 name: g
24 argcount: 1
25 posonlyargcount: 0
26 kwonlyargcount: 0
27 names: ()
28 varnames: ('y',)
29 cellvars: ()
30 freevars: ('x',)
31 nlocals: 1
32 flags: 19
33 consts: ('None',)
34
35 >>> def h(x, y):
36 ... a = x + y
37 ... b = x - y
38 ... c = a * b
39 ... return c
40 ...
41
42 >>> dump(h.__code__)
43 name: h
44 argcount: 2
45 posonlyargcount: 0
46 kwonlyargcount: 0
47 names: ()
48 varnames: ('x', 'y', 'a', 'b', 'c')
49 cellvars: ()
50 freevars: ()
51 nlocals: 5
52 flags: 3
53 consts: ('None',)
54
55 >>> def attrs(obj):
56 ... print(obj.attr1)
57 ... print(obj.attr2)
58 ... print(obj.attr3)
59
60 >>> dump(attrs.__code__)
61 name: attrs
62 argcount: 1
63 posonlyargcount: 0
64 kwonlyargcount: 0
65 names: ('print', 'attr1', 'attr2', 'attr3')
66 varnames: ('obj',)
67 cellvars: ()
68 freevars: ()
69 nlocals: 1
70 flags: 3
71 consts: ('None',)
72
73 >>> def optimize_away():
74 ... 'doc string'
75 ... 'not a docstring'
76 ... 53
77 ... 0x53
78
79 >>> dump(optimize_away.__code__)
80 name: optimize_away
81 argcount: 0
82 posonlyargcount: 0
83 kwonlyargcount: 0
84 names: ()
85 varnames: ()
86 cellvars: ()
87 freevars: ()
88 nlocals: 0
89 flags: 3
90 consts: ("'doc string'", 'None')
91
92 >>> def keywordonly_args(a,b,*,k1):
93 ... return a,b,k1
94 ...
95
96 >>> dump(keywordonly_args.__code__)
97 name: keywordonly_args
98 argcount: 2
99 posonlyargcount: 0
100 kwonlyargcount: 1
101 names: ()
102 varnames: ('a', 'b', 'k1')
103 cellvars: ()
104 freevars: ()
105 nlocals: 3
106 flags: 3
107 consts: ('None',)
108
109 >>> def posonly_args(a,b,/,c):
110 ... return a,b,c
111 ...
112
113 >>> dump(posonly_args.__code__)
114 name: posonly_args
115 argcount: 3
116 posonlyargcount: 2
117 kwonlyargcount: 0
118 names: ()
119 varnames: ('a', 'b', 'c')
120 cellvars: ()
121 freevars: ()
122 nlocals: 3
123 flags: 3
124 consts: ('None',)
125
126 """
127
128 import inspect
129 import re
130 import sys
131 import threading
132 import doctest
133 import unittest
134 import textwrap
135 import weakref
136 import dis
137
138 try:
139 import ctypes
140 except ImportError:
141 ctypes = None
142 from test.support import (cpython_only,
143 check_impl_detail, requires_debug_ranges,
144 gc_collect)
145 from test.support.script_helper import assert_python_ok
146 from test.support import threading_helper
147 from opcode import opmap
148
149
150 def consts(t):
151 """Yield a doctest-safe sequence of object reprs."""
152 for elt in t:
153 r = repr(elt)
154 if r.startswith("<code object"):
155 yield "<code object %s>" % elt.co_name
156 else:
157 yield r
158
159 def dump(co):
160 """Print out a text representation of a code object."""
161 for attr in ["name", "argcount", "posonlyargcount",
162 "kwonlyargcount", "names", "varnames",
163 "cellvars", "freevars", "nlocals", "flags"]:
164 print("%s: %s" % (attr, getattr(co, "co_" + attr)))
165 print("consts:", tuple(consts(co.co_consts)))
166
167 # Needed for test_closure_injection below
168 # Defined at global scope to avoid implicitly closing over __class__
169 def external_getitem(self, i):
170 return f"Foreign getitem: {super().__getitem__(i)}"
171
172 class CodeTest(unittest.TestCase):
173
174 @cpython_only
175 def test_newempty(self):
176 import _testcapi
177 co = _testcapi.code_newempty("filename", "funcname", 15)
178 self.assertEqual(co.co_filename, "filename")
179 self.assertEqual(co.co_name, "funcname")
180 self.assertEqual(co.co_firstlineno, 15)
181 #Empty code object should raise, but not crash the VM
182 with self.assertRaises(Exception):
183 exec(co)
184
185 @cpython_only
186 def test_closure_injection(self):
187 # From https://bugs.python.org/issue32176
188 from types import FunctionType
189 COPY_FREE_VARS = opmap['COPY_FREE_VARS']
190
191 def create_closure(__class__):
192 return (lambda: __class__).__closure__
193
194 def new_code(c):
195 '''A new code object with a __class__ cell added to freevars'''
196 return c.replace(co_freevars=c.co_freevars + ('__class__',), co_code=bytes([COPY_FREE_VARS, 1])+c.co_code)
197
198 def add_foreign_method(cls, name, f):
199 code = new_code(f.__code__)
200 assert not f.__closure__
201 closure = create_closure(cls)
202 defaults = f.__defaults__
203 setattr(cls, name, FunctionType(code, globals(), name, defaults, closure))
204
205 class List(list):
206 pass
207
208 add_foreign_method(List, "__getitem__", external_getitem)
209
210 # Ensure the closure injection actually worked
211 function = List.__getitem__
212 class_ref = function.__closure__[0].cell_contents
213 self.assertIs(class_ref, List)
214
215 # Ensure the zero-arg super() call in the injected method works
216 obj = List([1, 2, 3])
217 self.assertEqual(obj[0], "Foreign getitem: 1")
218
219 @cpython_only # co_exceptiontable is CPython 3.11-specific
220 def test_constructor(self):
221 def func(): pass
222 co = func.__code__
223 CodeType = type(co)
224
225 # test code constructor
226 CodeType(co.co_argcount,
227 co.co_posonlyargcount,
228 co.co_kwonlyargcount,
229 co.co_nlocals,
230 co.co_stacksize,
231 co.co_flags,
232 co.co_code,
233 co.co_consts,
234 co.co_names,
235 co.co_varnames,
236 co.co_filename,
237 co.co_name,
238 co.co_qualname,
239 co.co_firstlineno,
240 co.co_linetable,
241 co.co_exceptiontable,
242 co.co_freevars,
243 co.co_cellvars)
244
245 def test_qualname(self):
246 self.assertEqual(
247 CodeTest.test_qualname.__code__.co_qualname,
248 CodeTest.test_qualname.__qualname__
249 )
250
251 def test_replace(self):
252 def func():
253 x = 1
254 return x
255 code = func.__code__
256
257 # different co_name, co_varnames, co_consts
258 def func2():
259 y = 2
260 z = 3
261 return y
262 code2 = func2.__code__
263
264 for attr, value in (
265 ("co_argcount", 0),
266 ("co_posonlyargcount", 0),
267 ("co_kwonlyargcount", 0),
268 ("co_nlocals", 1),
269 ("co_stacksize", 0),
270 ("co_flags", code.co_flags | inspect.CO_COROUTINE),
271 ("co_firstlineno", 100),
272 ("co_code", code2.co_code),
273 ("co_consts", code2.co_consts),
274 ("co_names", ("myname",)),
275 ("co_varnames", ('spam',)),
276 ("co_freevars", ("freevar",)),
277 ("co_cellvars", ("cellvar",)),
278 ("co_filename", "newfilename"),
279 ("co_name", "newname"),
280 ("co_linetable", code2.co_linetable),
281 ):
282 with self.subTest(attr=attr, value=value):
283 new_code = code.replace(**{attr: value})
284 self.assertEqual(getattr(new_code, attr), value)
285
286 new_code = code.replace(co_varnames=code2.co_varnames,
287 co_nlocals=code2.co_nlocals)
288 self.assertEqual(new_code.co_varnames, code2.co_varnames)
289 self.assertEqual(new_code.co_nlocals, code2.co_nlocals)
290
291 @cpython_only # constructor signature includes co_exceptiontable
292 def test_nlocals_mismatch(self):
293 def func():
294 x = 1
295 return x
296 co = func.__code__
297 assert co.co_nlocals > 0;
298
299 # First we try the constructor.
300 CodeType = type(co)
301 for diff in (-1, 1):
302 with self.assertRaises(ValueError):
303 CodeType(co.co_argcount,
304 co.co_posonlyargcount,
305 co.co_kwonlyargcount,
306 # This is the only change.
307 co.co_nlocals + diff,
308 co.co_stacksize,
309 co.co_flags,
310 co.co_code,
311 co.co_consts,
312 co.co_names,
313 co.co_varnames,
314 co.co_filename,
315 co.co_name,
316 co.co_qualname,
317 co.co_firstlineno,
318 co.co_linetable,
319 co.co_exceptiontable,
320 co.co_freevars,
321 co.co_cellvars,
322 )
323 # Then we try the replace method.
324 with self.assertRaises(ValueError):
325 co.replace(co_nlocals=co.co_nlocals - 1)
326 with self.assertRaises(ValueError):
327 co.replace(co_nlocals=co.co_nlocals + 1)
328
329 def test_shrinking_localsplus(self):
330 # Check that PyCode_NewWithPosOnlyArgs resizes both
331 # localsplusnames and localspluskinds, if an argument is a cell.
332 def func(arg):
333 return lambda: arg
334 code = func.__code__
335 newcode = code.replace(co_name="func") # Should not raise SystemError
336 self.assertEqual(code, newcode)
337
338 def test_empty_linetable(self):
339 def func():
340 pass
341 new_code = code = func.__code__.replace(co_linetable=b'')
342 self.assertEqual(list(new_code.co_lines()), [])
343
344 @cpython_only # checks CPython-specific exception bytecodes (PUSH_EXC_INFO etc.)
345 @requires_debug_ranges()
346 def test_co_positions_artificial_instructions(self):
347 import dis
348
349 namespace = {}
350 exec(textwrap.dedent("""\
351 try:
352 1/0
353 except Exception as e:
354 exc = e
355 """), namespace)
356
357 exc = namespace['exc']
358 traceback = exc.__traceback__
359 code = traceback.tb_frame.f_code
360
361 artificial_instructions = []
362 for instr, positions in zip(
363 dis.get_instructions(code, show_caches=True),
364 code.co_positions(),
365 strict=True
366 ):
367 # If any of the positions is None, then all have to
368 # be None as well for the case above. There are still
369 # some places in the compiler, where the artificial instructions
370 # get assigned the first_lineno but they don't have other positions.
371 # There is no easy way of inferring them at that stage, so for now
372 # we don't support it.
373 self.assertIn(positions.count(None), [0, 3, 4])
374
375 if not any(positions):
376 artificial_instructions.append(instr)
377
378 self.assertEqual(
379 [
380 (instruction.opname, instruction.argval)
381 for instruction in artificial_instructions
382 ],
383 [
384 ("PUSH_EXC_INFO", None),
385 ("LOAD_CONST", None), # artificial 'None'
386 ("STORE_NAME", "e"), # XX: we know the location for this
387 ("DELETE_NAME", "e"),
388 ("RERAISE", 1),
389 ("COPY", 3),
390 ("POP_EXCEPT", None),
391 ("RERAISE", 1)
392 ]
393 )
394
395 def test_endline_and_columntable_none_when_no_debug_ranges(self):
396 # Make sure that if `-X no_debug_ranges` is used, there is
397 # minimal debug info
398 code = textwrap.dedent("""
399 def f():
400 pass
401
402 positions = f.__code__.co_positions()
403 for line, end_line, column, end_column in positions:
404 assert line == end_line
405 assert column is None
406 assert end_column is None
407 """)
408 assert_python_ok('-X', 'no_debug_ranges', '-c', code)
409
410 def test_endline_and_columntable_none_when_no_debug_ranges_env(self):
411 # Same as above but using the environment variable opt out.
412 code = textwrap.dedent("""
413 def f():
414 pass
415
416 positions = f.__code__.co_positions()
417 for line, end_line, column, end_column in positions:
418 assert line == end_line
419 assert column is None
420 assert end_column is None
421 """)
422 assert_python_ok('-c', code, PYTHONNODEBUGRANGES='1')
423
424 # co_positions behavior when info is missing.
425
426 @requires_debug_ranges()
427 def test_co_positions_empty_linetable(self):
428 def func():
429 x = 1
430 new_code = func.__code__.replace(co_linetable=b'')
431 positions = new_code.co_positions()
432 for line, end_line, column, end_column in positions:
433 self.assertIsNone(line)
434 self.assertEqual(end_line, new_code.co_firstlineno + 1)
435
436 @cpython_only # co_exceptiontable is CPython 3.11-specific
437 def test_code_equality(self):
438 def f():
439 try:
440 a()
441 except:
442 b()
443 else:
444 c()
445 finally:
446 d()
447 code_a = f.__code__
448 code_b = code_a.replace(co_linetable=b"")
449 code_c = code_a.replace(co_exceptiontable=b"")
450 code_d = code_b.replace(co_exceptiontable=b"")
451 self.assertNotEqual(code_a, code_b)
452 self.assertNotEqual(code_a, code_c)
453 self.assertNotEqual(code_a, code_d)
454 self.assertNotEqual(code_b, code_c)
455 self.assertNotEqual(code_b, code_d)
456 self.assertNotEqual(code_c, code_d)
457
458
459 def isinterned(s):
460 return s is sys.intern(('_' + s + '_')[1:-1])
461
462 class CodeConstsTest(unittest.TestCase):
463
464 def find_const(self, consts, value):
465 for v in consts:
466 if v == value:
467 return v
468 self.assertIn(value, consts) # raises an exception
469 self.fail('Should never be reached')
470
471 def assertIsInterned(self, s):
472 if not isinterned(s):
473 self.fail('String %r is not interned' % (s,))
474
475 def assertIsNotInterned(self, s):
476 if isinterned(s):
477 self.fail('String %r is interned' % (s,))
478
479 @cpython_only
480 def test_interned_string(self):
481 co = compile('res = "str_value"', '?', 'exec')
482 v = self.find_const(co.co_consts, 'str_value')
483 self.assertIsInterned(v)
484
485 @cpython_only
486 def test_interned_string_in_tuple(self):
487 co = compile('res = ("str_value",)', '?', 'exec')
488 v = self.find_const(co.co_consts, ('str_value',))
489 self.assertIsInterned(v[0])
490
491 @cpython_only
492 def test_interned_string_in_frozenset(self):
493 co = compile('res = a in {"str_value"}', '?', 'exec')
494 v = self.find_const(co.co_consts, frozenset(('str_value',)))
495 self.assertIsInterned(tuple(v)[0])
496
497 @cpython_only
498 def test_interned_string_default(self):
499 def f(a='str_value'):
500 return a
501 self.assertIsInterned(f())
502
503 @cpython_only
504 def test_interned_string_with_null(self):
505 co = compile(r'res = "str\0value!"', '?', 'exec')
506 v = self.find_const(co.co_consts, 'str\0value!')
507 self.assertIsNotInterned(v)
508
509
510 class CodeWeakRefTest(unittest.TestCase):
511
512 def test_basic(self):
513 # Create a code object in a clean environment so that we know we have
514 # the only reference to it left.
515 namespace = {}
516 exec("def f(): pass", globals(), namespace)
517 f = namespace["f"]
518 del namespace
519
520 self.called = False
521 def callback(code):
522 self.called = True
523
524 # f is now the last reference to the function, and through it, the code
525 # object. While we hold it, check that we can create a weakref and
526 # deref it. Then delete it, and check that the callback gets called and
527 # the reference dies.
528 coderef = weakref.ref(f.__code__, callback)
529 self.assertTrue(bool(coderef()))
530 del f
531 gc_collect() # For PyPy or other GCs.
532 self.assertFalse(bool(coderef()))
533 self.assertTrue(self.called)
534
535 # Python implementation of location table parsing algorithm
536 def read(it):
537 return next(it)
538
539 def read_varint(it):
540 b = read(it)
541 val = b & 63;
542 shift = 0;
543 while b & 64:
544 b = read(it)
545 shift += 6
546 val |= (b&63) << shift
547 return val
548
549 def read_signed_varint(it):
550 uval = read_varint(it)
551 if uval & 1:
552 return -(uval >> 1)
553 else:
554 return uval >> 1
555
556 def parse_location_table(code):
557 line = code.co_firstlineno
558 it = iter(code.co_linetable)
559 while True:
560 try:
561 first_byte = read(it)
562 except StopIteration:
563 return
564 code = (first_byte >> 3) & 15
565 length = (first_byte & 7) + 1
566 if code == 15:
567 yield (code, length, None, None, None, None)
568 elif code == 14:
569 line_delta = read_signed_varint(it)
570 line += line_delta
571 end_line = line + read_varint(it)
572 col = read_varint(it)
573 if col == 0:
574 col = None
575 else:
576 col -= 1
577 end_col = read_varint(it)
578 if end_col == 0:
579 end_col = None
580 else:
581 end_col -= 1
582 yield (code, length, line, end_line, col, end_col)
583 elif code == 13: # No column
584 line_delta = read_signed_varint(it)
585 line += line_delta
586 yield (code, length, line, line, None, None)
587 elif code in (10, 11, 12): # new line
588 line_delta = code - 10
589 line += line_delta
590 column = read(it)
591 end_column = read(it)
592 yield (code, length, line, line, column, end_column)
593 else:
594 assert (0 <= code < 10)
595 second_byte = read(it)
596 column = code << 3 | (second_byte >> 4)
597 yield (code, length, line, line, column, column + (second_byte & 15))
598
599 def positions_from_location_table(code):
600 for _, length, line, end_line, col, end_col in parse_location_table(code):
601 for _ in range(length):
602 yield (line, end_line, col, end_col)
603
604 def dedup(lst, prev=object()):
605 for item in lst:
606 if item != prev:
607 yield item
608 prev = item
609
610 def lines_from_postions(positions):
611 return dedup(l for (l, _, _, _) in positions)
612
613 def misshappen():
614 """
615
616
617
618
619
620 """
621 x = (
622
623
624 4
625
626 +
627
628 y
629
630 )
631 y = (
632 a
633 +
634 b
635 +
636
637 d
638 )
639 return q if (
640
641 x
642
643 ) else p
644
645 def bug93662():
646 example_report_generation_message= (
647 """
648 """
649 ).strip()
650 raise ValueError()
651
652
653 class CodeLocationTest(unittest.TestCase):
654
655 def check_positions(self, func):
656 co = func.__code__
657 pos1 = list(co.co_positions())
658 if sys.implementation.name == 'pypy':
659 # PyPy uses a different co_linetable format; cross-check
660 # co_positions() against co_lines() instead.
661 lines_from_pos = set(l for (l, _, _, _) in pos1 if l is not None)
662 lines_from_table = set(l for (_, _, l) in co.co_lines() if l is not None)
663 self.assertEqual(lines_from_pos, lines_from_table)
664 return
665 pos2 = list(positions_from_location_table(co))
666 for l1, l2 in zip(pos1, pos2):
667 self.assertEqual(l1, l2)
668 self.assertEqual(len(pos1), len(pos2))
669
670 def test_positions(self):
671 self.check_positions(parse_location_table)
672 self.check_positions(misshappen)
673 self.check_positions(bug93662)
674
675 def check_lines(self, func):
676 co = func.__code__
677 lines1 = list(dedup(l for (_, _, l) in co.co_lines()))
678 if sys.implementation.name == 'pypy':
679 # PyPy uses a different co_linetable format; cross-check
680 # co_lines() against co_positions() instead.
681 lines_from_table = set(l for l in lines1 if l is not None)
682 lines_from_pos = set(l for (l, _, _, _) in co.co_positions() if l is not None)
683 self.assertEqual(lines_from_table, lines_from_pos)
684 return
685 lines2 = list(lines_from_postions(positions_from_location_table(co)))
686 for l1, l2 in zip(lines1, lines2):
687 self.assertEqual(l1, l2)
688 self.assertEqual(len(lines1), len(lines2))
689
690 def test_lines(self):
691 self.check_lines(parse_location_table)
692 self.check_lines(misshappen)
693 self.check_lines(bug93662)
694
695 @cpython_only
696 def test_code_new_empty(self):
697 # If this test fails, it means that the construction of PyCode_NewEmpty
698 # needs to be modified! Please update this test *and* PyCode_NewEmpty,
699 # so that they both stay in sync.
700 def f():
701 pass
702 PY_CODE_LOCATION_INFO_NO_COLUMNS = 13
703 f.__code__ = f.__code__.replace(
704 co_firstlineno=42,
705 co_code=bytes(
706 [
707 dis.opmap["RESUME"], 0,
708 dis.opmap["LOAD_ASSERTION_ERROR"], 0,
709 dis.opmap["RAISE_VARARGS"], 1,
710 ]
711 ),
712 co_linetable=bytes(
713 [
714 (1 << 7)
715 | (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3)
716 | (3 - 1),
717 0,
718 ]
719 ),
720 )
721 self.assertRaises(AssertionError, f)
722 self.assertEqual(
723 list(f.__code__.co_positions()),
724 3 * [(42, 42, None, None)],
725 )
726
727
728 if check_impl_detail(cpython=True) and ctypes is not None:
729 py = ctypes.pythonapi
730 freefunc = ctypes.CFUNCTYPE(None,ctypes.c_voidp)
731
732 RequestCodeExtraIndex = py._PyEval_RequestCodeExtraIndex
733 RequestCodeExtraIndex.argtypes = (freefunc,)
734 RequestCodeExtraIndex.restype = ctypes.c_ssize_t
735
736 SetExtra = py._PyCode_SetExtra
737 SetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t, ctypes.c_voidp)
738 SetExtra.restype = ctypes.c_int
739
740 GetExtra = py._PyCode_GetExtra
741 GetExtra.argtypes = (ctypes.py_object, ctypes.c_ssize_t,
742 ctypes.POINTER(ctypes.c_voidp))
743 GetExtra.restype = ctypes.c_int
744
745 LAST_FREED = None
746 def myfree(ptr):
747 global LAST_FREED
748 LAST_FREED = ptr
749
750 FREE_FUNC = freefunc(myfree)
751 FREE_INDEX = RequestCodeExtraIndex(FREE_FUNC)
752
753 class CoExtra(unittest.TestCase):
754 def get_func(self):
755 # Defining a function causes the containing function to have a
756 # reference to the code object. We need the code objects to go
757 # away, so we eval a lambda.
758 return eval('lambda:42')
759
760 def test_get_non_code(self):
761 f = self.get_func()
762
763 self.assertRaises(SystemError, SetExtra, 42, FREE_INDEX,
764 ctypes.c_voidp(100))
765 self.assertRaises(SystemError, GetExtra, 42, FREE_INDEX,
766 ctypes.c_voidp(100))
767
768 def test_bad_index(self):
769 f = self.get_func()
770 self.assertRaises(SystemError, SetExtra, f.__code__,
771 FREE_INDEX+100, ctypes.c_voidp(100))
772 self.assertEqual(GetExtra(f.__code__, FREE_INDEX+100,
773 ctypes.c_voidp(100)), 0)
774
775 def test_free_called(self):
776 # Verify that the provided free function gets invoked
777 # when the code object is cleaned up.
778 f = self.get_func()
779
780 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(100))
781 del f
782 self.assertEqual(LAST_FREED, 100)
783
784 def test_get_set(self):
785 # Test basic get/set round tripping.
786 f = self.get_func()
787
788 extra = ctypes.c_voidp()
789
790 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(200))
791 # reset should free...
792 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(300))
793 self.assertEqual(LAST_FREED, 200)
794
795 extra = ctypes.c_voidp()
796 GetExtra(f.__code__, FREE_INDEX, extra)
797 self.assertEqual(extra.value, 300)
798 del f
799
800 @threading_helper.requires_working_threading()
801 def test_free_different_thread(self):
802 # Freeing a code object on a different thread then
803 # where the co_extra was set should be safe.
804 f = self.get_func()
805 class ThreadTest(threading.Thread):
806 def __init__(self, f, test):
807 super().__init__()
808 self.f = f
809 self.test = test
810 def run(self):
811 del self.f
812 self.test.assertEqual(LAST_FREED, 500)
813
814 SetExtra(f.__code__, FREE_INDEX, ctypes.c_voidp(500))
815 tt = ThreadTest(f, self)
816 del f
817 tt.start()
818 tt.join()
819 self.assertEqual(LAST_FREED, 500)
820
821
822 def load_tests(loader, tests, pattern):
823 if sys.implementation.name == 'pypy':
824 # PyPy sets several flags that CPython 3.11 does not expose publicly:
825 # CO_NOFREE (0x40), CO_GENERATOR_ALLOWED (0x1000),
826 # CO_KILL_DOCSTRING (0x2000000), CO_YIELD_INSIDE_TRY (0x4000000).
827 # Strip them from actual output so the doctest expected values match.
828 _FLAGS_RE = re.compile(r'^(flags: )(\d+)$', re.MULTILINE)
829 _PYPY_ONLY_FLAGS = 0x40 | 0x1000 | 0x2000000 | 0x4000000
830 class _PyPyOutputChecker(doctest.OutputChecker):
831 def check_output(self, want, got, optionflags):
832 got2 = _FLAGS_RE.sub(
833 lambda m: m.group(1) + str(int(m.group(2)) & ~_PYPY_ONLY_FLAGS),
834 got)
835 return super().check_output(want, got2, optionflags)
836 tests.addTest(doctest.DocTestSuite(checker=_PyPyOutputChecker()))
837 else:
838 tests.addTest(doctest.DocTestSuite())
839 return tests
840
841
842 if __name__ == "__main__":
843 unittest.main()