Debian Codegraph @

Lib/test/test_capi/test_misc.py

raw
1 # Run the _testcapi module tests (tests for the Python/C API): by defn,
2 # these are all functions _testcapi exports whose name begins with 'test_'.
3
4 import _thread
5 from collections import deque
6 import contextlib
7 import importlib.machinery
8 import importlib.util
9 import json
10 import os
11 import pickle
12 import queue
13 import random
14 import sys
15 import textwrap
16 import threading
17 import time
18 import types
19 import unittest
20 import warnings
21 import weakref
22 import operator
23 from test import support
24 from test.support import MISSING_C_DOCSTRINGS
25 from test.support import import_helper
26 from test.support import threading_helper
27 from test.support import warnings_helper
28 from test.support import requires_limited_api
29 from test.support import suppress_immortalization
30 from test.support import expected_failure_if_gil_disabled
31 from test.support import Py_GIL_DISABLED
32 from test.support.script_helper import assert_python_failure, assert_python_ok, run_python_until_end
33 try:
34 import _posixsubprocess
35 except ImportError:
36 _posixsubprocess = None
37 try:
38 import _testmultiphase
39 except ImportError:
40 _testmultiphase = None
41 try:
42 import _testsinglephase
43 except ImportError:
44 _testsinglephase = None
45 try:
46 import _interpreters
47 except ModuleNotFoundError:
48 _interpreters = None
49
50 # Skip this test if the _testcapi module isn't available.
51 _testcapi = import_helper.import_module('_testcapi')
52
53 import _testlimitedcapi
54 import _testinternalcapi
55
56
57 NULL = None
58
59 def decode_stderr(err):
60 return err.decode('utf-8', 'replace').replace('\r', '')
61
62
63 def requires_subinterpreters(meth):
64 """Decorator to skip a test if subinterpreters are not supported."""
65 return unittest.skipIf(_interpreters is None,
66 'subinterpreters required')(meth)
67
68
69 def testfunction(self):
70 """some doc"""
71 return self
72
73
74 class InstanceMethod:
75 id = _testcapi.instancemethod(id)
76 testfunction = _testcapi.instancemethod(testfunction)
77
78
79 @support.force_not_colorized_test_class
80 class CAPITest(unittest.TestCase):
81
82 def test_instancemethod(self):
83 inst = InstanceMethod()
84 self.assertEqual(id(inst), inst.id())
85 self.assertTrue(inst.testfunction() is inst)
86 self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
87 self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
88
89 InstanceMethod.testfunction.attribute = "test"
90 self.assertEqual(testfunction.attribute, "test")
91 self.assertRaises(AttributeError, setattr, inst.testfunction, "attribute", "test")
92
93 @support.requires_subprocess()
94 def test_no_FatalError_infinite_loop(self):
95 code = textwrap.dedent("""
96 import _testcapi
97 from test import support
98
99 with support.SuppressCrashReport():
100 _testcapi.crash_no_current_thread()
101 """)
102
103 run_result, _cmd_line = run_python_until_end('-c', code)
104 _rc, out, err = run_result
105 self.assertEqual(out, b'')
106 # This used to cause an infinite loop.
107 msg = ("Fatal Python error: PyThreadState_Get: "
108 "the function must be called with the GIL held, "
109 "after Python initialization and before Python finalization, "
110 "but the GIL is released "
111 "(the current Python thread state is NULL)").encode()
112 self.assertTrue(err.rstrip().startswith(msg),
113 err)
114
115 def test_memoryview_from_NULL_pointer(self):
116 self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
117
118 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
119 def test_seq_bytes_to_charp_array(self):
120 # Issue #15732: crash in _PySequence_BytesToCharpArray()
121 class Z(object):
122 def __len__(self):
123 return 1
124 with self.assertRaisesRegex(TypeError, 'indexing'):
125 _posixsubprocess.fork_exec(
126 1,Z(),True,(1, 2),5,6,7,8,9,10,11,12,13,14,True,True,17,False,19,20,21,22,False)
127 # Issue #15736: overflow in _PySequence_BytesToCharpArray()
128 class Z(object):
129 def __len__(self):
130 return sys.maxsize
131 def __getitem__(self, i):
132 return b'x'
133 self.assertRaises(MemoryError, _posixsubprocess.fork_exec,
134 1,Z(),True,(1, 2),5,6,7,8,9,10,11,12,13,14,True,True,17,False,19,20,21,22,False)
135
136 @unittest.skipUnless(_posixsubprocess, '_posixsubprocess required for this test.')
137 def test_subprocess_fork_exec(self):
138 class Z(object):
139 def __len__(self):
140 return 1
141
142 # Issue #15738: crash in subprocess_fork_exec()
143 self.assertRaises(TypeError, _posixsubprocess.fork_exec,
144 Z(),[b'1'],True,(1, 2),5,6,7,8,9,10,11,12,13,14,True,True,17,False,19,20,21,22,False)
145
146 @unittest.skipIf(MISSING_C_DOCSTRINGS,
147 "Signature information for builtins requires docstrings")
148 def test_docstring_signature_parsing(self):
149
150 self.assertEqual(_testcapi.no_docstring.__doc__, None)
151 self.assertEqual(_testcapi.no_docstring.__text_signature__, None)
152
153 self.assertEqual(_testcapi.docstring_empty.__doc__, None)
154 self.assertEqual(_testcapi.docstring_empty.__text_signature__, None)
155
156 self.assertEqual(_testcapi.docstring_no_signature.__doc__,
157 "This docstring has no signature.")
158 self.assertEqual(_testcapi.docstring_no_signature.__text_signature__, None)
159
160 self.assertEqual(_testcapi.docstring_with_invalid_signature.__doc__,
161 "docstring_with_invalid_signature($module, /, boo)\n"
162 "\n"
163 "This docstring has an invalid signature."
164 )
165 self.assertEqual(_testcapi.docstring_with_invalid_signature.__text_signature__, None)
166
167 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__doc__,
168 "docstring_with_invalid_signature2($module, /, boo)\n"
169 "\n"
170 "--\n"
171 "\n"
172 "This docstring also has an invalid signature."
173 )
174 self.assertEqual(_testcapi.docstring_with_invalid_signature2.__text_signature__, None)
175
176 self.assertEqual(_testcapi.docstring_with_signature.__doc__,
177 "This docstring has a valid signature.")
178 self.assertEqual(_testcapi.docstring_with_signature.__text_signature__, "($module, /, sig)")
179
180 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__doc__, None)
181 self.assertEqual(_testcapi.docstring_with_signature_but_no_doc.__text_signature__,
182 "($module, /, sig)")
183
184 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__doc__,
185 "\nThis docstring has a valid signature and some extra newlines.")
186 self.assertEqual(_testcapi.docstring_with_signature_and_extra_newlines.__text_signature__,
187 "($module, /, parameter)")
188
189 def test_c_type_with_matrix_multiplication(self):
190 M = _testcapi.matmulType
191 m1 = M()
192 m2 = M()
193 self.assertEqual(m1 @ m2, ("matmul", m1, m2))
194 self.assertEqual(m1 @ 42, ("matmul", m1, 42))
195 self.assertEqual(42 @ m1, ("matmul", 42, m1))
196 o = m1
197 o @= m2
198 self.assertEqual(o, ("imatmul", m1, m2))
199 o = m1
200 o @= 42
201 self.assertEqual(o, ("imatmul", m1, 42))
202 o = 42
203 o @= m1
204 self.assertEqual(o, ("matmul", 42, m1))
205
206 def test_c_type_with_ipow(self):
207 # When the __ipow__ method of a type was implemented in C, using the
208 # modulo param would cause segfaults.
209 o = _testcapi.ipowType()
210 self.assertEqual(o.__ipow__(1), (1, None))
211 self.assertEqual(o.__ipow__(2, 2), (2, 2))
212
213 def test_return_null_without_error(self):
214 # Issue #23571: A function must not return NULL without setting an
215 # error
216 if support.Py_DEBUG:
217 code = textwrap.dedent("""
218 import _testcapi
219 from test import support
220
221 with support.SuppressCrashReport():
222 _testcapi.return_null_without_error()
223 """)
224 rc, out, err = assert_python_failure('-c', code)
225 err = decode_stderr(err)
226 self.assertRegex(err,
227 r'Fatal Python error: _Py_CheckFunctionResult: '
228 r'a function returned NULL without setting an exception\n'
229 r'Python runtime state: initialized\n'
230 r'SystemError: <built-in function return_null_without_error> '
231 r'returned NULL without setting an exception\n'
232 r'\n'
233 r'Current thread.*:\n'
234 r' File .*", line 6 in <module>\n')
235 else:
236 with self.assertRaises(SystemError) as cm:
237 _testcapi.return_null_without_error()
238 self.assertRegex(str(cm.exception),
239 'return_null_without_error.* '
240 'returned NULL without setting an exception')
241
242 def test_return_result_with_error(self):
243 # Issue #23571: A function must not return a result with an error set
244 if support.Py_DEBUG:
245 code = textwrap.dedent("""
246 import _testcapi
247 from test import support
248
249 with support.SuppressCrashReport():
250 _testcapi.return_result_with_error()
251 """)
252 rc, out, err = assert_python_failure('-c', code)
253 err = decode_stderr(err)
254 self.assertRegex(err,
255 r'Fatal Python error: _Py_CheckFunctionResult: '
256 r'a function returned a result with an exception set\n'
257 r'Python runtime state: initialized\n'
258 r'ValueError\n'
259 r'\n'
260 r'The above exception was the direct cause '
261 r'of the following exception:\n'
262 r'\n'
263 r'SystemError: <built-in '
264 r'function return_result_with_error> '
265 r'returned a result with an exception set\n'
266 r'\n'
267 r'Current thread.*:\n'
268 r' File .*, line 6 in <module>\n')
269 else:
270 with self.assertRaises(SystemError) as cm:
271 _testcapi.return_result_with_error()
272 self.assertRegex(str(cm.exception),
273 'return_result_with_error.* '
274 'returned a result with an exception set')
275
276 def test_getitem_with_error(self):
277 # Test _Py_CheckSlotResult(). Raise an exception and then calls
278 # PyObject_GetItem(): check that the assertion catches the bug.
279 # PyObject_GetItem() must not be called with an exception set.
280 code = textwrap.dedent("""
281 import _testcapi
282 from test import support
283
284 with support.SuppressCrashReport():
285 _testcapi.getitem_with_error({1: 2}, 1)
286 """)
287 rc, out, err = assert_python_failure('-c', code)
288 err = decode_stderr(err)
289 if 'SystemError: ' not in err:
290 self.assertRegex(err,
291 r'Fatal Python error: _Py_CheckSlotResult: '
292 r'Slot __getitem__ of type dict succeeded '
293 r'with an exception set\n'
294 r'Python runtime state: initialized\n'
295 r'ValueError: bug\n'
296 r'\n'
297 r'Current thread .* \(most recent call first\):\n'
298 r' File .*, line 6 in <module>\n'
299 r'\n'
300 r'Extension modules: _testcapi \(total: 1\)\n')
301 else:
302 # Python built with NDEBUG macro defined:
303 # test _Py_CheckFunctionResult() instead.
304 self.assertIn('returned a result with an exception set', err)
305
306 def test_buildvalue(self):
307 # Test Py_BuildValue() with object arguments
308 buildvalue = _testcapi.py_buildvalue
309 self.assertEqual(buildvalue(''), None)
310 self.assertEqual(buildvalue('()'), ())
311 self.assertEqual(buildvalue('[]'), [])
312 self.assertEqual(buildvalue('{}'), {})
313 self.assertEqual(buildvalue('()[]{}'), ((), [], {}))
314 self.assertEqual(buildvalue('O', 1), 1)
315 self.assertEqual(buildvalue('(O)', 1), (1,))
316 self.assertEqual(buildvalue('[O]', 1), [1])
317 self.assertRaises(SystemError, buildvalue, '{O}', 1)
318 self.assertEqual(buildvalue('OO', 1, 2), (1, 2))
319 self.assertEqual(buildvalue('(OO)', 1, 2), (1, 2))
320 self.assertEqual(buildvalue('[OO]', 1, 2), [1, 2])
321 self.assertEqual(buildvalue('{OO}', 1, 2), {1: 2})
322 self.assertEqual(buildvalue('{OOOO}', 1, 2, 3, 4), {1: 2, 3: 4})
323 self.assertEqual(buildvalue('((O))', 1), ((1,),))
324 self.assertEqual(buildvalue('((OO))', 1, 2), ((1, 2),))
325
326 self.assertEqual(buildvalue(' \t,:'), None)
327 self.assertEqual(buildvalue('O,', 1), 1)
328 self.assertEqual(buildvalue(' O ', 1), 1)
329 self.assertEqual(buildvalue('\tO\t', 1), 1)
330 self.assertEqual(buildvalue('O,O', 1, 2), (1, 2))
331 self.assertEqual(buildvalue('O, O', 1, 2), (1, 2))
332 self.assertEqual(buildvalue('O,\tO', 1, 2), (1, 2))
333 self.assertEqual(buildvalue('O O', 1, 2), (1, 2))
334 self.assertEqual(buildvalue('O\tO', 1, 2), (1, 2))
335 self.assertEqual(buildvalue('(O,O)', 1, 2), (1, 2))
336 self.assertEqual(buildvalue('(O, O,)', 1, 2), (1, 2))
337 self.assertEqual(buildvalue(' ( O O ) ', 1, 2), (1, 2))
338 self.assertEqual(buildvalue('\t(\tO\tO\t)\t', 1, 2), (1, 2))
339 self.assertEqual(buildvalue('[O,O]', 1, 2), [1, 2])
340 self.assertEqual(buildvalue('[O, O,]', 1, 2), [1, 2])
341 self.assertEqual(buildvalue(' [ O O ] ', 1, 2), [1, 2])
342 self.assertEqual(buildvalue(' [\tO\tO\t] ', 1, 2), [1, 2])
343 self.assertEqual(buildvalue('{O:O}', 1, 2), {1: 2})
344 self.assertEqual(buildvalue('{O:O,O:O}', 1, 2, 3, 4), {1: 2, 3: 4})
345 self.assertEqual(buildvalue('{O: O, O: O,}', 1, 2, 3, 4), {1: 2, 3: 4})
346 self.assertEqual(buildvalue(' { O O O O } ', 1, 2, 3, 4), {1: 2, 3: 4})
347 self.assertEqual(buildvalue('\t{\tO\tO\tO\tO\t}\t', 1, 2, 3, 4), {1: 2, 3: 4})
348
349 self.assertRaises(SystemError, buildvalue, 'O', NULL)
350 self.assertRaises(SystemError, buildvalue, '(O)', NULL)
351 self.assertRaises(SystemError, buildvalue, '[O]', NULL)
352 self.assertRaises(SystemError, buildvalue, '{O}', NULL)
353 self.assertRaises(SystemError, buildvalue, 'OO', 1, NULL)
354 self.assertRaises(SystemError, buildvalue, 'OO', NULL, 2)
355 self.assertRaises(SystemError, buildvalue, '(OO)', 1, NULL)
356 self.assertRaises(SystemError, buildvalue, '(OO)', NULL, 2)
357 self.assertRaises(SystemError, buildvalue, '[OO]', 1, NULL)
358 self.assertRaises(SystemError, buildvalue, '[OO]', NULL, 2)
359 self.assertRaises(SystemError, buildvalue, '{OO}', 1, NULL)
360 self.assertRaises(SystemError, buildvalue, '{OO}', NULL, 2)
361
362 def test_buildvalue_ints(self):
363 # Test Py_BuildValue() with integer arguments
364 buildvalue = _testcapi.py_buildvalue_ints
365 from _testcapi import SHRT_MIN, SHRT_MAX, USHRT_MAX, INT_MIN, INT_MAX, UINT_MAX
366 self.assertEqual(buildvalue('i', INT_MAX), INT_MAX)
367 self.assertEqual(buildvalue('i', INT_MIN), INT_MIN)
368 self.assertEqual(buildvalue('I', UINT_MAX), UINT_MAX)
369
370 self.assertEqual(buildvalue('h', SHRT_MAX), SHRT_MAX)
371 self.assertEqual(buildvalue('h', SHRT_MIN), SHRT_MIN)
372 self.assertEqual(buildvalue('H', USHRT_MAX), USHRT_MAX)
373
374 self.assertEqual(buildvalue('b', 127), 127)
375 self.assertEqual(buildvalue('b', -128), -128)
376 self.assertEqual(buildvalue('B', 255), 255)
377
378 self.assertEqual(buildvalue('c', ord('A')), b'A')
379 self.assertEqual(buildvalue('c', 255), b'\xff')
380 self.assertEqual(buildvalue('c', 256), b'\x00')
381 self.assertEqual(buildvalue('c', -1), b'\xff')
382
383 self.assertEqual(buildvalue('C', 255), chr(255))
384 self.assertEqual(buildvalue('C', 256), chr(256))
385 self.assertEqual(buildvalue('C', sys.maxunicode), chr(sys.maxunicode))
386 self.assertRaises(ValueError, buildvalue, 'C', -1)
387 self.assertRaises(ValueError, buildvalue, 'C', sys.maxunicode+1)
388
389 # gh-84489
390 self.assertRaises(ValueError, buildvalue, '(C )i', -1, 2)
391 self.assertRaises(ValueError, buildvalue, '[C ]i', -1, 2)
392 self.assertRaises(ValueError, buildvalue, '{Ci }i', -1, 2, 3)
393
394 def test_buildvalue_N(self):
395 _testcapi.test_buildvalue_N()
396
397 def check_negative_refcount(self, code):
398 # bpo-35059: Check that Py_DECREF() reports the correct filename
399 # when calling _Py_NegativeRefcount() to abort Python.
400 code = textwrap.dedent(code)
401 rc, out, err = assert_python_failure('-c', code)
402 self.assertRegex(err,
403 br'_testcapimodule\.c:[0-9]+: '
404 br'_Py_NegativeRefcount: Assertion failed: '
405 br'object has negative ref count')
406
407 @unittest.skipUnless(hasattr(_testcapi, 'negative_refcount'),
408 'need _testcapi.negative_refcount()')
409 def test_negative_refcount(self):
410 code = """
411 import _testcapi
412 from test import support
413
414 with support.SuppressCrashReport():
415 _testcapi.negative_refcount()
416 """
417 self.check_negative_refcount(code)
418
419 @unittest.skipUnless(hasattr(_testcapi, 'decref_freed_object'),
420 'need _testcapi.decref_freed_object()')
421 @support.skip_if_sanitizer("use after free on purpose",
422 address=True, memory=True, ub=True)
423 def test_decref_freed_object(self):
424 code = """
425 import _testcapi
426 from test import support
427
428 with support.SuppressCrashReport():
429 _testcapi.decref_freed_object()
430 """
431 self.check_negative_refcount(code)
432
433 def test_trashcan_subclass(self):
434 # bpo-35983: Check that the trashcan mechanism for "list" is NOT
435 # activated when its tp_dealloc is being called by a subclass
436 from _testcapi import MyList
437 L = None
438 for i in range(1000):
439 L = MyList((L,))
440
441 @support.requires_resource('cpu')
442 def test_trashcan_python_class1(self):
443 self.do_test_trashcan_python_class(list)
444
445 @support.requires_resource('cpu')
446 def test_trashcan_python_class2(self):
447 from _testcapi import MyList
448 self.do_test_trashcan_python_class(MyList)
449
450 def do_test_trashcan_python_class(self, base):
451 # Check that the trashcan mechanism works properly for a Python
452 # subclass of a class using the trashcan (this specific test assumes
453 # that the base class "base" behaves like list)
454 class PyList(base):
455 # Count the number of PyList instances to verify that there is
456 # no memory leak
457 num = 0
458 def __init__(self, *args):
459 __class__.num += 1
460 super().__init__(*args)
461 def __del__(self):
462 __class__.num -= 1
463
464 for parity in (0, 1):
465 L = None
466 # We need in the order of 2**20 iterations here such that a
467 # typical 8MB stack would overflow without the trashcan.
468 for i in range(2**20):
469 L = PyList((L,))
470 L.attr = i
471 if parity:
472 # Add one additional nesting layer
473 L = (L,)
474 self.assertGreater(PyList.num, 0)
475 del L
476 self.assertEqual(PyList.num, 0)
477
478 @unittest.skipIf(MISSING_C_DOCSTRINGS,
479 "Signature information for builtins requires docstrings")
480 def test_heap_ctype_doc_and_text_signature(self):
481 self.assertEqual(_testcapi.HeapDocCType.__doc__, "somedoc")
482 self.assertEqual(_testcapi.HeapDocCType.__text_signature__, "(arg1, arg2)")
483
484 def test_null_type_doc(self):
485 self.assertEqual(_testcapi.NullTpDocType.__doc__, None)
486
487 @suppress_immortalization()
488 def test_subclass_of_heap_gc_ctype_with_tpdealloc_decrefs_once(self):
489 class HeapGcCTypeSubclass(_testcapi.HeapGcCType):
490 def __init__(self):
491 self.value2 = 20
492 super().__init__()
493
494 subclass_instance = HeapGcCTypeSubclass()
495 type_refcnt = sys.getrefcount(HeapGcCTypeSubclass)
496
497 # Test that subclass instance was fully created
498 self.assertEqual(subclass_instance.value, 10)
499 self.assertEqual(subclass_instance.value2, 20)
500
501 # Test that the type reference count is only decremented once
502 del subclass_instance
503 self.assertEqual(type_refcnt - 1, sys.getrefcount(HeapGcCTypeSubclass))
504
505 @suppress_immortalization()
506 def test_subclass_of_heap_gc_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
507 class A(_testcapi.HeapGcCType):
508 def __init__(self):
509 self.value2 = 20
510 super().__init__()
511
512 class B(A):
513 def __init__(self):
514 super().__init__()
515
516 def __del__(self):
517 self.__class__ = A
518 A.refcnt_in_del = sys.getrefcount(A)
519 B.refcnt_in_del = sys.getrefcount(B)
520
521 subclass_instance = B()
522 type_refcnt = sys.getrefcount(B)
523 new_type_refcnt = sys.getrefcount(A)
524
525 # Test that subclass instance was fully created
526 self.assertEqual(subclass_instance.value, 10)
527 self.assertEqual(subclass_instance.value2, 20)
528
529 del subclass_instance
530
531 # Test that setting __class__ modified the reference counts of the types
532 if support.Py_DEBUG:
533 # gh-89373: In debug mode, _Py_Dealloc() keeps a strong reference
534 # to the type while calling tp_dealloc()
535 self.assertEqual(type_refcnt, B.refcnt_in_del)
536 else:
537 self.assertEqual(type_refcnt - 1, B.refcnt_in_del)
538 self.assertEqual(new_type_refcnt + 1, A.refcnt_in_del)
539
540 # Test that the original type already has decreased its refcnt
541 self.assertEqual(type_refcnt - 1, sys.getrefcount(B))
542
543 # Test that subtype_dealloc decref the newly assigned __class__ only once
544 self.assertEqual(new_type_refcnt, sys.getrefcount(A))
545
546 def test_heaptype_with_dict(self):
547 inst = _testcapi.HeapCTypeWithDict()
548 inst.foo = 42
549 self.assertEqual(inst.foo, 42)
550 self.assertEqual(inst.dictobj, inst.__dict__)
551 self.assertEqual(inst.dictobj, {"foo": 42})
552
553 inst = _testcapi.HeapCTypeWithDict()
554 self.assertEqual({}, inst.__dict__)
555
556 def test_heaptype_with_managed_dict(self):
557 inst = _testcapi.HeapCTypeWithManagedDict()
558 inst.foo = 42
559 self.assertEqual(inst.foo, 42)
560 self.assertEqual(inst.__dict__, {"foo": 42})
561
562 inst = _testcapi.HeapCTypeWithManagedDict()
563 self.assertEqual({}, inst.__dict__)
564
565 a = _testcapi.HeapCTypeWithManagedDict()
566 b = _testcapi.HeapCTypeWithManagedDict()
567 a.b = b
568 b.a = a
569 del a, b
570
571 def test_sublclassing_managed_dict(self):
572
573 class C(_testcapi.HeapCTypeWithManagedDict):
574 pass
575
576 i = C()
577 i.spam = i
578 del i
579
580 def test_heaptype_with_negative_dict(self):
581 inst = _testcapi.HeapCTypeWithNegativeDict()
582 inst.foo = 42
583 self.assertEqual(inst.foo, 42)
584 self.assertEqual(inst.dictobj, inst.__dict__)
585 self.assertEqual(inst.dictobj, {"foo": 42})
586
587 inst = _testcapi.HeapCTypeWithNegativeDict()
588 self.assertEqual({}, inst.__dict__)
589
590 def test_heaptype_with_weakref(self):
591 inst = _testcapi.HeapCTypeWithWeakref()
592 ref = weakref.ref(inst)
593 self.assertEqual(ref(), inst)
594 self.assertEqual(inst.weakreflist, ref)
595
596 def test_heaptype_with_managed_weakref(self):
597 inst = _testcapi.HeapCTypeWithManagedWeakref()
598 ref = weakref.ref(inst)
599 self.assertEqual(ref(), inst)
600
601 def test_sublclassing_managed_weakref(self):
602
603 class C(_testcapi.HeapCTypeWithManagedWeakref):
604 pass
605
606 inst = C()
607 ref = weakref.ref(inst)
608 self.assertEqual(ref(), inst)
609
610 def test_sublclassing_managed_both(self):
611
612 class C1(_testcapi.HeapCTypeWithManagedWeakref, _testcapi.HeapCTypeWithManagedDict):
613 pass
614
615 class C2(_testcapi.HeapCTypeWithManagedDict, _testcapi.HeapCTypeWithManagedWeakref):
616 pass
617
618 for cls in (C1, C2):
619 inst = cls()
620 ref = weakref.ref(inst)
621 self.assertEqual(ref(), inst)
622 inst.spam = inst
623 del inst
624 ref = weakref.ref(cls())
625 self.assertIs(ref(), None)
626
627 def test_heaptype_with_buffer(self):
628 inst = _testcapi.HeapCTypeWithBuffer()
629 b = bytes(inst)
630 self.assertEqual(b, b"1234")
631
632 def test_c_subclass_of_heap_ctype_with_tpdealloc_decrefs_once(self):
633 subclass_instance = _testcapi.HeapCTypeSubclass()
634 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
635
636 # Test that subclass instance was fully created
637 self.assertEqual(subclass_instance.value, 10)
638 self.assertEqual(subclass_instance.value2, 20)
639
640 # Test that the type reference count is only decremented once
641 del subclass_instance
642 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclass))
643
644 def test_c_subclass_of_heap_ctype_with_del_modifying_dunder_class_only_decrefs_once(self):
645 subclass_instance = _testcapi.HeapCTypeSubclassWithFinalizer()
646 type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer)
647 new_type_refcnt = sys.getrefcount(_testcapi.HeapCTypeSubclass)
648
649 # Test that subclass instance was fully created
650 self.assertEqual(subclass_instance.value, 10)
651 self.assertEqual(subclass_instance.value2, 20)
652
653 # The tp_finalize slot will set __class__ to HeapCTypeSubclass
654 del subclass_instance
655
656 # Test that setting __class__ modified the reference counts of the types
657 if support.Py_DEBUG:
658 # gh-89373: In debug mode, _Py_Dealloc() keeps a strong reference
659 # to the type while calling tp_dealloc()
660 self.assertEqual(type_refcnt, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
661 else:
662 self.assertEqual(type_refcnt - 1, _testcapi.HeapCTypeSubclassWithFinalizer.refcnt_in_del)
663 self.assertEqual(new_type_refcnt + 1, _testcapi.HeapCTypeSubclass.refcnt_in_del)
664
665 # Test that the original type already has decreased its refcnt
666 self.assertEqual(type_refcnt - 1, sys.getrefcount(_testcapi.HeapCTypeSubclassWithFinalizer))
667
668 # Test that subtype_dealloc decref the newly assigned __class__ only once
669 self.assertEqual(new_type_refcnt, sys.getrefcount(_testcapi.HeapCTypeSubclass))
670
671 def test_heaptype_with_setattro(self):
672 obj = _testcapi.HeapCTypeSetattr()
673 self.assertEqual(obj.pvalue, 10)
674 obj.value = 12
675 self.assertEqual(obj.pvalue, 12)
676 del obj.value
677 self.assertEqual(obj.pvalue, 0)
678
679 def test_heaptype_with_custom_metaclass(self):
680 metaclass = _testcapi.HeapCTypeMetaclass
681 self.assertTrue(issubclass(metaclass, type))
682
683 # Class creation from C
684 t = _testcapi.pytype_fromspec_meta(metaclass)
685 self.assertIsInstance(t, type)
686 self.assertEqual(t.__name__, "HeapCTypeViaMetaclass")
687 self.assertIs(type(t), metaclass)
688
689 # Class creation from Python
690 t = metaclass("PyClassViaMetaclass", (), {})
691 self.assertIsInstance(t, type)
692 self.assertEqual(t.__name__, "PyClassViaMetaclass")
693
694 def test_heaptype_with_custom_metaclass_null_new(self):
695 metaclass = _testcapi.HeapCTypeMetaclassNullNew
696
697 self.assertTrue(issubclass(metaclass, type))
698
699 # Class creation from C
700 t = _testcapi.pytype_fromspec_meta(metaclass)
701 self.assertIsInstance(t, type)
702 self.assertEqual(t.__name__, "HeapCTypeViaMetaclass")
703 self.assertIs(type(t), metaclass)
704
705 # Class creation from Python
706 with self.assertRaisesRegex(TypeError, "cannot create .* instances"):
707 metaclass("PyClassViaMetaclass", (), {})
708
709 def test_heaptype_with_custom_metaclass_custom_new(self):
710 metaclass = _testcapi.HeapCTypeMetaclassCustomNew
711
712 self.assertTrue(issubclass(_testcapi.HeapCTypeMetaclassCustomNew, type))
713
714 msg = "Metaclasses with custom tp_new are not supported."
715 with self.assertRaisesRegex(TypeError, msg):
716 t = _testcapi.pytype_fromspec_meta(metaclass)
717
718 def test_heaptype_with_custom_metaclass_deprecation(self):
719 metaclass = _testcapi.HeapCTypeMetaclassCustomNew
720
721 # gh-103968: a metaclass with custom tp_new is deprecated, but still
722 # allowed for functions that existed in 3.11
723 # (PyType_FromSpecWithBases is used here).
724 class Base(metaclass=metaclass):
725 pass
726
727 # Class creation from C
728 with warnings_helper.check_warnings(
729 ('.* _testcapi.Subclass .* custom tp_new.*in Python 3.14.*', DeprecationWarning),
730 ):
731 sub = _testcapi.make_type_with_base(Base)
732 self.assertTrue(issubclass(sub, Base))
733 self.assertIsInstance(sub, metaclass)
734
735 def test_multiple_inheritance_ctypes_with_weakref_or_dict(self):
736
737 with self.assertRaises(TypeError):
738 class Both1(_testcapi.HeapCTypeWithWeakref, _testcapi.HeapCTypeWithDict):
739 pass
740 with self.assertRaises(TypeError):
741 class Both2(_testcapi.HeapCTypeWithDict, _testcapi.HeapCTypeWithWeakref):
742 pass
743
744 def test_multiple_inheritance_ctypes_with_weakref_or_dict_and_other_builtin(self):
745
746 with self.assertRaises(TypeError):
747 class C1(_testcapi.HeapCTypeWithDict, list):
748 pass
749
750 with self.assertRaises(TypeError):
751 class C2(_testcapi.HeapCTypeWithWeakref, list):
752 pass
753
754 class C3(_testcapi.HeapCTypeWithManagedDict, list):
755 pass
756 class C4(_testcapi.HeapCTypeWithManagedWeakref, list):
757 pass
758
759 inst = C3()
760 inst.append(0)
761 str(inst.__dict__)
762
763 inst = C4()
764 inst.append(0)
765 str(inst.__weakref__)
766
767 for cls in (_testcapi.HeapCTypeWithManagedDict, _testcapi.HeapCTypeWithManagedWeakref):
768 for cls2 in (_testcapi.HeapCTypeWithDict, _testcapi.HeapCTypeWithWeakref):
769 class S(cls, cls2):
770 pass
771 class B1(C3, cls):
772 pass
773 class B2(C4, cls):
774 pass
775
776 def test_pytype_fromspec_with_repeated_slots(self):
777 for variant in range(2):
778 with self.subTest(variant=variant):
779 with self.assertRaises(SystemError):
780 _testcapi.create_type_from_repeated_slots(variant)
781
782 @warnings_helper.ignore_warnings(category=DeprecationWarning)
783 def test_immutable_type_with_mutable_base(self):
784 # Add deprecation warning here so it's removed in 3.14
785 warnings._deprecated(
786 'creating immutable classes with mutable bases', remove=(3, 14))
787
788 class MutableBase:
789 def meth(self):
790 return 'original'
791
792 with self.assertWarns(DeprecationWarning):
793 ImmutableSubclass = _testcapi.make_immutable_type_with_base(
794 MutableBase)
795 instance = ImmutableSubclass()
796
797 self.assertEqual(instance.meth(), 'original')
798
799 # Cannot override the static type's method
800 with self.assertRaisesRegex(
801 TypeError,
802 "cannot set 'meth' attribute of immutable type"):
803 ImmutableSubclass.meth = lambda self: 'overridden'
804 self.assertEqual(instance.meth(), 'original')
805
806 # Can change the method on the mutable base
807 MutableBase.meth = lambda self: 'changed'
808 self.assertEqual(instance.meth(), 'changed')
809
810 def test_pynumber_tobase(self):
811 from _testcapi import pynumber_tobase
812 small_number = 123
813 large_number = 2**64
814 class IDX:
815 def __init__(self, val):
816 self.val = val
817 def __index__(self):
818 return self.val
819
820 test_cases = ((2, '0b1111011', '0b10000000000000000000000000000000000000000000000000000000000000000'),
821 (8, '0o173', '0o2000000000000000000000'),
822 (10, '123', '18446744073709551616'),
823 (16, '0x7b', '0x10000000000000000'))
824 for base, small_target, large_target in test_cases:
825 with self.subTest(base=base, st=small_target, lt=large_target):
826 # Test for small number
827 self.assertEqual(pynumber_tobase(small_number, base), small_target)
828 self.assertEqual(pynumber_tobase(-small_number, base), '-' + small_target)
829 self.assertEqual(pynumber_tobase(IDX(small_number), base), small_target)
830 # Test for large number(out of range of a longlong,i.e.[-2**63, 2**63-1])
831 self.assertEqual(pynumber_tobase(large_number, base), large_target)
832 self.assertEqual(pynumber_tobase(-large_number, base), '-' + large_target)
833 self.assertEqual(pynumber_tobase(IDX(large_number), base), large_target)
834 self.assertRaises(TypeError, pynumber_tobase, IDX(123.0), 10)
835 self.assertRaises(TypeError, pynumber_tobase, IDX('123'), 10)
836 self.assertRaises(TypeError, pynumber_tobase, 123.0, 10)
837 self.assertRaises(TypeError, pynumber_tobase, '123', 10)
838 self.assertRaises(SystemError, pynumber_tobase, 123, 0)
839
840 def test_pyobject_repr_from_null(self):
841 s = _testcapi.pyobject_repr_from_null()
842 self.assertEqual(s, '<NULL>')
843
844 def test_pyobject_str_from_null(self):
845 s = _testcapi.pyobject_str_from_null()
846 self.assertEqual(s, '<NULL>')
847
848 def test_pyobject_bytes_from_null(self):
849 s = _testcapi.pyobject_bytes_from_null()
850 self.assertEqual(s, b'<NULL>')
851
852 def test_Py_CompileString(self):
853 # Check that Py_CompileString respects the coding cookie
854 _compile = _testcapi.Py_CompileString
855 code = b"# -*- coding: latin1 -*-\nprint('\xc2\xa4')\n"
856 result = _compile(code)
857 expected = compile(code, "<string>", "exec")
858 self.assertEqual(result.co_consts, expected.co_consts)
859
860 def test_export_symbols(self):
861 # bpo-44133: Ensure that the "Py_FrozenMain" and
862 # "PyThread_get_thread_native_id" symbols are exported by the Python
863 # (directly by the binary, or via by the Python dynamic library).
864 ctypes = import_helper.import_module('ctypes')
865 names = []
866
867 # Test if the PY_HAVE_THREAD_NATIVE_ID macro is defined
868 if hasattr(_thread, 'get_native_id'):
869 names.append('PyThread_get_thread_native_id')
870
871 # Python/frozenmain.c fails to build on Windows when the symbols are
872 # missing:
873 # - PyWinFreeze_ExeInit
874 # - PyWinFreeze_ExeTerm
875 # - PyInitFrozenExtensions
876 if os.name != 'nt':
877 names.append('Py_FrozenMain')
878
879 for name in names:
880 with self.subTest(name=name):
881 self.assertTrue(hasattr(ctypes.pythonapi, name))
882
883 def test_clear_managed_dict(self):
884
885 class C:
886 def __init__(self):
887 self.a = 1
888
889 c = C()
890 _testcapi.clear_managed_dict(c)
891 self.assertEqual(c.__dict__, {})
892 c = C()
893 self.assertEqual(c.__dict__, {'a':1})
894 _testcapi.clear_managed_dict(c)
895 self.assertEqual(c.__dict__, {})
896
897 def test_function_get_code(self):
898 import types
899
900 def some():
901 pass
902
903 code = _testcapi.function_get_code(some)
904 self.assertIsInstance(code, types.CodeType)
905 self.assertEqual(code, some.__code__)
906
907 with self.assertRaises(SystemError):
908 _testcapi.function_get_code(None) # not a function
909
910 def test_function_get_globals(self):
911 def some():
912 pass
913
914 globals_ = _testcapi.function_get_globals(some)
915 self.assertIsInstance(globals_, dict)
916 self.assertEqual(globals_, some.__globals__)
917
918 with self.assertRaises(SystemError):
919 _testcapi.function_get_globals(None) # not a function
920
921 def test_function_get_module(self):
922 def some():
923 pass
924
925 module = _testcapi.function_get_module(some)
926 self.assertIsInstance(module, str)
927 self.assertEqual(module, some.__module__)
928
929 with self.assertRaises(SystemError):
930 _testcapi.function_get_module(None) # not a function
931
932 def test_function_get_defaults(self):
933 def some(
934 pos_only1, pos_only2='p',
935 /,
936 zero=0, optional=None,
937 *,
938 kw1,
939 kw2=True,
940 ):
941 pass
942
943 defaults = _testcapi.function_get_defaults(some)
944 self.assertEqual(defaults, ('p', 0, None))
945 self.assertEqual(defaults, some.__defaults__)
946
947 with self.assertRaises(SystemError):
948 _testcapi.function_get_defaults(None) # not a function
949
950 def test_function_set_defaults(self):
951 def some(
952 pos_only1, pos_only2='p',
953 /,
954 zero=0, optional=None,
955 *,
956 kw1,
957 kw2=True,
958 ):
959 pass
960
961 old_defaults = ('p', 0, None)
962 self.assertEqual(_testcapi.function_get_defaults(some), old_defaults)
963 self.assertEqual(some.__defaults__, old_defaults)
964
965 with self.assertRaises(SystemError):
966 _testcapi.function_set_defaults(some, 1) # not tuple or None
967 self.assertEqual(_testcapi.function_get_defaults(some), old_defaults)
968 self.assertEqual(some.__defaults__, old_defaults)
969
970 with self.assertRaises(SystemError):
971 _testcapi.function_set_defaults(1, ()) # not a function
972 self.assertEqual(_testcapi.function_get_defaults(some), old_defaults)
973 self.assertEqual(some.__defaults__, old_defaults)
974
975 new_defaults = ('q', 1, None)
976 _testcapi.function_set_defaults(some, new_defaults)
977 self.assertEqual(_testcapi.function_get_defaults(some), new_defaults)
978 self.assertEqual(some.__defaults__, new_defaults)
979
980 # Empty tuple is fine:
981 new_defaults = ()
982 _testcapi.function_set_defaults(some, new_defaults)
983 self.assertEqual(_testcapi.function_get_defaults(some), new_defaults)
984 self.assertEqual(some.__defaults__, new_defaults)
985
986 class tuplesub(tuple): ... # tuple subclasses must work
987
988 new_defaults = tuplesub(((1, 2), ['a', 'b'], None))
989 _testcapi.function_set_defaults(some, new_defaults)
990 self.assertEqual(_testcapi.function_get_defaults(some), new_defaults)
991 self.assertEqual(some.__defaults__, new_defaults)
992
993 # `None` is special, it sets `defaults` to `NULL`,
994 # it needs special handling in `_testcapi`:
995 _testcapi.function_set_defaults(some, None)
996 self.assertEqual(_testcapi.function_get_defaults(some), None)
997 self.assertEqual(some.__defaults__, None)
998
999 def test_function_get_kw_defaults(self):
1000 def some(
1001 pos_only1, pos_only2='p',
1002 /,
1003 zero=0, optional=None,
1004 *,
1005 kw1,
1006 kw2=True,
1007 ):
1008 pass
1009
1010 defaults = _testcapi.function_get_kw_defaults(some)
1011 self.assertEqual(defaults, {'kw2': True})
1012 self.assertEqual(defaults, some.__kwdefaults__)
1013
1014 with self.assertRaises(SystemError):
1015 _testcapi.function_get_kw_defaults(None) # not a function
1016
1017 def test_function_set_kw_defaults(self):
1018 def some(
1019 pos_only1, pos_only2='p',
1020 /,
1021 zero=0, optional=None,
1022 *,
1023 kw1,
1024 kw2=True,
1025 ):
1026 pass
1027
1028 old_defaults = {'kw2': True}
1029 self.assertEqual(_testcapi.function_get_kw_defaults(some), old_defaults)
1030 self.assertEqual(some.__kwdefaults__, old_defaults)
1031
1032 with self.assertRaises(SystemError):
1033 _testcapi.function_set_kw_defaults(some, 1) # not dict or None
1034 self.assertEqual(_testcapi.function_get_kw_defaults(some), old_defaults)
1035 self.assertEqual(some.__kwdefaults__, old_defaults)
1036
1037 with self.assertRaises(SystemError):
1038 _testcapi.function_set_kw_defaults(1, {}) # not a function
1039 self.assertEqual(_testcapi.function_get_kw_defaults(some), old_defaults)
1040 self.assertEqual(some.__kwdefaults__, old_defaults)
1041
1042 new_defaults = {'kw2': (1, 2, 3)}
1043 _testcapi.function_set_kw_defaults(some, new_defaults)
1044 self.assertEqual(_testcapi.function_get_kw_defaults(some), new_defaults)
1045 self.assertEqual(some.__kwdefaults__, new_defaults)
1046
1047 # Empty dict is fine:
1048 new_defaults = {}
1049 _testcapi.function_set_kw_defaults(some, new_defaults)
1050 self.assertEqual(_testcapi.function_get_kw_defaults(some), new_defaults)
1051 self.assertEqual(some.__kwdefaults__, new_defaults)
1052
1053 class dictsub(dict): ... # dict subclasses must work
1054
1055 new_defaults = dictsub({'kw2': None})
1056 _testcapi.function_set_kw_defaults(some, new_defaults)
1057 self.assertEqual(_testcapi.function_get_kw_defaults(some), new_defaults)
1058 self.assertEqual(some.__kwdefaults__, new_defaults)
1059
1060 # `None` is special, it sets `kwdefaults` to `NULL`,
1061 # it needs special handling in `_testcapi`:
1062 _testcapi.function_set_kw_defaults(some, None)
1063 self.assertEqual(_testcapi.function_get_kw_defaults(some), None)
1064 self.assertEqual(some.__kwdefaults__, None)
1065
1066 def test_unstable_gc_new_with_extra_data(self):
1067 class Data(_testcapi.ObjExtraData):
1068 __slots__ = ('x', 'y')
1069
1070 d = Data()
1071 d.x = 10
1072 d.y = 20
1073 d.extra = 30
1074 self.assertEqual(d.x, 10)
1075 self.assertEqual(d.y, 20)
1076 self.assertEqual(d.extra, 30)
1077 del d.extra
1078 self.assertIsNone(d.extra)
1079
1080 def test_get_type_name(self):
1081 class MyType:
1082 pass
1083
1084 from _testcapi import (
1085 get_type_name, get_type_qualname,
1086 get_type_fullyqualname, get_type_module_name)
1087
1088 from collections import OrderedDict
1089 ht = _testcapi.get_heaptype_for_name()
1090 for cls, fullname, modname, qualname, name in (
1091 (int,
1092 'int',
1093 'builtins',
1094 'int',
1095 'int'),
1096 (OrderedDict,
1097 'collections.OrderedDict',
1098 'collections',
1099 'OrderedDict',
1100 'OrderedDict'),
1101 (ht,
1102 '_testcapi.HeapTypeNameType',
1103 '_testcapi',
1104 'HeapTypeNameType',
1105 'HeapTypeNameType'),
1106 (MyType,
1107 f'{__name__}.CAPITest.test_get_type_name.<locals>.MyType',
1108 __name__,
1109 'CAPITest.test_get_type_name.<locals>.MyType',
1110 'MyType'),
1111 ):
1112 with self.subTest(cls=repr(cls)):
1113 self.assertEqual(get_type_fullyqualname(cls), fullname)
1114 self.assertEqual(get_type_module_name(cls), modname)
1115 self.assertEqual(get_type_qualname(cls), qualname)
1116 self.assertEqual(get_type_name(cls), name)
1117
1118 # override __module__
1119 ht.__module__ = 'test_module'
1120 self.assertEqual(get_type_fullyqualname(ht), 'test_module.HeapTypeNameType')
1121 self.assertEqual(get_type_module_name(ht), 'test_module')
1122 self.assertEqual(get_type_qualname(ht), 'HeapTypeNameType')
1123 self.assertEqual(get_type_name(ht), 'HeapTypeNameType')
1124
1125 # override __name__ and __qualname__
1126 MyType.__name__ = 'my_name'
1127 MyType.__qualname__ = 'my_qualname'
1128 self.assertEqual(get_type_fullyqualname(MyType), f'{__name__}.my_qualname')
1129 self.assertEqual(get_type_module_name(MyType), __name__)
1130 self.assertEqual(get_type_qualname(MyType), 'my_qualname')
1131 self.assertEqual(get_type_name(MyType), 'my_name')
1132
1133 # override also __module__
1134 MyType.__module__ = 'my_module'
1135 self.assertEqual(get_type_fullyqualname(MyType), 'my_module.my_qualname')
1136 self.assertEqual(get_type_module_name(MyType), 'my_module')
1137 self.assertEqual(get_type_qualname(MyType), 'my_qualname')
1138 self.assertEqual(get_type_name(MyType), 'my_name')
1139
1140 # PyType_GetFullyQualifiedName() ignores the module if it's "builtins"
1141 # or "__main__" of it is not a string
1142 MyType.__module__ = 'builtins'
1143 self.assertEqual(get_type_fullyqualname(MyType), 'my_qualname')
1144 MyType.__module__ = '__main__'
1145 self.assertEqual(get_type_fullyqualname(MyType), 'my_qualname')
1146 MyType.__module__ = 123
1147 self.assertEqual(get_type_fullyqualname(MyType), 'my_qualname')
1148
1149
1150 def test_gen_get_code(self):
1151 def genf(): yield
1152 gen = genf()
1153 self.assertEqual(_testcapi.gen_get_code(gen), gen.gi_code)
1154
1155
1156 @requires_limited_api
1157 class TestHeapTypeRelative(unittest.TestCase):
1158 """Test API for extending opaque types (PEP 697)"""
1159
1160 @requires_limited_api
1161 def test_heaptype_relative_sizes(self):
1162 # Test subclassing using "relative" basicsize, see PEP 697
1163 def check(extra_base_size, extra_size):
1164 Base, Sub, instance, data_ptr, data_offset, data_size = (
1165 _testlimitedcapi.make_sized_heaptypes(
1166 extra_base_size, -extra_size))
1167
1168 # no alignment shenanigans when inheriting directly
1169 if extra_size == 0:
1170 self.assertEqual(Base.__basicsize__, Sub.__basicsize__)
1171 self.assertEqual(data_size, 0)
1172
1173 else:
1174 # The following offsets should be in increasing order:
1175 offsets = [
1176 (0, 'start of object'),
1177 (Base.__basicsize__, 'end of base data'),
1178 (data_offset, 'subclass data'),
1179 (data_offset + extra_size, 'end of requested subcls data'),
1180 (data_offset + data_size, 'end of reserved subcls data'),
1181 (Sub.__basicsize__, 'end of object'),
1182 ]
1183 ordered_offsets = sorted(offsets, key=operator.itemgetter(0))
1184 self.assertEqual(
1185 offsets, ordered_offsets,
1186 msg=f'Offsets not in expected order, got: {ordered_offsets}')
1187
1188 # end of reserved subcls data == end of object
1189 self.assertEqual(Sub.__basicsize__, data_offset + data_size)
1190
1191 # we don't reserve (requested + alignment) or more data
1192 self.assertLess(data_size - extra_size,
1193 _testlimitedcapi.ALIGNOF_MAX_ALIGN_T)
1194
1195 # The offsets/sizes we calculated should be aligned.
1196 self.assertEqual(data_offset % _testlimitedcapi.ALIGNOF_MAX_ALIGN_T, 0)
1197 self.assertEqual(data_size % _testlimitedcapi.ALIGNOF_MAX_ALIGN_T, 0)
1198
1199 sizes = sorted({0, 1, 2, 3, 4, 7, 8, 123,
1200 object.__basicsize__,
1201 object.__basicsize__-1,
1202 object.__basicsize__+1})
1203 for extra_base_size in sizes:
1204 for extra_size in sizes:
1205 args = dict(extra_base_size=extra_base_size,
1206 extra_size=extra_size)
1207 with self.subTest(**args):
1208 check(**args)
1209
1210 def test_HeapCCollection(self):
1211 """Make sure HeapCCollection works properly by itself"""
1212 collection = _testcapi.HeapCCollection(1, 2, 3)
1213 self.assertEqual(list(collection), [1, 2, 3])
1214
1215 def test_heaptype_inherit_itemsize(self):
1216 """Test HeapCCollection subclasses work properly"""
1217 sizes = sorted({0, 1, 2, 3, 4, 7, 8, 123,
1218 object.__basicsize__,
1219 object.__basicsize__-1,
1220 object.__basicsize__+1})
1221 for extra_size in sizes:
1222 with self.subTest(extra_size=extra_size):
1223 Sub = _testlimitedcapi.subclass_var_heaptype(
1224 _testcapi.HeapCCollection, -extra_size, 0, 0)
1225 collection = Sub(1, 2, 3)
1226 collection.set_data_to_3s()
1227
1228 self.assertEqual(list(collection), [1, 2, 3])
1229 mem = collection.get_data()
1230 self.assertGreaterEqual(len(mem), extra_size)
1231 self.assertTrue(set(mem) <= {3}, f'got {mem!r}')
1232
1233 def test_heaptype_invalid_inheritance(self):
1234 with self.assertRaises(SystemError,
1235 msg="Cannot extend variable-size class without "
1236 + "Py_TPFLAGS_ITEMS_AT_END"):
1237 _testlimitedcapi.subclass_heaptype(int, -8, 0)
1238
1239 def test_heaptype_relative_members(self):
1240 """Test HeapCCollection subclasses work properly"""
1241 sizes = sorted({0, 1, 2, 3, 4, 7, 8, 123,
1242 object.__basicsize__,
1243 object.__basicsize__-1,
1244 object.__basicsize__+1})
1245 for extra_base_size in sizes:
1246 for extra_size in sizes:
1247 for offset in sizes:
1248 with self.subTest(extra_base_size=extra_base_size, extra_size=extra_size, offset=offset):
1249 if offset < extra_size:
1250 Sub = _testlimitedcapi.make_heaptype_with_member(
1251 extra_base_size, -extra_size, offset, True)
1252 Base = Sub.mro()[1]
1253 instance = Sub()
1254 self.assertEqual(instance.memb, instance.get_memb())
1255 instance.set_memb(13)
1256 self.assertEqual(instance.memb, instance.get_memb())
1257 self.assertEqual(instance.get_memb(), 13)
1258 instance.memb = 14
1259 self.assertEqual(instance.memb, instance.get_memb())
1260 self.assertEqual(instance.get_memb(), 14)
1261 self.assertGreaterEqual(instance.get_memb_offset(), Base.__basicsize__)
1262 self.assertLess(instance.get_memb_offset(), Sub.__basicsize__)
1263 with self.assertRaises(SystemError):
1264 instance.get_memb_relative()
1265 with self.assertRaises(SystemError):
1266 instance.set_memb_relative(0)
1267 else:
1268 with self.assertRaises(SystemError):
1269 Sub = _testlimitedcapi.make_heaptype_with_member(
1270 extra_base_size, -extra_size, offset, True)
1271 with self.assertRaises(SystemError):
1272 Sub = _testlimitedcapi.make_heaptype_with_member(
1273 extra_base_size, extra_size, offset, True)
1274 with self.subTest(extra_base_size=extra_base_size, extra_size=extra_size):
1275 with self.assertRaises(SystemError):
1276 Sub = _testlimitedcapi.make_heaptype_with_member(
1277 extra_base_size, -extra_size, -1, True)
1278
1279 def test_heaptype_relative_members_errors(self):
1280 with self.assertRaisesRegex(
1281 SystemError,
1282 r"With Py_RELATIVE_OFFSET, basicsize must be negative"):
1283 _testlimitedcapi.make_heaptype_with_member(0, 1234, 0, True)
1284 with self.assertRaisesRegex(
1285 SystemError, r"Member offset out of range \(0\.\.-basicsize\)"):
1286 _testlimitedcapi.make_heaptype_with_member(0, -8, 1234, True)
1287 with self.assertRaisesRegex(
1288 SystemError, r"Member offset out of range \(0\.\.-basicsize\)"):
1289 _testlimitedcapi.make_heaptype_with_member(0, -8, -1, True)
1290
1291 Sub = _testlimitedcapi.make_heaptype_with_member(0, -8, 0, True)
1292 instance = Sub()
1293 with self.assertRaisesRegex(
1294 SystemError, r"PyMember_GetOne used with Py_RELATIVE_OFFSET"):
1295 instance.get_memb_relative()
1296 with self.assertRaisesRegex(
1297 SystemError, r"PyMember_SetOne used with Py_RELATIVE_OFFSET"):
1298 instance.set_memb_relative(0)
1299
1300 def test_pyobject_getitemdata_error(self):
1301 """Test PyObject_GetItemData fails on unsupported types"""
1302 with self.assertRaises(TypeError):
1303 # None is not variable-length
1304 _testcapi.pyobject_getitemdata(None)
1305 with self.assertRaises(TypeError):
1306 # int is variable-length, but doesn't have the
1307 # Py_TPFLAGS_ITEMS_AT_END layout (and flag)
1308 _testcapi.pyobject_getitemdata(0)
1309
1310
1311 def test_function_get_closure(self):
1312 from types import CellType
1313
1314 def regular_function(): ...
1315 def unused_one_level(arg1):
1316 def inner(arg2, arg3): ...
1317 return inner
1318 def unused_two_levels(arg1, arg2):
1319 def decorator(arg3, arg4):
1320 def inner(arg5, arg6): ...
1321 return inner
1322 return decorator
1323 def with_one_level(arg1):
1324 def inner(arg2, arg3):
1325 return arg1 + arg2 + arg3
1326 return inner
1327 def with_two_levels(arg1, arg2):
1328 def decorator(arg3, arg4):
1329 def inner(arg5, arg6):
1330 return arg1 + arg2 + arg3 + arg4 + arg5 + arg6
1331 return inner
1332 return decorator
1333
1334 # Functions without closures:
1335 self.assertIsNone(_testcapi.function_get_closure(regular_function))
1336 self.assertIsNone(regular_function.__closure__)
1337
1338 func = unused_one_level(1)
1339 closure = _testcapi.function_get_closure(func)
1340 self.assertIsNone(closure)
1341 self.assertIsNone(func.__closure__)
1342
1343 func = unused_two_levels(1, 2)(3, 4)
1344 closure = _testcapi.function_get_closure(func)
1345 self.assertIsNone(closure)
1346 self.assertIsNone(func.__closure__)
1347
1348 # Functions with closures:
1349 func = with_one_level(5)
1350 closure = _testcapi.function_get_closure(func)
1351 self.assertEqual(closure, func.__closure__)
1352 self.assertIsInstance(closure, tuple)
1353 self.assertEqual(len(closure), 1)
1354 self.assertEqual(len(closure), len(func.__code__.co_freevars))
1355 self.assertTrue(all(isinstance(cell, CellType) for cell in closure))
1356 self.assertTrue(closure[0].cell_contents, 5)
1357
1358 func = with_two_levels(1, 2)(3, 4)
1359 closure = _testcapi.function_get_closure(func)
1360 self.assertEqual(closure, func.__closure__)
1361 self.assertIsInstance(closure, tuple)
1362 self.assertEqual(len(closure), 4)
1363 self.assertEqual(len(closure), len(func.__code__.co_freevars))
1364 self.assertTrue(all(isinstance(cell, CellType) for cell in closure))
1365 self.assertEqual([cell.cell_contents for cell in closure],
1366 [1, 2, 3, 4])
1367
1368 def test_function_get_closure_error(self):
1369 with self.assertRaises(SystemError):
1370 _testcapi.function_get_closure(1)
1371 with self.assertRaises(SystemError):
1372 _testcapi.function_get_closure(None)
1373
1374 def test_function_set_closure(self):
1375 from types import CellType
1376
1377 def function_without_closure(): ...
1378 def function_with_closure(arg):
1379 def inner():
1380 return arg
1381 return inner
1382
1383 func = function_without_closure
1384 _testcapi.function_set_closure(func, (CellType(1), CellType(1)))
1385 closure = _testcapi.function_get_closure(func)
1386 self.assertEqual([c.cell_contents for c in closure], [1, 1])
1387 self.assertEqual([c.cell_contents for c in func.__closure__], [1, 1])
1388
1389 func = function_with_closure(1)
1390 _testcapi.function_set_closure(func,
1391 (CellType(1), CellType(2), CellType(3)))
1392 closure = _testcapi.function_get_closure(func)
1393 self.assertEqual([c.cell_contents for c in closure], [1, 2, 3])
1394 self.assertEqual([c.cell_contents for c in func.__closure__], [1, 2, 3])
1395
1396 def test_function_set_closure_none(self):
1397 def function_without_closure(): ...
1398 def function_with_closure(arg):
1399 def inner():
1400 return arg
1401 return inner
1402
1403 _testcapi.function_set_closure(function_without_closure, None)
1404 self.assertIsNone(
1405 _testcapi.function_get_closure(function_without_closure))
1406 self.assertIsNone(function_without_closure.__closure__)
1407
1408 _testcapi.function_set_closure(function_with_closure, None)
1409 self.assertIsNone(
1410 _testcapi.function_get_closure(function_with_closure))
1411 self.assertIsNone(function_with_closure.__closure__)
1412
1413 def test_function_set_closure_errors(self):
1414 def function_without_closure(): ...
1415
1416 with self.assertRaises(SystemError):
1417 _testcapi.function_set_closure(None, ()) # not a function
1418
1419 with self.assertRaises(SystemError):
1420 _testcapi.function_set_closure(function_without_closure, 1)
1421 self.assertIsNone(function_without_closure.__closure__) # no change
1422
1423 # NOTE: this works, but goes against the docs:
1424 _testcapi.function_set_closure(function_without_closure, (1, 2))
1425 self.assertEqual(
1426 _testcapi.function_get_closure(function_without_closure), (1, 2))
1427 self.assertEqual(function_without_closure.__closure__, (1, 2))
1428
1429
1430 class TestPendingCalls(unittest.TestCase):
1431
1432 # See the comment in ceval.c (at the "handle_eval_breaker" label)
1433 # about when pending calls get run. This is especially relevant
1434 # here for creating deterministic tests.
1435
1436 def main_pendingcalls_submit(self, l, n):
1437 def callback():
1438 #this function can be interrupted by thread switching so let's
1439 #use an atomic operation
1440 l.append(None)
1441
1442 for i in range(n):
1443 time.sleep(random.random()*0.02) #0.01 secs on average
1444 #try submitting callback until successful.
1445 #rely on regular interrupt to flush queue if we are
1446 #unsuccessful.
1447 while True:
1448 if _testcapi._pending_threadfunc(callback):
1449 break
1450
1451 def pendingcalls_submit(self, l, n, *, main=True, ensure=False):
1452 def callback():
1453 #this function can be interrupted by thread switching so let's
1454 #use an atomic operation
1455 l.append(None)
1456
1457 if main:
1458 return _testcapi._pending_threadfunc(callback, n,
1459 blocking=False,
1460 ensure_added=ensure)
1461 else:
1462 return _testinternalcapi.pending_threadfunc(callback, n,
1463 blocking=False,
1464 ensure_added=ensure)
1465
1466 def pendingcalls_wait(self, l, numadded, context = None):
1467 #now, stick around until l[0] has grown to 10
1468 count = 0
1469 while len(l) != numadded:
1470 #this busy loop is where we expect to be interrupted to
1471 #run our callbacks. Note that some callbacks are only run on the
1472 #main thread
1473 if False and support.verbose:
1474 print("(%i)"%(len(l),),)
1475 for i in range(1000):
1476 a = i*i
1477 if context and not context.event.is_set():
1478 continue
1479 count += 1
1480 self.assertTrue(count < 10000,
1481 "timeout waiting for %i callbacks, got %i"%(numadded, len(l)))
1482 if False and support.verbose:
1483 print("(%i)"%(len(l),))
1484
1485 @threading_helper.requires_working_threading()
1486 def test_main_pendingcalls_threaded(self):
1487
1488 #do every callback on a separate thread
1489 n = 32 #total callbacks
1490 threads = []
1491 class foo(object):pass
1492 context = foo()
1493 context.l = []
1494 context.n = 2 #submits per thread
1495 context.nThreads = n // context.n
1496 context.nFinished = 0
1497 context.lock = threading.Lock()
1498 context.event = threading.Event()
1499
1500 threads = [threading.Thread(target=self.main_pendingcalls_thread,
1501 args=(context,))
1502 for i in range(context.nThreads)]
1503 with threading_helper.start_threads(threads):
1504 self.pendingcalls_wait(context.l, n, context)
1505
1506 def main_pendingcalls_thread(self, context):
1507 try:
1508 self.main_pendingcalls_submit(context.l, context.n)
1509 finally:
1510 with context.lock:
1511 context.nFinished += 1
1512 nFinished = context.nFinished
1513 if False and support.verbose:
1514 print("finished threads: ", nFinished)
1515 if nFinished == context.nThreads:
1516 context.event.set()
1517
1518 def test_main_pendingcalls_non_threaded(self):
1519 #again, just using the main thread, likely they will all be dispatched at
1520 #once. It is ok to ask for too many, because we loop until we find a slot.
1521 #the loop can be interrupted to dispatch.
1522 #there are only 32 dispatch slots, so we go for twice that!
1523 l = []
1524 n = 64
1525 self.main_pendingcalls_submit(l, n)
1526 self.pendingcalls_wait(l, n)
1527
1528 def test_max_pending(self):
1529 with self.subTest('main-only'):
1530 maxpending = 32
1531
1532 l = []
1533 added = self.pendingcalls_submit(l, 1, main=True)
1534 self.pendingcalls_wait(l, added)
1535 self.assertEqual(added, 1)
1536
1537 l = []
1538 added = self.pendingcalls_submit(l, maxpending, main=True)
1539 self.pendingcalls_wait(l, added)
1540 self.assertEqual(added, maxpending)
1541
1542 l = []
1543 added = self.pendingcalls_submit(l, maxpending+1, main=True)
1544 self.pendingcalls_wait(l, added)
1545 self.assertEqual(added, maxpending)
1546
1547 with self.subTest('not main-only'):
1548 # Per-interpreter pending calls has a much higher limit
1549 # on how many may be pending at a time.
1550 maxpending = 300
1551
1552 l = []
1553 added = self.pendingcalls_submit(l, 1, main=False)
1554 self.pendingcalls_wait(l, added)
1555 self.assertEqual(added, 1)
1556
1557 l = []
1558 added = self.pendingcalls_submit(l, maxpending, main=False)
1559 self.pendingcalls_wait(l, added)
1560 self.assertEqual(added, maxpending)
1561
1562 l = []
1563 added = self.pendingcalls_submit(l, maxpending+1, main=False)
1564 self.pendingcalls_wait(l, added)
1565 self.assertEqual(added, maxpending)
1566
1567 class PendingTask(types.SimpleNamespace):
1568
1569 _add_pending = _testinternalcapi.pending_threadfunc
1570
1571 def __init__(self, req, taskid=None, notify_done=None):
1572 self.id = taskid
1573 self.req = req
1574 self.notify_done = notify_done
1575
1576 self.creator_tid = threading.get_ident()
1577 self.requester_tid = None
1578 self.runner_tid = None
1579 self.result = None
1580
1581 def run(self):
1582 assert self.result is None
1583 self.runner_tid = threading.get_ident()
1584 self._run()
1585 if self.notify_done is not None:
1586 self.notify_done()
1587
1588 def _run(self):
1589 self.result = self.req
1590
1591 def run_in_pending_call(self, worker_tids):
1592 assert self._add_pending is _testinternalcapi.pending_threadfunc
1593 self.requester_tid = threading.get_ident()
1594 def callback():
1595 assert self.result is None
1596 # It can be tricky to control which thread handles
1597 # the eval breaker, so we take a naive approach to
1598 # make sure.
1599 if threading.get_ident() not in worker_tids:
1600 self._add_pending(callback, ensure_added=True)
1601 return
1602 self.run()
1603 self._add_pending(callback, ensure_added=True)
1604
1605 def create_thread(self, worker_tids):
1606 return threading.Thread(
1607 target=self.run_in_pending_call,
1608 args=(worker_tids,),
1609 )
1610
1611 def wait_for_result(self):
1612 while self.result is None:
1613 time.sleep(0.01)
1614
1615 @threading_helper.requires_working_threading()
1616 def test_subthreads_can_handle_pending_calls(self):
1617 payload = 'Spam spam spam spam. Lovely spam! Wonderful spam!'
1618
1619 task = self.PendingTask(payload)
1620 def do_the_work():
1621 tid = threading.get_ident()
1622 t = task.create_thread({tid})
1623 with threading_helper.start_threads([t]):
1624 task.wait_for_result()
1625 t = threading.Thread(target=do_the_work)
1626 with threading_helper.start_threads([t]):
1627 pass
1628
1629 self.assertEqual(task.result, payload)
1630
1631 @threading_helper.requires_working_threading()
1632 def test_many_subthreads_can_handle_pending_calls(self):
1633 main_tid = threading.get_ident()
1634 self.assertEqual(threading.main_thread().ident, main_tid)
1635
1636 # We can't use queue.Queue since it isn't reentrant relative
1637 # to pending calls.
1638 _queue = deque()
1639 _active = deque()
1640 _done_lock = threading.Lock()
1641 def queue_put(task):
1642 _queue.append(task)
1643 _active.append(True)
1644 def queue_get():
1645 try:
1646 task = _queue.popleft()
1647 except IndexError:
1648 raise queue.Empty
1649 return task
1650 def queue_task_done():
1651 _active.pop()
1652 if not _active:
1653 try:
1654 _done_lock.release()
1655 except RuntimeError:
1656 assert not _done_lock.locked()
1657 def queue_empty():
1658 return not _queue
1659 def queue_join():
1660 _done_lock.acquire()
1661 _done_lock.release()
1662
1663 tasks = []
1664 for i in range(20):
1665 task = self.PendingTask(
1666 req=f'request {i}',
1667 taskid=i,
1668 notify_done=queue_task_done,
1669 )
1670 tasks.append(task)
1671 queue_put(task)
1672 # This will be released once all the tasks have finished.
1673 _done_lock.acquire()
1674
1675 def add_tasks(worker_tids):
1676 while True:
1677 if done:
1678 return
1679 try:
1680 task = queue_get()
1681 except queue.Empty:
1682 break
1683 task.run_in_pending_call(worker_tids)
1684
1685 done = False
1686 def run_tasks():
1687 while not queue_empty():
1688 if done:
1689 return
1690 time.sleep(0.01)
1691 # Give the worker a chance to handle any remaining pending calls.
1692 while not done:
1693 time.sleep(0.01)
1694
1695 # Start the workers and wait for them to finish.
1696 worker_threads = [threading.Thread(target=run_tasks)
1697 for _ in range(3)]
1698 with threading_helper.start_threads(worker_threads):
1699 try:
1700 # Add a pending call for each task.
1701 worker_tids = [t.ident for t in worker_threads]
1702 threads = [threading.Thread(target=add_tasks, args=(worker_tids,))
1703 for _ in range(3)]
1704 with threading_helper.start_threads(threads):
1705 try:
1706 pass
1707 except BaseException:
1708 done = True
1709 raise # re-raise
1710 # Wait for the pending calls to finish.
1711 queue_join()
1712 # Notify the workers that they can stop.
1713 done = True
1714 except BaseException:
1715 done = True
1716 raise # re-raise
1717 runner_tids = [t.runner_tid for t in tasks]
1718
1719 self.assertNotIn(main_tid, runner_tids)
1720 for task in tasks:
1721 with self.subTest(f'task {task.id}'):
1722 self.assertNotEqual(task.requester_tid, main_tid)
1723 self.assertNotEqual(task.requester_tid, task.runner_tid)
1724 self.assertNotIn(task.requester_tid, runner_tids)
1725
1726 @requires_subinterpreters
1727 def test_isolated_subinterpreter(self):
1728 # We exercise the most important permutations.
1729
1730 # This test relies on pending calls getting called
1731 # (eval breaker tripped) at each loop iteration
1732 # and at each call.
1733
1734 maxtext = 250
1735 main_interpid = 0
1736 interpid = _interpreters.create()
1737 self.addCleanup(lambda: _interpreters.destroy(interpid))
1738 _interpreters.run_string(interpid, f"""if True:
1739 import json
1740 import os
1741 import threading
1742 import time
1743 import _testinternalcapi
1744 from test.support import threading_helper
1745 """)
1746
1747 def create_pipe():
1748 r, w = os.pipe()
1749 self.addCleanup(lambda: os.close(r))
1750 self.addCleanup(lambda: os.close(w))
1751 return r, w
1752
1753 with self.subTest('add in main, run in subinterpreter'):
1754 r_ready, w_ready = create_pipe()
1755 r_done, w_done= create_pipe()
1756 timeout = time.time() + 30 # seconds
1757
1758 def do_work():
1759 _interpreters.run_string(interpid, f"""if True:
1760 # Wait until this interp has handled the pending call.
1761 waiting = False
1762 done = False
1763 def wait(os_read=os.read):
1764 global done, waiting
1765 waiting = True
1766 os_read({r_done}, 1)
1767 done = True
1768 t = threading.Thread(target=wait)
1769 with threading_helper.start_threads([t]):
1770 while not waiting:
1771 pass
1772 os.write({w_ready}, b'\\0')
1773 # Loop to trigger the eval breaker.
1774 while not done:
1775 time.sleep(0.01)
1776 if time.time() > {timeout}:
1777 raise Exception('timed out!')
1778 """)
1779 t = threading.Thread(target=do_work)
1780 with threading_helper.start_threads([t]):
1781 os.read(r_ready, 1)
1782 # Add the pending call and wait for it to finish.
1783 actual = _testinternalcapi.pending_identify(interpid)
1784 # Signal the subinterpreter to stop.
1785 os.write(w_done, b'\0')
1786
1787 self.assertEqual(actual, int(interpid))
1788
1789 with self.subTest('add in main, run in subinterpreter sub-thread'):
1790 r_ready, w_ready = create_pipe()
1791 r_done, w_done= create_pipe()
1792 timeout = time.time() + 30 # seconds
1793
1794 def do_work():
1795 _interpreters.run_string(interpid, f"""if True:
1796 waiting = False
1797 done = False
1798 def subthread():
1799 while not waiting:
1800 pass
1801 os.write({w_ready}, b'\\0')
1802 # Loop to trigger the eval breaker.
1803 while not done:
1804 time.sleep(0.01)
1805 if time.time() > {timeout}:
1806 raise Exception('timed out!')
1807 t = threading.Thread(target=subthread)
1808 with threading_helper.start_threads([t]):
1809 # Wait until this interp has handled the pending call.
1810 waiting = True
1811 os.read({r_done}, 1)
1812 done = True
1813 """)
1814 t = threading.Thread(target=do_work)
1815 with threading_helper.start_threads([t]):
1816 os.read(r_ready, 1)
1817 # Add the pending call and wait for it to finish.
1818 actual = _testinternalcapi.pending_identify(interpid)
1819 # Signal the subinterpreter to stop.
1820 os.write(w_done, b'\0')
1821
1822 self.assertEqual(actual, int(interpid))
1823
1824 with self.subTest('add in subinterpreter, run in main'):
1825 r_ready, w_ready = create_pipe()
1826 r_done, w_done= create_pipe()
1827 r_data, w_data= create_pipe()
1828 timeout = time.time() + 30 # seconds
1829
1830 def add_job():
1831 os.read(r_ready, 1)
1832 _interpreters.run_string(interpid, f"""if True:
1833 # Add the pending call and wait for it to finish.
1834 actual = _testinternalcapi.pending_identify({main_interpid})
1835 # Signal the subinterpreter to stop.
1836 os.write({w_done}, b'\\0')
1837 os.write({w_data}, actual.to_bytes(1, 'little'))
1838 """)
1839 # Wait until this interp has handled the pending call.
1840 waiting = False
1841 done = False
1842 def wait(os_read=os.read):
1843 nonlocal done, waiting
1844 waiting = True
1845 os_read(r_done, 1)
1846 done = True
1847 t1 = threading.Thread(target=add_job)
1848 t2 = threading.Thread(target=wait)
1849 with threading_helper.start_threads([t1, t2]):
1850 while not waiting:
1851 pass
1852 os.write(w_ready, b'\0')
1853 # Loop to trigger the eval breaker.
1854 while not done:
1855 time.sleep(0.01)
1856 if time.time() > timeout:
1857 raise Exception('timed out!')
1858 text = os.read(r_data, 1)
1859 actual = int.from_bytes(text, 'little')
1860
1861 self.assertEqual(actual, int(main_interpid))
1862
1863 with self.subTest('add in subinterpreter, run in sub-thread'):
1864 r_ready, w_ready = create_pipe()
1865 r_done, w_done= create_pipe()
1866 r_data, w_data= create_pipe()
1867 timeout = time.time() + 30 # seconds
1868
1869 def add_job():
1870 os.read(r_ready, 1)
1871 _interpreters.run_string(interpid, f"""if True:
1872 # Add the pending call and wait for it to finish.
1873 actual = _testinternalcapi.pending_identify({main_interpid})
1874 # Signal the subinterpreter to stop.
1875 os.write({w_done}, b'\\0')
1876 os.write({w_data}, actual.to_bytes(1, 'little'))
1877 """)
1878 # Wait until this interp has handled the pending call.
1879 waiting = False
1880 done = False
1881 def wait(os_read=os.read):
1882 nonlocal done, waiting
1883 waiting = True
1884 os_read(r_done, 1)
1885 done = True
1886 def subthread():
1887 while not waiting:
1888 pass
1889 os.write(w_ready, b'\0')
1890 # Loop to trigger the eval breaker.
1891 while not done:
1892 time.sleep(0.01)
1893 if time.time() > timeout:
1894 raise Exception('timed out!')
1895 t1 = threading.Thread(target=add_job)
1896 t2 = threading.Thread(target=wait)
1897 t3 = threading.Thread(target=subthread)
1898 with threading_helper.start_threads([t1, t2, t3]):
1899 pass
1900 text = os.read(r_data, 1)
1901 actual = int.from_bytes(text, 'little')
1902
1903 self.assertEqual(actual, int(main_interpid))
1904
1905 # XXX We can't use the rest until gh-105716 is fixed.
1906 return
1907
1908 with self.subTest('add in subinterpreter, run in subinterpreter sub-thread'):
1909 r_ready, w_ready = create_pipe()
1910 r_done, w_done= create_pipe()
1911 r_data, w_data= create_pipe()
1912 timeout = time.time() + 30 # seconds
1913
1914 def do_work():
1915 _interpreters.run_string(interpid, f"""if True:
1916 waiting = False
1917 done = False
1918 def subthread():
1919 while not waiting:
1920 pass
1921 os.write({w_ready}, b'\\0')
1922 # Loop to trigger the eval breaker.
1923 while not done:
1924 time.sleep(0.01)
1925 if time.time() > {timeout}:
1926 raise Exception('timed out!')
1927 t = threading.Thread(target=subthread)
1928 with threading_helper.start_threads([t]):
1929 # Wait until this interp has handled the pending call.
1930 waiting = True
1931 os.read({r_done}, 1)
1932 done = True
1933 """)
1934 t = threading.Thread(target=do_work)
1935 #with threading_helper.start_threads([t]):
1936 t.start()
1937 if True:
1938 os.read(r_ready, 1)
1939 _interpreters.run_string(interpid, f"""if True:
1940 # Add the pending call and wait for it to finish.
1941 actual = _testinternalcapi.pending_identify({interpid})
1942 # Signal the subinterpreter to stop.
1943 os.write({w_done}, b'\\0')
1944 os.write({w_data}, actual.to_bytes(1, 'little'))
1945 """)
1946 t.join()
1947 text = os.read(r_data, 1)
1948 actual = int.from_bytes(text, 'little')
1949
1950 self.assertEqual(actual, int(interpid))
1951
1952
1953 class SubinterpreterTest(unittest.TestCase):
1954
1955 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
1956 def test_subinterps(self):
1957 import builtins
1958 r, w = os.pipe()
1959 code = """if 1:
1960 import sys, builtins, pickle
1961 with open({:d}, "wb") as f:
1962 pickle.dump(id(sys.modules), f)
1963 pickle.dump(id(builtins), f)
1964 """.format(w)
1965 with open(r, "rb") as f:
1966 ret = support.run_in_subinterp(code)
1967 self.assertEqual(ret, 0)
1968 self.assertNotEqual(pickle.load(f), id(sys.modules))
1969 self.assertNotEqual(pickle.load(f), id(builtins))
1970
1971 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
1972 def test_subinterps_recent_language_features(self):
1973 r, w = os.pipe()
1974 code = """if 1:
1975 import pickle
1976 with open({:d}, "wb") as f:
1977
1978 @(lambda x:x) # Py 3.9
1979 def noop(x): return x
1980
1981 a = (b := f'1{{2}}3') + noop('x') # Py 3.8 (:=) / 3.6 (f'')
1982
1983 async def foo(arg): return await arg # Py 3.5
1984
1985 pickle.dump(dict(a=a, b=b), f)
1986 """.format(w)
1987
1988 with open(r, "rb") as f:
1989 ret = support.run_in_subinterp(code)
1990 self.assertEqual(ret, 0)
1991 self.assertEqual(pickle.load(f), {'a': '123x', 'b': '123'})
1992
1993 def test_py_config_isoloated_per_interpreter(self):
1994 # A config change in one interpreter must not leak to out to others.
1995 #
1996 # This test could verify ANY config value, it just happens to have been
1997 # written around the time of int_max_str_digits. Refactoring is okay.
1998 code = """if 1:
1999 import sys, _testinternalcapi
2000
2001 # Any config value would do, this happens to be the one being
2002 # double checked at the time this test was written.
2003 config = _testinternalcapi.get_config()
2004 config['int_max_str_digits'] = 55555
2005 config['parse_argv'] = 0
2006 _testinternalcapi.set_config(config)
2007 sub_value = _testinternalcapi.get_config()['int_max_str_digits']
2008 assert sub_value == 55555, sub_value
2009 """
2010 before_config = _testinternalcapi.get_config()
2011 assert before_config['int_max_str_digits'] != 55555
2012 self.assertEqual(support.run_in_subinterp(code), 0,
2013 'subinterp code failure, check stderr.')
2014 after_config = _testinternalcapi.get_config()
2015 self.assertIsNot(
2016 before_config, after_config,
2017 "Expected get_config() to return a new dict on each call")
2018 self.assertEqual(before_config, after_config,
2019 "CAUTION: Tests executed after this may be "
2020 "running under an altered config.")
2021 # try:...finally: calling set_config(before_config) not done
2022 # as that results in sys.argv, sys.path, and sys.warnoptions
2023 # "being modified by test_capi" per test.regrtest. So if this
2024 # test fails, assume that the environment in this process may
2025 # be altered and suspect.
2026
2027 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
2028 def test_configured_settings(self):
2029 """
2030 The config with which an interpreter is created corresponds
2031 1-to-1 with the new interpreter's settings. This test verifies
2032 that they match.
2033 """
2034
2035 OBMALLOC = 1<<5
2036 EXTENSIONS = 1<<8
2037 THREADS = 1<<10
2038 DAEMON_THREADS = 1<<11
2039 FORK = 1<<15
2040 EXEC = 1<<16
2041 ALL_FLAGS = (OBMALLOC | FORK | EXEC | THREADS | DAEMON_THREADS
2042 | EXTENSIONS);
2043
2044 features = [
2045 'obmalloc',
2046 'fork',
2047 'exec',
2048 'threads',
2049 'daemon_threads',
2050 'extensions',
2051 'own_gil',
2052 ]
2053 kwlist = [f'allow_{n}' for n in features]
2054 kwlist[0] = 'use_main_obmalloc'
2055 kwlist[-2] = 'check_multi_interp_extensions'
2056 kwlist[-1] = 'own_gil'
2057
2058 expected_to_work = {
2059 (True, True, True, True, True, True, True):
2060 (ALL_FLAGS, True),
2061 (True, False, False, False, False, False, False):
2062 (OBMALLOC, False),
2063 (False, False, False, True, False, True, False):
2064 (THREADS | EXTENSIONS, False),
2065 }
2066
2067 expected_to_fail = {
2068 (False, False, False, False, False, False, False),
2069 }
2070
2071 # gh-117649: The free-threaded build does not currently allow
2072 # setting check_multi_interp_extensions to False.
2073 if Py_GIL_DISABLED:
2074 for config in list(expected_to_work.keys()):
2075 kwargs = dict(zip(kwlist, config))
2076 if not kwargs['check_multi_interp_extensions']:
2077 del expected_to_work[config]
2078 expected_to_fail.add(config)
2079
2080 # expected to work
2081 for config, expected in expected_to_work.items():
2082 kwargs = dict(zip(kwlist, config))
2083 exp_flags, exp_gil = expected
2084 expected = {
2085 'feature_flags': exp_flags,
2086 'own_gil': exp_gil,
2087 }
2088 with self.subTest(config):
2089 r, w = os.pipe()
2090 script = textwrap.dedent(f'''
2091 import _testinternalcapi, json, os
2092 settings = _testinternalcapi.get_interp_settings()
2093 with os.fdopen({w}, "w") as stdin:
2094 json.dump(settings, stdin)
2095 ''')
2096 with os.fdopen(r) as stdout:
2097 ret = support.run_in_subinterp_with_config(script, **kwargs)
2098 self.assertEqual(ret, 0)
2099 out = stdout.read()
2100 settings = json.loads(out)
2101
2102 self.assertEqual(settings, expected)
2103
2104 # expected to fail
2105 for config in expected_to_fail:
2106 kwargs = dict(zip(kwlist, config))
2107 with self.subTest(config):
2108 script = textwrap.dedent(f'''
2109 import _testinternalcapi
2110 _testinternalcapi.get_interp_settings()
2111 raise NotImplementedError('unreachable')
2112 ''')
2113 with self.assertRaises(_interpreters.InterpreterError):
2114 support.run_in_subinterp_with_config(script, **kwargs)
2115
2116 @unittest.skipIf(_testsinglephase is None, "test requires _testsinglephase module")
2117 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
2118 # gh-117649: The free-threaded build does not currently allow overriding
2119 # the check_multi_interp_extensions setting.
2120 @expected_failure_if_gil_disabled()
2121 def test_overridden_setting_extensions_subinterp_check(self):
2122 """
2123 PyInterpreterConfig.check_multi_interp_extensions can be overridden
2124 with PyInterpreterState.override_multi_interp_extensions_check.
2125 This verifies that the override works but does not modify
2126 the underlying setting.
2127 """
2128
2129 OBMALLOC = 1<<5
2130 EXTENSIONS = 1<<8
2131 THREADS = 1<<10
2132 DAEMON_THREADS = 1<<11
2133 FORK = 1<<15
2134 EXEC = 1<<16
2135 BASE_FLAGS = OBMALLOC | FORK | EXEC | THREADS | DAEMON_THREADS
2136 base_kwargs = {
2137 'use_main_obmalloc': True,
2138 'allow_fork': True,
2139 'allow_exec': True,
2140 'allow_threads': True,
2141 'allow_daemon_threads': True,
2142 'own_gil': False,
2143 }
2144
2145 def check(enabled, override):
2146 kwargs = dict(
2147 base_kwargs,
2148 check_multi_interp_extensions=enabled,
2149 )
2150 flags = BASE_FLAGS | EXTENSIONS if enabled else BASE_FLAGS
2151 settings = {
2152 'feature_flags': flags,
2153 'own_gil': False,
2154 }
2155
2156 expected = {
2157 'requested': override,
2158 'override__initial': 0,
2159 'override_after': override,
2160 'override_restored': 0,
2161 # The override should not affect the config or settings.
2162 'settings__initial': settings,
2163 'settings_after': settings,
2164 'settings_restored': settings,
2165 # These are the most likely values to be wrong.
2166 'allowed__initial': not enabled,
2167 'allowed_after': not ((override > 0) if override else enabled),
2168 'allowed_restored': not enabled,
2169 }
2170
2171 r, w = os.pipe()
2172 if Py_GIL_DISABLED:
2173 # gh-117649: The test fails before `w` is closed
2174 self.addCleanup(os.close, w)
2175 script = textwrap.dedent(f'''
2176 from test.test_capi.check_config import run_singlephase_check
2177 run_singlephase_check({override}, {w})
2178 ''')
2179 with os.fdopen(r) as stdout:
2180 ret = support.run_in_subinterp_with_config(script, **kwargs)
2181 self.assertEqual(ret, 0)
2182 out = stdout.read()
2183 results = json.loads(out)
2184
2185 self.assertEqual(results, expected)
2186
2187 self.maxDiff = None
2188
2189 # setting: check disabled
2190 with self.subTest('config: check disabled; override: disabled'):
2191 check(False, -1)
2192 with self.subTest('config: check disabled; override: use config'):
2193 check(False, 0)
2194 with self.subTest('config: check disabled; override: enabled'):
2195 check(False, 1)
2196
2197 # setting: check enabled
2198 with self.subTest('config: check enabled; override: disabled'):
2199 check(True, -1)
2200 with self.subTest('config: check enabled; override: use config'):
2201 check(True, 0)
2202 with self.subTest('config: check enabled; override: enabled'):
2203 check(True, 1)
2204
2205 def test_mutate_exception(self):
2206 """
2207 Exceptions saved in global module state get shared between
2208 individual module instances. This test checks whether or not
2209 a change in one interpreter's module gets reflected into the
2210 other ones.
2211 """
2212 import binascii
2213
2214 support.run_in_subinterp("import binascii; binascii.Error.foobar = 'foobar'")
2215
2216 self.assertFalse(hasattr(binascii.Error, "foobar"))
2217
2218 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
2219 # gh-117649: The free-threaded build does not currently support sharing
2220 # extension module state between interpreters.
2221 @expected_failure_if_gil_disabled()
2222 def test_module_state_shared_in_global(self):
2223 """
2224 bpo-44050: Extension module state should be shared between interpreters
2225 when it doesn't support sub-interpreters.
2226 """
2227 r, w = os.pipe()
2228 self.addCleanup(os.close, r)
2229 self.addCleanup(os.close, w)
2230
2231 # Apple extensions must be distributed as frameworks. This requires
2232 # a specialist loader.
2233 if support.is_apple_mobile:
2234 loader = "AppleFrameworkLoader"
2235 else:
2236 loader = "ExtensionFileLoader"
2237
2238 script = textwrap.dedent(f"""
2239 import importlib.machinery
2240 import importlib.util
2241 import os
2242
2243 fullname = '_test_module_state_shared'
2244 origin = importlib.util.find_spec('_testmultiphase').origin
2245 loader = importlib.machinery.{loader}(fullname, origin)
2246 spec = importlib.util.spec_from_loader(fullname, loader)
2247 module = importlib.util.module_from_spec(spec)
2248 attr_id = str(id(module.Error)).encode()
2249
2250 os.write({w}, attr_id)
2251 """)
2252 exec(script)
2253 main_attr_id = os.read(r, 100)
2254
2255 ret = support.run_in_subinterp(script)
2256 self.assertEqual(ret, 0)
2257 subinterp_attr_id = os.read(r, 100)
2258 self.assertEqual(main_attr_id, subinterp_attr_id)
2259
2260
2261 @requires_subinterpreters
2262 class InterpreterConfigTests(unittest.TestCase):
2263
2264 supported = {
2265 'isolated': types.SimpleNamespace(
2266 use_main_obmalloc=False,
2267 allow_fork=False,
2268 allow_exec=False,
2269 allow_threads=True,
2270 allow_daemon_threads=False,
2271 check_multi_interp_extensions=True,
2272 gil='own',
2273 ),
2274 'legacy': types.SimpleNamespace(
2275 use_main_obmalloc=True,
2276 allow_fork=True,
2277 allow_exec=True,
2278 allow_threads=True,
2279 allow_daemon_threads=True,
2280 check_multi_interp_extensions=bool(Py_GIL_DISABLED),
2281 gil='shared',
2282 ),
2283 'empty': types.SimpleNamespace(
2284 use_main_obmalloc=False,
2285 allow_fork=False,
2286 allow_exec=False,
2287 allow_threads=False,
2288 allow_daemon_threads=False,
2289 check_multi_interp_extensions=False,
2290 gil='default',
2291 ),
2292 }
2293 gil_supported = ['default', 'shared', 'own']
2294
2295 def iter_all_configs(self):
2296 for use_main_obmalloc in (True, False):
2297 for allow_fork in (True, False):
2298 for allow_exec in (True, False):
2299 for allow_threads in (True, False):
2300 for allow_daemon in (True, False):
2301 for checkext in (True, False):
2302 for gil in ('shared', 'own', 'default'):
2303 yield types.SimpleNamespace(
2304 use_main_obmalloc=use_main_obmalloc,
2305 allow_fork=allow_fork,
2306 allow_exec=allow_exec,
2307 allow_threads=allow_threads,
2308 allow_daemon_threads=allow_daemon,
2309 check_multi_interp_extensions=checkext,
2310 gil=gil,
2311 )
2312
2313 def assert_ns_equal(self, ns1, ns2, msg=None):
2314 # This is mostly copied from TestCase.assertDictEqual.
2315 self.assertEqual(type(ns1), type(ns2))
2316 if ns1 == ns2:
2317 return
2318
2319 import difflib
2320 import pprint
2321 from unittest.util import _common_shorten_repr
2322 standardMsg = '%s != %s' % _common_shorten_repr(ns1, ns2)
2323 diff = ('\n' + '\n'.join(difflib.ndiff(
2324 pprint.pformat(vars(ns1)).splitlines(),
2325 pprint.pformat(vars(ns2)).splitlines())))
2326 diff = f'namespace({diff})'
2327 standardMsg = self._truncateMessage(standardMsg, diff)
2328 self.fail(self._formatMessage(msg, standardMsg))
2329
2330 def test_predefined_config(self):
2331 def check(name, expected):
2332 expected = self.supported[expected]
2333 args = (name,) if name else ()
2334
2335 config1 = _interpreters.new_config(*args)
2336 self.assert_ns_equal(config1, expected)
2337 self.assertIsNot(config1, expected)
2338
2339 config2 = _interpreters.new_config(*args)
2340 self.assert_ns_equal(config2, expected)
2341 self.assertIsNot(config2, expected)
2342 self.assertIsNot(config2, config1)
2343
2344 with self.subTest('default'):
2345 check(None, 'isolated')
2346
2347 for name in self.supported:
2348 with self.subTest(name):
2349 check(name, name)
2350
2351 def test_update_from_dict(self):
2352 for name, vanilla in self.supported.items():
2353 with self.subTest(f'noop ({name})'):
2354 expected = vanilla
2355 overrides = vars(vanilla)
2356 config = _interpreters.new_config(name, **overrides)
2357 self.assert_ns_equal(config, expected)
2358
2359 with self.subTest(f'change all ({name})'):
2360 overrides = {k: not v for k, v in vars(vanilla).items()}
2361 for gil in self.gil_supported:
2362 if vanilla.gil == gil:
2363 continue
2364 overrides['gil'] = gil
2365 expected = types.SimpleNamespace(**overrides)
2366 config = _interpreters.new_config(
2367 name, **overrides)
2368 self.assert_ns_equal(config, expected)
2369
2370 # Override individual fields.
2371 for field, old in vars(vanilla).items():
2372 if field == 'gil':
2373 values = [v for v in self.gil_supported if v != old]
2374 else:
2375 values = [not old]
2376 for val in values:
2377 with self.subTest(f'{name}.{field} ({old!r} -> {val!r})'):
2378 overrides = {field: val}
2379 expected = types.SimpleNamespace(
2380 **dict(vars(vanilla), **overrides),
2381 )
2382 config = _interpreters.new_config(
2383 name, **overrides)
2384 self.assert_ns_equal(config, expected)
2385
2386 with self.subTest('unsupported field'):
2387 for name in self.supported:
2388 with self.assertRaises(ValueError):
2389 _interpreters.new_config(name, spam=True)
2390
2391 # Bad values for bool fields.
2392 for field, value in vars(self.supported['empty']).items():
2393 if field == 'gil':
2394 continue
2395 assert isinstance(value, bool)
2396 for value in [1, '', 'spam', 1.0, None, object()]:
2397 with self.subTest(f'unsupported value ({field}={value!r})'):
2398 with self.assertRaises(TypeError):
2399 _interpreters.new_config(**{field: value})
2400
2401 # Bad values for .gil.
2402 for value in [True, 1, 1.0, None, object()]:
2403 with self.subTest(f'unsupported value(gil={value!r})'):
2404 with self.assertRaises(TypeError):
2405 _interpreters.new_config(gil=value)
2406 for value in ['', 'spam']:
2407 with self.subTest(f'unsupported value (gil={value!r})'):
2408 with self.assertRaises(ValueError):
2409 _interpreters.new_config(gil=value)
2410
2411 def test_interp_init(self):
2412 questionable = [
2413 # strange
2414 dict(
2415 allow_fork=True,
2416 allow_exec=False,
2417 ),
2418 dict(
2419 gil='shared',
2420 use_main_obmalloc=False,
2421 ),
2422 # risky
2423 dict(
2424 allow_fork=True,
2425 allow_threads=True,
2426 ),
2427 # ought to be invalid?
2428 dict(
2429 allow_threads=False,
2430 allow_daemon_threads=True,
2431 ),
2432 dict(
2433 gil='own',
2434 use_main_obmalloc=True,
2435 ),
2436 ]
2437 invalid = [
2438 dict(
2439 use_main_obmalloc=False,
2440 check_multi_interp_extensions=False
2441 ),
2442 ]
2443 if Py_GIL_DISABLED:
2444 invalid.append(dict(check_multi_interp_extensions=False))
2445 def match(config, override_cases):
2446 ns = vars(config)
2447 for overrides in override_cases:
2448 if dict(ns, **overrides) == ns:
2449 return True
2450 return False
2451
2452 def check(config):
2453 script = 'pass'
2454 rc = _testinternalcapi.run_in_subinterp_with_config(script, config)
2455 self.assertEqual(rc, 0)
2456
2457 for config in self.iter_all_configs():
2458 if config.gil == 'default':
2459 continue
2460 if match(config, invalid):
2461 with self.subTest(f'invalid: {config}'):
2462 with self.assertRaises(_interpreters.InterpreterError):
2463 check(config)
2464 elif match(config, questionable):
2465 with self.subTest(f'questionable: {config}'):
2466 check(config)
2467 else:
2468 with self.subTest(f'valid: {config}'):
2469 check(config)
2470
2471 def test_get_config(self):
2472 @contextlib.contextmanager
2473 def new_interp(config):
2474 interpid = _interpreters.create(config, reqrefs=False)
2475 try:
2476 yield interpid
2477 finally:
2478 try:
2479 _interpreters.destroy(interpid)
2480 except _interpreters.InterpreterNotFoundError:
2481 pass
2482
2483 with self.subTest('main'):
2484 expected = _interpreters.new_config('legacy')
2485 expected.gil = 'own'
2486 if Py_GIL_DISABLED:
2487 expected.check_multi_interp_extensions = False
2488 interpid, *_ = _interpreters.get_main()
2489 config = _interpreters.get_config(interpid)
2490 self.assert_ns_equal(config, expected)
2491
2492 with self.subTest('isolated'):
2493 expected = _interpreters.new_config('isolated')
2494 with new_interp('isolated') as interpid:
2495 config = _interpreters.get_config(interpid)
2496 self.assert_ns_equal(config, expected)
2497
2498 with self.subTest('legacy'):
2499 expected = _interpreters.new_config('legacy')
2500 with new_interp('legacy') as interpid:
2501 config = _interpreters.get_config(interpid)
2502 self.assert_ns_equal(config, expected)
2503
2504 with self.subTest('custom'):
2505 orig = _interpreters.new_config(
2506 'empty',
2507 use_main_obmalloc=True,
2508 gil='shared',
2509 check_multi_interp_extensions=bool(Py_GIL_DISABLED),
2510 )
2511 with new_interp(orig) as interpid:
2512 config = _interpreters.get_config(interpid)
2513 self.assert_ns_equal(config, orig)
2514
2515
2516 @requires_subinterpreters
2517 class InterpreterIDTests(unittest.TestCase):
2518
2519 def add_interp_cleanup(self, interpid):
2520 def ensure_destroyed():
2521 try:
2522 _interpreters.destroy(interpid)
2523 except _interpreters.InterpreterNotFoundError:
2524 pass
2525 self.addCleanup(ensure_destroyed)
2526
2527 def new_interpreter(self):
2528 id = _interpreters.create()
2529 self.add_interp_cleanup(id)
2530 return id
2531
2532 def test_conversion_int(self):
2533 convert = _testinternalcapi.normalize_interp_id
2534 interpid = convert(10)
2535 self.assertEqual(interpid, 10)
2536
2537 def test_conversion_coerced(self):
2538 convert = _testinternalcapi.normalize_interp_id
2539 class MyInt(str):
2540 def __index__(self):
2541 return 10
2542 interpid = convert(MyInt())
2543 self.assertEqual(interpid, 10)
2544
2545 def test_conversion_from_interpreter(self):
2546 convert = _testinternalcapi.normalize_interp_id
2547 interpid = self.new_interpreter()
2548 converted = convert(interpid)
2549 self.assertEqual(converted, interpid)
2550
2551 def test_conversion_bad(self):
2552 convert = _testinternalcapi.normalize_interp_id
2553
2554 for badid in [
2555 object(),
2556 10.0,
2557 '10',
2558 b'10',
2559 ]:
2560 with self.subTest(f'bad: {badid!r}'):
2561 with self.assertRaises(TypeError):
2562 convert(badid)
2563
2564 badid = -1
2565 with self.subTest(f'bad: {badid!r}'):
2566 with self.assertRaises(ValueError):
2567 convert(badid)
2568
2569 badid = 2**64
2570 with self.subTest(f'bad: {badid!r}'):
2571 with self.assertRaises(OverflowError):
2572 convert(badid)
2573
2574 def test_lookup_exists(self):
2575 interpid = self.new_interpreter()
2576 self.assertTrue(
2577 _testinternalcapi.interpreter_exists(interpid))
2578
2579 def test_lookup_does_not_exist(self):
2580 interpid = _testinternalcapi.unused_interpreter_id()
2581 self.assertFalse(
2582 _testinternalcapi.interpreter_exists(interpid))
2583
2584 def test_lookup_destroyed(self):
2585 interpid = _interpreters.create()
2586 _interpreters.destroy(interpid)
2587 self.assertFalse(
2588 _testinternalcapi.interpreter_exists(interpid))
2589
2590 def get_refcount_helpers(self):
2591 return (
2592 _testinternalcapi.get_interpreter_refcount,
2593 (lambda id: _interpreters.incref(id, implieslink=False)),
2594 _interpreters.decref,
2595 )
2596
2597 def test_linked_lifecycle_does_not_exist(self):
2598 exists = _testinternalcapi.interpreter_exists
2599 is_linked = _testinternalcapi.interpreter_refcount_linked
2600 link = _testinternalcapi.link_interpreter_refcount
2601 unlink = _testinternalcapi.unlink_interpreter_refcount
2602 get_refcount, incref, decref = self.get_refcount_helpers()
2603
2604 with self.subTest('never existed'):
2605 interpid = _testinternalcapi.unused_interpreter_id()
2606 self.assertFalse(
2607 exists(interpid))
2608 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2609 is_linked(interpid)
2610 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2611 link(interpid)
2612 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2613 unlink(interpid)
2614 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2615 get_refcount(interpid)
2616 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2617 incref(interpid)
2618 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2619 decref(interpid)
2620
2621 with self.subTest('destroyed'):
2622 interpid = _interpreters.create()
2623 _interpreters.destroy(interpid)
2624 self.assertFalse(
2625 exists(interpid))
2626 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2627 is_linked(interpid)
2628 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2629 link(interpid)
2630 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2631 unlink(interpid)
2632 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2633 get_refcount(interpid)
2634 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2635 incref(interpid)
2636 with self.assertRaises(_interpreters.InterpreterNotFoundError):
2637 decref(interpid)
2638
2639 def test_linked_lifecycle_initial(self):
2640 is_linked = _testinternalcapi.interpreter_refcount_linked
2641 get_refcount, _, _ = self.get_refcount_helpers()
2642
2643 # A new interpreter will start out not linked, with a refcount of 0.
2644 interpid = self.new_interpreter()
2645 linked = is_linked(interpid)
2646 refcount = get_refcount(interpid)
2647
2648 self.assertFalse(linked)
2649 self.assertEqual(refcount, 0)
2650
2651 def test_linked_lifecycle_never_linked(self):
2652 exists = _testinternalcapi.interpreter_exists
2653 is_linked = _testinternalcapi.interpreter_refcount_linked
2654 get_refcount, incref, decref = self.get_refcount_helpers()
2655
2656 interpid = self.new_interpreter()
2657
2658 # Incref will not automatically link it.
2659 incref(interpid)
2660 self.assertFalse(
2661 is_linked(interpid))
2662 self.assertEqual(
2663 1, get_refcount(interpid))
2664
2665 # It isn't linked so it isn't destroyed.
2666 decref(interpid)
2667 self.assertTrue(
2668 exists(interpid))
2669 self.assertFalse(
2670 is_linked(interpid))
2671 self.assertEqual(
2672 0, get_refcount(interpid))
2673
2674 def test_linked_lifecycle_link_unlink(self):
2675 exists = _testinternalcapi.interpreter_exists
2676 is_linked = _testinternalcapi.interpreter_refcount_linked
2677 link = _testinternalcapi.link_interpreter_refcount
2678 unlink = _testinternalcapi.unlink_interpreter_refcount
2679
2680 interpid = self.new_interpreter()
2681
2682 # Linking at refcount 0 does not destroy the interpreter.
2683 link(interpid)
2684 self.assertTrue(
2685 exists(interpid))
2686 self.assertTrue(
2687 is_linked(interpid))
2688
2689 # Unlinking at refcount 0 does not destroy the interpreter.
2690 unlink(interpid)
2691 self.assertTrue(
2692 exists(interpid))
2693 self.assertFalse(
2694 is_linked(interpid))
2695
2696 def test_linked_lifecycle_link_incref_decref(self):
2697 exists = _testinternalcapi.interpreter_exists
2698 is_linked = _testinternalcapi.interpreter_refcount_linked
2699 link = _testinternalcapi.link_interpreter_refcount
2700 get_refcount, incref, decref = self.get_refcount_helpers()
2701
2702 interpid = self.new_interpreter()
2703
2704 # Linking it will not change the refcount.
2705 link(interpid)
2706 self.assertTrue(
2707 is_linked(interpid))
2708 self.assertEqual(
2709 0, get_refcount(interpid))
2710
2711 # Decref with a refcount of 0 is not allowed.
2712 incref(interpid)
2713 self.assertEqual(
2714 1, get_refcount(interpid))
2715
2716 # When linked, decref back to 0 destroys the interpreter.
2717 decref(interpid)
2718 self.assertFalse(
2719 exists(interpid))
2720
2721 def test_linked_lifecycle_incref_link(self):
2722 is_linked = _testinternalcapi.interpreter_refcount_linked
2723 link = _testinternalcapi.link_interpreter_refcount
2724 get_refcount, incref, _ = self.get_refcount_helpers()
2725
2726 interpid = self.new_interpreter()
2727
2728 incref(interpid)
2729 self.assertEqual(
2730 1, get_refcount(interpid))
2731
2732 # Linking it will not reset the refcount.
2733 link(interpid)
2734 self.assertTrue(
2735 is_linked(interpid))
2736 self.assertEqual(
2737 1, get_refcount(interpid))
2738
2739 def test_linked_lifecycle_link_incref_unlink_decref(self):
2740 exists = _testinternalcapi.interpreter_exists
2741 is_linked = _testinternalcapi.interpreter_refcount_linked
2742 link = _testinternalcapi.link_interpreter_refcount
2743 unlink = _testinternalcapi.unlink_interpreter_refcount
2744 get_refcount, incref, decref = self.get_refcount_helpers()
2745
2746 interpid = self.new_interpreter()
2747
2748 link(interpid)
2749 self.assertTrue(
2750 is_linked(interpid))
2751
2752 incref(interpid)
2753 self.assertEqual(
2754 1, get_refcount(interpid))
2755
2756 # Unlinking it will not change the refcount.
2757 unlink(interpid)
2758 self.assertFalse(
2759 is_linked(interpid))
2760 self.assertEqual(
2761 1, get_refcount(interpid))
2762
2763 # Unlinked: decref back to 0 does not destroys the interpreter.
2764 decref(interpid)
2765 self.assertTrue(
2766 exists(interpid))
2767 self.assertEqual(
2768 0, get_refcount(interpid))
2769
2770
2771 class BuiltinStaticTypesTests(unittest.TestCase):
2772
2773 TYPES = [
2774 object,
2775 type,
2776 int,
2777 str,
2778 dict,
2779 type(None),
2780 bool,
2781 BaseException,
2782 Exception,
2783 Warning,
2784 DeprecationWarning, # Warning subclass
2785 ]
2786
2787 def test_tp_bases_is_set(self):
2788 # PyTypeObject.tp_bases is documented as public API.
2789 # See https://github.com/python/cpython/issues/105020.
2790 for typeobj in self.TYPES:
2791 with self.subTest(typeobj):
2792 bases = _testcapi.type_get_tp_bases(typeobj)
2793 self.assertIsNot(bases, None)
2794
2795 def test_tp_mro_is_set(self):
2796 # PyTypeObject.tp_bases is documented as public API.
2797 # See https://github.com/python/cpython/issues/105020.
2798 for typeobj in self.TYPES:
2799 with self.subTest(typeobj):
2800 mro = _testcapi.type_get_tp_mro(typeobj)
2801 self.assertIsNot(mro, None)
2802
2803
2804 class TestStaticTypes(unittest.TestCase):
2805
2806 _has_run = False
2807
2808 @classmethod
2809 def setUpClass(cls):
2810 # The tests here don't play nice with our approach to refleak
2811 # detection, so we bail out in that case.
2812 if cls._has_run:
2813 raise unittest.SkipTest('these tests do not support re-running')
2814 cls._has_run = True
2815
2816 @contextlib.contextmanager
2817 def basic_static_type(self, *args):
2818 cls = _testcapi.get_basic_static_type(*args)
2819 yield cls
2820
2821 def test_pytype_ready_always_sets_tp_type(self):
2822 # The point of this test is to prevent something like
2823 # https://github.com/python/cpython/issues/104614
2824 # from happening again.
2825
2826 # First check when tp_base/tp_bases is *not* set before PyType_Ready().
2827 with self.basic_static_type() as cls:
2828 self.assertIs(cls.__base__, object);
2829 self.assertEqual(cls.__bases__, (object,));
2830 self.assertIs(type(cls), type(object));
2831
2832 # Then check when we *do* set tp_base/tp_bases first.
2833 with self.basic_static_type(object) as cls:
2834 self.assertIs(cls.__base__, object);
2835 self.assertEqual(cls.__bases__, (object,));
2836 self.assertIs(type(cls), type(object));
2837
2838
2839 class TestThreadState(unittest.TestCase):
2840
2841 @threading_helper.reap_threads
2842 @threading_helper.requires_working_threading()
2843 def test_thread_state(self):
2844 # some extra thread-state tests driven via _testcapi
2845 def target():
2846 idents = []
2847
2848 def callback():
2849 idents.append(threading.get_ident())
2850
2851 _testcapi._test_thread_state(callback)
2852 a = b = callback
2853 time.sleep(1)
2854 # Check our main thread is in the list exactly 3 times.
2855 self.assertEqual(idents.count(threading.get_ident()), 3,
2856 "Couldn't find main thread correctly in the list")
2857
2858 target()
2859 t = threading.Thread(target=target)
2860 t.start()
2861 t.join()
2862
2863 @threading_helper.reap_threads
2864 @threading_helper.requires_working_threading()
2865 def test_thread_gilstate_in_clear(self):
2866 # See https://github.com/python/cpython/issues/119585
2867 class C:
2868 def __del__(self):
2869 _testcapi.gilstate_ensure_release()
2870
2871 # Thread-local variables are destroyed in `PyThreadState_Clear()`.
2872 local_var = threading.local()
2873
2874 def callback():
2875 local_var.x = C()
2876
2877 _testcapi._test_thread_state(callback)
2878
2879 @threading_helper.reap_threads
2880 @threading_helper.requires_working_threading()
2881 def test_gilstate_ensure_no_deadlock(self):
2882 # See https://github.com/python/cpython/issues/96071
2883 code = textwrap.dedent("""
2884 import _testcapi
2885
2886 def callback():
2887 print('callback called')
2888
2889 _testcapi._test_thread_state(callback)
2890 """)
2891 ret = assert_python_ok('-X', 'tracemalloc', '-c', code)
2892 self.assertIn(b'callback called', ret.out)
2893
2894 def test_gilstate_matches_current(self):
2895 _testcapi.test_current_tstate_matches()
2896
2897
2898 def get_test_funcs(mod, exclude_prefix=None):
2899 funcs = {}
2900 for name in dir(mod):
2901 if not name.startswith('test_'):
2902 continue
2903 if exclude_prefix is not None and name.startswith(exclude_prefix):
2904 continue
2905 funcs[name] = getattr(mod, name)
2906 return funcs
2907
2908
2909 class Test_testcapi(unittest.TestCase):
2910 locals().update(get_test_funcs(_testcapi))
2911
2912 # Suppress warning from PyUnicode_FromUnicode().
2913 @warnings_helper.ignore_warnings(category=DeprecationWarning)
2914 def test_widechar(self):
2915 _testlimitedcapi.test_widechar()
2916
2917 def test_version_api_data(self):
2918 self.assertEqual(_testcapi.Py_Version, sys.hexversion)
2919
2920
2921 class Test_testlimitedcapi(unittest.TestCase):
2922 locals().update(get_test_funcs(_testlimitedcapi))
2923
2924
2925 class Test_testinternalcapi(unittest.TestCase):
2926 locals().update(get_test_funcs(_testinternalcapi,
2927 exclude_prefix='test_lock_'))
2928
2929
2930 @threading_helper.requires_working_threading()
2931 class Test_PyLock(unittest.TestCase):
2932 locals().update((name, getattr(_testinternalcapi, name))
2933 for name in dir(_testinternalcapi)
2934 if name.startswith('test_lock_'))
2935
2936
2937 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
2938 class Test_ModuleStateAccess(unittest.TestCase):
2939 """Test access to module start (PEP 573)"""
2940
2941 # The C part of the tests lives in _testmultiphase, in a module called
2942 # _testmultiphase_meth_state_access.
2943 # This module has multi-phase initialization, unlike _testcapi.
2944
2945 def setUp(self):
2946 fullname = '_testmultiphase_meth_state_access' # XXX
2947 origin = importlib.util.find_spec('_testmultiphase').origin
2948 # Apple extensions must be distributed as frameworks. This requires
2949 # a specialist loader.
2950 if support.is_apple_mobile:
2951 loader = importlib.machinery.AppleFrameworkLoader(fullname, origin)
2952 else:
2953 loader = importlib.machinery.ExtensionFileLoader(fullname, origin)
2954 spec = importlib.util.spec_from_loader(fullname, loader)
2955 module = importlib.util.module_from_spec(spec)
2956 loader.exec_module(module)
2957 self.module = module
2958
2959 def test_subclass_get_module(self):
2960 """PyType_GetModule for defining_class"""
2961 class StateAccessType_Subclass(self.module.StateAccessType):
2962 pass
2963
2964 instance = StateAccessType_Subclass()
2965 self.assertIs(instance.get_defining_module(), self.module)
2966
2967 def test_subclass_get_module_with_super(self):
2968 class StateAccessType_Subclass(self.module.StateAccessType):
2969 def get_defining_module(self):
2970 return super().get_defining_module()
2971
2972 instance = StateAccessType_Subclass()
2973 self.assertIs(instance.get_defining_module(), self.module)
2974
2975 def test_state_access(self):
2976 """Checks methods defined with and without argument clinic
2977
2978 This tests a no-arg method (get_count) and a method with
2979 both a positional and keyword argument.
2980 """
2981
2982 a = self.module.StateAccessType()
2983 b = self.module.StateAccessType()
2984
2985 methods = {
2986 'clinic': a.increment_count_clinic,
2987 'noclinic': a.increment_count_noclinic,
2988 }
2989
2990 for name, increment_count in methods.items():
2991 with self.subTest(name):
2992 self.assertEqual(a.get_count(), b.get_count())
2993 self.assertEqual(a.get_count(), 0)
2994
2995 increment_count()
2996 self.assertEqual(a.get_count(), b.get_count())
2997 self.assertEqual(a.get_count(), 1)
2998
2999 increment_count(3)
3000 self.assertEqual(a.get_count(), b.get_count())
3001 self.assertEqual(a.get_count(), 4)
3002
3003 increment_count(-2, twice=True)
3004 self.assertEqual(a.get_count(), b.get_count())
3005 self.assertEqual(a.get_count(), 0)
3006
3007 with self.assertRaises(TypeError):
3008 increment_count(thrice=3)
3009
3010 with self.assertRaises(TypeError):
3011 increment_count(1, 2, 3)
3012
3013 def test_get_module_bad_def(self):
3014 # PyType_GetModuleByDef fails gracefully if it doesn't
3015 # find what it's looking for.
3016 # see bpo-46433
3017 instance = self.module.StateAccessType()
3018 with self.assertRaises(TypeError):
3019 instance.getmodulebydef_bad_def()
3020
3021 def test_get_module_static_in_mro(self):
3022 # Here, the class PyType_GetModuleByDef is looking for
3023 # appears in the MRO after a static type (Exception).
3024 # see bpo-46433
3025 class Subclass(BaseException, self.module.StateAccessType):
3026 pass
3027 self.assertIs(Subclass().get_defining_module(), self.module)
3028
3029
3030 class TestInternalFrameApi(unittest.TestCase):
3031
3032 @staticmethod
3033 def func():
3034 return sys._getframe()
3035
3036 def test_code(self):
3037 frame = self.func()
3038 code = _testinternalcapi.iframe_getcode(frame)
3039 self.assertIs(code, self.func.__code__)
3040
3041 def test_lasti(self):
3042 frame = self.func()
3043 lasti = _testinternalcapi.iframe_getlasti(frame)
3044 self.assertGreater(lasti, 0)
3045 self.assertLess(lasti, len(self.func.__code__.co_code))
3046
3047 def test_line(self):
3048 frame = self.func()
3049 line = _testinternalcapi.iframe_getline(frame)
3050 firstline = self.func.__code__.co_firstlineno
3051 self.assertEqual(line, firstline + 2)
3052
3053
3054 SUFFICIENT_TO_DEOPT_AND_SPECIALIZE = 100
3055
3056 class Test_Pep523API(unittest.TestCase):
3057
3058 def do_test(self, func, names):
3059 actual_calls = []
3060 start = SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
3061 count = start + SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
3062 try:
3063 for i in range(count):
3064 if i == start:
3065 _testinternalcapi.set_eval_frame_record(actual_calls)
3066 func()
3067 finally:
3068 _testinternalcapi.set_eval_frame_default()
3069 expected_calls = names * SUFFICIENT_TO_DEOPT_AND_SPECIALIZE
3070 self.assertEqual(len(expected_calls), len(actual_calls))
3071 for expected, actual in zip(expected_calls, actual_calls, strict=True):
3072 self.assertEqual(expected, actual)
3073
3074 def test_inlined_binary_subscr(self):
3075 class C:
3076 def __getitem__(self, other):
3077 return None
3078 def func():
3079 C()[42]
3080 names = ["func", "__getitem__"]
3081 self.do_test(func, names)
3082
3083 def test_inlined_call(self):
3084 def inner(x=42):
3085 pass
3086 def func():
3087 inner()
3088 inner(42)
3089 names = ["func", "inner", "inner"]
3090 self.do_test(func, names)
3091
3092 def test_inlined_call_function_ex(self):
3093 def inner(x):
3094 pass
3095 def func():
3096 inner(*[42])
3097 names = ["func", "inner"]
3098 self.do_test(func, names)
3099
3100 def test_inlined_for_iter(self):
3101 def gen():
3102 yield 42
3103 def func():
3104 for _ in gen():
3105 pass
3106 names = ["func", "gen", "gen", "gen"]
3107 self.do_test(func, names)
3108
3109 def test_inlined_load_attr(self):
3110 class C:
3111 @property
3112 def a(self):
3113 return 42
3114 class D:
3115 def __getattribute__(self, name):
3116 return 42
3117 def func():
3118 C().a
3119 D().a
3120 names = ["func", "a", "__getattribute__"]
3121 self.do_test(func, names)
3122
3123 def test_inlined_send(self):
3124 def inner():
3125 yield 42
3126 def outer():
3127 yield from inner()
3128 def func():
3129 list(outer())
3130 names = ["func", "outer", "outer", "inner", "inner", "outer", "inner"]
3131 self.do_test(func, names)
3132
3133
3134 @unittest.skipUnless(support.Py_GIL_DISABLED, 'need Py_GIL_DISABLED')
3135 class TestPyThreadId(unittest.TestCase):
3136 def test_py_thread_id(self):
3137 # gh-112535: Test _Py_ThreadId(): make sure that thread identifiers
3138 # in a few threads are unique
3139 py_thread_id = _testinternalcapi.py_thread_id
3140 short_sleep = 0.010
3141
3142 class GetThreadId(threading.Thread):
3143 def __init__(self):
3144 super().__init__()
3145 self.get_lock = threading.Lock()
3146 self.get_lock.acquire()
3147 self.started_lock = threading.Event()
3148 self.py_tid = None
3149
3150 def run(self):
3151 self.started_lock.set()
3152 self.get_lock.acquire()
3153 self.py_tid = py_thread_id()
3154 time.sleep(short_sleep)
3155 self.py_tid2 = py_thread_id()
3156
3157 nthread = 5
3158 threads = [GetThreadId() for _ in range(nthread)]
3159
3160 # first make run sure that all threads are running
3161 for thread in threads:
3162 thread.start()
3163 for thread in threads:
3164 thread.started_lock.wait()
3165
3166 # call _Py_ThreadId() in the main thread
3167 py_thread_ids = [py_thread_id()]
3168
3169 # now call _Py_ThreadId() in each thread
3170 for thread in threads:
3171 thread.get_lock.release()
3172
3173 # call _Py_ThreadId() in each thread and wait until threads complete
3174 for thread in threads:
3175 thread.join()
3176 py_thread_ids.append(thread.py_tid)
3177 # _PyThread_Id() should not change for a given thread.
3178 # For example, it should remain the same after a short sleep.
3179 self.assertEqual(thread.py_tid2, thread.py_tid)
3180
3181 # make sure that all _Py_ThreadId() are unique
3182 for tid in py_thread_ids:
3183 self.assertIsInstance(tid, int)
3184 self.assertGreater(tid, 0)
3185 self.assertEqual(len(set(py_thread_ids)), len(py_thread_ids),
3186 py_thread_ids)
3187
3188
3189 class TestCEval(unittest.TestCase):
3190 def test_ceval_decref(self):
3191 code = textwrap.dedent("""
3192 import _testcapi
3193 _testcapi.toggle_reftrace_printer(True)
3194 l1 = []
3195 l2 = []
3196 del l1
3197 del l2
3198 _testcapi.toggle_reftrace_printer(False)
3199 """)
3200 _, out, _ = assert_python_ok("-c", code)
3201 lines = out.decode("utf-8").splitlines()
3202 self.assertEqual(lines.count("CREATE list"), 2)
3203 self.assertEqual(lines.count("DESTROY list"), 2)
3204
3205
3206 if __name__ == "__main__":
3207 unittest.main()